From aeec75cba38b6a2f32080c71f6b8cd21d03f8170 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Mon, 3 Aug 2026 17:20:44 +0800 Subject: [PATCH 1/4] Harden Classic COM ABI and add coclass and dual-module JS projections --- bindings/js/src/com.rs | 277 ++++++++++-- bindings/js/src/lib.rs | 56 ++- crates/dynwinrt/src/call.rs | 20 +- crates/dynwinrt/src/com.rs | 421 ++++++++++++++++-- crates/dynwinrt/src/native_call.rs | 293 +++++++++++- docs/classic-com-support.md | 79 +++- tests/e2e_test.ps1 | 5 +- tests/runners/com/electron-hwnd-buffer.mjs | 5 +- tests/runners/com/file-open-dialog.mjs | 6 +- tests/runners/com/file-operation.mjs | 6 +- tests/runners/com/module-commonjs.cjs | 19 + tests/runners/com/persist-file.mjs | 20 + tests/runners/com/shelllink-buffer.mjs | 44 -- tests/runners/com/taskbarlist.mjs | 34 +- tests/runners/com/wic-imaging-factory.mjs | 2 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 110 ++++- .../src/codegen/com/javascript/naming.rs | 41 +- .../src/codegen/com/javascript/render.rs | 333 ++++++++++++-- .../codegen/com/javascript/render_tests.rs | 171 ++++++- .../src/codegen/com/javascript/types.rs | 8 + tools/dynwinrt-codegen/src/codegen/com/mod.rs | 10 +- .../src/codegen/com/project/mod.rs | 256 +++++++++-- .../src/codegen/com/project/types.rs | 25 +- tools/dynwinrt-codegen/src/codegen/package.rs | 24 +- .../javascript/render/javascript/commonjs.rs | 100 ++++- .../winrt/javascript/render/javascript/mod.rs | 2 +- tools/dynwinrt-codegen/src/com_metadata.rs | 307 ++++++++----- tools/dynwinrt-codegen/src/main.rs | 148 ++++-- .../IDataTransferManagerInterop.d.ts | 9 +- .../IDataTransferManagerInterop.js | 23 +- .../snapshots/itaskbarlist3/ITaskbarList.d.ts | 25 ++ .../snapshots/itaskbarlist3/ITaskbarList.js | 51 +++ .../itaskbarlist3/ITaskbarList2.d.ts | 27 ++ .../snapshots/itaskbarlist3/ITaskbarList2.js | 56 +++ .../itaskbarlist3/ITaskbarList3.d.ts | 32 +- .../snapshots/itaskbarlist3/ITaskbarList3.js | 86 ++-- .../itaskbarlist3/ITaskbarList4.d.ts | 61 +++ .../snapshots/itaskbarlist3/ITaskbarList4.js | 123 +++++ .../snapshots/itaskbarlist3/STPFLAG.d.ts | 9 + .../tests/snapshots/itaskbarlist3/STPFLAG.js | 10 + .../tests/snapshots/itaskbarlist3/TBPFLAG.js | 4 +- .../snapshots/itaskbarlist3/TaskbarList.d.ts | 12 + .../snapshots/itaskbarlist3/TaskbarList.js | 30 ++ .../dynwinrt-codegen/tests/win32_com_test.rs | 401 ++++++++++++++--- 44 files changed, 3224 insertions(+), 557 deletions(-) create mode 100644 tests/runners/com/module-commonjs.cjs create mode 100644 tests/runners/com/persist-file.mjs delete mode 100644 tests/runners/com/shelllink-buffer.mjs create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.js create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 9f3882d9..ce4f84e8 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use napi::JsValue; use napi::bindgen_prelude::{BigInt, FromNapiValue, ToNapiValue, Unknown}; +use napi::JsValue; use napi_derive::napi; -use windows::core::{GUID, Interface as _}; +use windows::core::{Interface as _, GUID}; -use super::{DynWinRTValue, TABLE, WinGUID}; +use super::{DynWinRTValue, WinGUID, TABLE}; #[allow(dead_code)] pub(super) enum NativePointerOwner { @@ -18,13 +18,18 @@ pub(super) enum NativePointerOwner { }, CoTaskMem(*mut std::ffi::c_void), Guid(*mut GUID), + WideString(Box<[u16]>), + AnsiString(Box<[u8]>), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum PointerProvenance { None, Borrowed, - NativeOutput, + UnclassifiedOutput, + ComOutput, + CoTaskMemOutput, + BstrOutput, } impl NativePointerOwner { @@ -115,6 +120,16 @@ fn co_create_instance(clsid: String, iid: &WinGUID) -> napi::Result napi::Result> { + const E_NOINTERFACE: windows::core::HRESULT = windows::core::HRESULT(0x80004002u32 as i32); + + match value.0.cast(&iid.0) { + Ok(value) => Ok(Some(DynWinRTValue::new(value))), + Err(dynwinrt::Error::WindowsError(error)) if error.code() == E_NOINTERFACE => Ok(None), + Err(error) => Err(napi::Error::from_reason(error.message())), + } +} + fn create_test_hwnd() -> napi::Result { use std::sync::atomic::{AtomicUsize, Ordering}; use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, WINDOW_EX_STYLE, WS_POPUP}; @@ -153,6 +168,29 @@ struct Uint8ArrayInfo { length: usize, } +fn validate_wide_string_bytes(bytes: &[u8]) -> napi::Result<()> { + if bytes.len() < 2 || bytes.len() % 2 != 0 { + return Err(napi::Error::from_reason( + "wideStringPointer(): Buffer/Uint8Array must have an even byte length and include a UTF-16 NUL terminator", + )); + } + if bytes[bytes.len() - 2..] != [0, 0] { + return Err(napi::Error::from_reason( + "wideStringPointer(): Buffer/Uint8Array must end with a UTF-16 NUL terminator", + )); + } + Ok(()) +} + +fn validate_ansi_string_bytes(bytes: &[u8]) -> napi::Result<()> { + if bytes.last() != Some(&0) { + return Err(napi::Error::from_reason( + "ansiStringPointer(): Buffer/Uint8Array must end with a NUL terminator", + )); + } + Ok(()) +} + fn uint8_array_info( env: napi::sys::napi_env, raw: napi::sys::napi_value, @@ -282,6 +320,68 @@ fn pointer(value: Unknown) -> napi::Result { )) } +fn wide_string_pointer(value: Unknown) -> napi::Result { + use napi::sys; + + let env = value.value().env; + let raw = value.value().value; + let mut value_type = sys::ValueType::napi_undefined; + unsafe { sys::napi_typeof(env, raw, &mut value_type) }; + if value_type == sys::ValueType::napi_string { + let text = unsafe { String::from_napi_value(env, raw) }?; + let mut storage = text + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>() + .into_boxed_slice(); + let ptr = storage.as_mut_ptr().cast(); + return Ok(DynWinRTValue::with_pointer_owner( + dynwinrt::WinRTValue::RawPtr(ptr), + NativePointerOwner::WideString(storage), + )); + } + if let Some(array) = uint8_array_info(env, raw)? { + if !array.data.is_null() && (array.data as usize) % std::mem::align_of::() != 0 { + return Err(napi::Error::from_reason( + "wideStringPointer(): Buffer/Uint8Array backing address must be aligned for UTF-16", + )); + } + let bytes = unsafe { std::slice::from_raw_parts(array.data, array.length) }; + validate_wide_string_bytes(bytes)?; + } + pointer(value) +} + +fn ansi_string_pointer(value: Unknown) -> napi::Result { + use napi::sys; + + let env = value.value().env; + let raw = value.value().value; + let mut value_type = sys::ValueType::napi_undefined; + unsafe { sys::napi_typeof(env, raw, &mut value_type) }; + if value_type == sys::ValueType::napi_string { + let text = unsafe { String::from_napi_value(env, raw) }?; + if !text.is_ascii() { + return Err(napi::Error::from_reason( + "ansiStringPointer(): non-ASCII strings require an explicitly encoded NUL-terminated Buffer/Uint8Array", + )); + } + let mut storage = text.into_bytes(); + storage.push(0); + let mut storage = storage.into_boxed_slice(); + let ptr = storage.as_mut_ptr().cast(); + return Ok(DynWinRTValue::with_pointer_owner( + dynwinrt::WinRTValue::RawPtr(ptr), + NativePointerOwner::AnsiString(storage), + )); + } + if let Some(array) = uint8_array_info(env, raw)? { + let bytes = unsafe { std::slice::from_raw_parts(array.data, array.length) }; + validate_ansi_string_bytes(bytes)?; + } + pointer(value) +} + fn handle_value(value: Unknown) -> napi::Result { use napi::sys; @@ -342,7 +442,7 @@ fn adopt_com_pointer( value: &mut DynWinRTValue, iid: Option<&WinGUID>, ) -> napi::Result { - let ptr = take_native_output_pointer(value, "COM interface")?; + let ptr = take_native_output_pointer(value, PointerProvenance::ComOutput, "COM interface")?; let adopted = unsafe { dynwinrt::com::adopt_com_pointer(ptr) }; match iid { Some(iid) => adopted @@ -354,7 +454,11 @@ fn adopt_com_pointer( } fn adopt_co_task_mem_pointer(value: &mut DynWinRTValue) -> napi::Result { - let ptr = take_native_output_pointer(value, "CoTaskMem allocation")?; + let ptr = take_native_output_pointer( + value, + PointerProvenance::CoTaskMemOutput, + "CoTaskMem allocation", + )?; if ptr.is_null() { return Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)); } @@ -384,7 +488,7 @@ fn as_pointer_bigint(value: &DynWinRTValue) -> napi::Result { } fn take_co_task_mem_wide_string(value: &mut DynWinRTValue) -> napi::Result { - let ptr = take_native_output_pointer(value, "wide-string")?; + let ptr = take_native_output_pointer(value, PointerProvenance::CoTaskMemOutput, "wide-string")?; if ptr.is_null() { return Ok(String::new()); } @@ -395,7 +499,7 @@ fn take_co_task_mem_wide_string(value: &mut DynWinRTValue) -> napi::Result napi::Result { - let ptr = take_native_output_pointer(value, "ANSI-string")?; + let ptr = take_native_output_pointer(value, PointerProvenance::CoTaskMemOutput, "ANSI-string")?; if ptr.is_null() { return Ok(String::new()); } @@ -406,7 +510,7 @@ fn take_co_task_mem_ansi_string(value: &mut DynWinRTValue) -> napi::Result napi::Result { - let ptr = take_native_output_pointer(value, "BSTR")?; + let ptr = take_native_output_pointer(value, PointerProvenance::BstrOutput, "BSTR")?; if ptr.is_null() { return Ok(String::new()); } @@ -423,6 +527,7 @@ fn validate_pointer_owner(value: &DynWinRTValue) -> napi::Result<()> { fn take_native_output_pointer( value: &mut DynWinRTValue, + expected: PointerProvenance, description: &str, ) -> napi::Result<*mut std::ffi::c_void> { if value.1.is_some() { @@ -430,9 +535,10 @@ fn take_native_output_pointer( "Cannot consume an owner-backed {description} pointer" ))); } - if value.2 != PointerProvenance::NativeOutput { + if value.2 != expected { return Err(napi::Error::from_reason(format!( - "Cannot adopt a borrowed {description} pointer; only owned native outputs may be consumed" + "Cannot consume {description} pointer with {:?} provenance; expected {:?}", + value.2, expected ))); } match std::mem::replace(&mut value.0, dynwinrt::WinRTValue::Null) { @@ -524,6 +630,21 @@ impl DynComInterface { Self(self.0.clone().add_method(&name, signature.0.clone())) } + #[napi] + pub fn add_method_at( + &self, + vtable_index: u32, + name: String, + signature: &DynComMethodSig, + ) -> napi::Result { + self + .0 + .clone() + .add_method_at(vtable_index as usize, &name, signature.0.clone()) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + #[napi] pub fn method(&self, vtable_index: i32) -> napi::Result { self @@ -570,16 +691,15 @@ impl DynComMethodHandle { validate_pointer_owner(arg)?; } let args = args.iter().map(|arg| arg.0.clone()).collect::>(); - let results = self + let mut results = self .0 - .invoke(raw, &args) + .invoke_with_output_kinds(raw, &args) .map_err(|error| napi::Error::from_reason(error.message()))?; - Ok(DynWinRTValue::from_com_result( - results - .into_iter() - .next() - .unwrap_or(dynwinrt::WinRTValue::I32(0)), - )) + let (value, kind) = results.drain(..).next().unwrap_or(( + dynwinrt::WinRTValue::I32(0), + dynwinrt::com::PointerOutputKind::None, + )); + Ok(DynWinRTValue::from_com_result(value, kind)) } #[napi] @@ -599,11 +719,11 @@ impl DynComMethodHandle { let args = args.iter().map(|arg| arg.0.clone()).collect::>(); self .0 - .invoke(raw, &args) + .invoke_with_output_kinds(raw, &args) .map(|results| { results .into_iter() - .map(DynWinRTValue::from_com_result) + .map(|(value, kind)| DynWinRTValue::from_com_result(value, kind)) .collect() }) .map_err(|error| napi::Error::from_reason(error.message())) @@ -751,6 +871,21 @@ impl DynCom { DynComType(dynwinrt::com::Type::pointer()) } + #[napi] + pub fn owned_com_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::owned_com_pointer()) + } + + #[napi] + pub fn co_task_mem_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::co_task_mem_pointer()) + } + + #[napi] + pub fn bstr_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::bstr_pointer()) + } + #[napi] pub fn interface_type(iid: &WinGUID) -> DynComType { DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) @@ -882,6 +1017,11 @@ impl DynCom { self::co_create_instance(clsid, iid) } + #[napi] + pub fn try_cast(value: &DynWinRTValue, iid: &WinGUID) -> napi::Result> { + self::try_cast(value, iid) + } + #[napi] pub fn pointer( #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array | null | undefined")] @@ -890,6 +1030,22 @@ impl DynCom { self::pointer(value) } + #[napi] + pub fn wide_string_pointer( + #[napi(ts_arg_type = "string | bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::wide_string_pointer(value) + } + + #[napi] + pub fn ansi_string_pointer( + #[napi(ts_arg_type = "string | bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::ansi_string_pointer(value) + } + #[napi] pub fn handle_value( #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array")] value: Unknown, @@ -1019,6 +1175,15 @@ impl DynCom { mod tests { use super::*; + #[test] + fn string_pointer_buffers_require_matching_nul_terminators() { + assert!(validate_wide_string_bytes(&[b'a', 0, 0, 0]).is_ok()); + assert!(validate_wide_string_bytes(&[b'a', 0]).is_err()); + assert!(validate_wide_string_bytes(&[b'a', 0, 0]).is_err()); + assert!(validate_ansi_string_bytes(b"text\0").is_ok()); + assert!(validate_ansi_string_bytes(b"text").is_err()); + } + #[test] fn takes_and_clears_cotaskmem_wide_string() { let text = "dynwinrt"; @@ -1029,7 +1194,10 @@ mod tests { unsafe { std::ptr::copy_nonoverlapping(wide.as_ptr(), ptr.cast::(), wide.len()); } - let mut value = DynWinRTValue::from_com_result(dynwinrt::WinRTValue::RawPtr(ptr)); + let mut value = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(ptr), + dynwinrt::com::PointerOutputKind::CoTaskMem, + ); assert_eq!(take_co_task_mem_wide_string(&mut value).unwrap(), text); assert!(matches!(value.0, dynwinrt::WinRTValue::Null)); @@ -1038,11 +1206,17 @@ mod tests { #[test] fn consuming_native_output_pointer_clears_source_value() { let ptr = 0x1234usize as *mut std::ffi::c_void; - let mut value = DynWinRTValue::from_com_result(dynwinrt::WinRTValue::RawPtr(ptr)); + let mut value = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(ptr), + dynwinrt::com::PointerOutputKind::Com, + ); - assert_eq!(take_native_output_pointer(&mut value, "test").unwrap(), ptr); + assert_eq!( + take_native_output_pointer(&mut value, PointerProvenance::ComOutput, "test").unwrap(), + ptr + ); assert!(matches!(value.0, dynwinrt::WinRTValue::Null)); - assert!(take_native_output_pointer(&mut value, "test").is_err()); + assert!(take_native_output_pointer(&mut value, PointerProvenance::ComOutput, "test").is_err()); } #[test] @@ -1050,20 +1224,36 @@ mod tests { let ptr = 0x1234usize as *mut std::ffi::c_void; let mut value = DynWinRTValue::with_borrowed_pointer(dynwinrt::WinRTValue::RawPtr(ptr)); - let error = take_native_output_pointer(&mut value, "COM interface").unwrap_err(); - assert!( - error - .reason - .contains("Cannot adopt a borrowed COM interface") + let error = + take_native_output_pointer(&mut value, PointerProvenance::ComOutput, "COM interface") + .unwrap_err(); + assert!(error.reason.contains("Borrowed")); + assert!(matches!(value.0, dynwinrt::WinRTValue::RawPtr(raw) if raw == ptr)); + } + + #[test] + fn pointer_output_requires_the_exact_allocator_provenance() { + let ptr = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(1) }; + assert!(!ptr.is_null()); + let mut value = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(ptr), + dynwinrt::com::PointerOutputKind::CoTaskMem, ); + + let error = + take_native_output_pointer(&mut value, PointerProvenance::ComOutput, "COM interface") + .unwrap_err(); + assert!(error.reason.contains("CoTaskMemOutput")); assert!(matches!(value.0, dynwinrt::WinRTValue::RawPtr(raw) if raw == ptr)); } #[test] fn takes_and_frees_bstr() { let raw = windows::core::BSTR::from("dynwinrt").into_raw(); - let mut value = - DynWinRTValue::from_com_result(dynwinrt::WinRTValue::RawPtr(raw as *mut std::ffi::c_void)); + let mut value = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(raw as *mut std::ffi::c_void), + dynwinrt::com::PointerOutputKind::Bstr, + ); assert_eq!(take_bstr(&mut value).unwrap(), "dynwinrt"); assert!(matches!(value.0, dynwinrt::WinRTValue::Null)); @@ -1076,11 +1266,24 @@ mod tests { let value = co_create_instance("00021401-0000-0000-c000-000000000046".into(), &iid).unwrap(); let error = as_pointer_bigint(&value).unwrap_err(); - assert!( - error - .reason - .contains("Managed COM objects cannot be exported") - ); + assert!(error + .reason + .contains("Managed COM objects cannot be exported")); + } + + #[test] + fn try_cast_distinguishes_no_interface_from_other_errors() { + dynwinrt::com::initialize_apartment(dynwinrt::com::ApartmentType::MultiThreaded).unwrap(); + let shell_link_iid = WinGUID(GUID::from_u128(0x000214f9_0000_0000_c000_000000000046)); + let value = co_create_instance( + "00021401-0000-0000-c000-000000000046".into(), + &shell_link_iid, + ) + .unwrap(); + + assert!(try_cast(&value, &shell_link_iid).unwrap().is_some()); + let unsupported = WinGUID(GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee)); + assert!(try_cast(&value, &unsupported).unwrap().is_none()); } #[test] diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index bbdb7686..0ab45e88 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -11,11 +11,11 @@ use std::{ }; use dynwinrt; -use napi::Env; use napi::bindgen_prelude::{BigInt, PromiseRaw}; use napi::threadsafe_function::ThreadsafeFunctionCallMode; +use napi::Env; use napi_derive::napi; -use windows::core::{HSTRING, IUnknown, Interface}; +use windows::core::{IUnknown, Interface, HSTRING}; mod com; pub use com::{DynCom, DynComInterface, DynComMethodHandle, DynComMethodSig, DynComType}; @@ -105,7 +105,7 @@ pub fn get_winappsdk_resource_pri_path() -> napi::Result { #[napi] pub fn ro_initialize(apartment_type: Option) { use windows::Win32::System::WinRT::{ - RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, RoInitialize, + RoInitialize, RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, }; let init_type = match apartment_type.unwrap_or(1) { 0 => RO_INIT_SINGLETHREADED, @@ -596,18 +596,57 @@ impl DynWinRTValue { Self(value, None, com::PointerProvenance::Borrowed) } - fn from_com_result(value: dynwinrt::WinRTValue) -> Self { + fn from_com_result( + value: dynwinrt::WinRTValue, + output_kind: dynwinrt::com::PointerOutputKind, + ) -> Self { let provenance = if matches!(value, dynwinrt::WinRTValue::RawPtr(_)) { - com::PointerProvenance::NativeOutput + match output_kind { + dynwinrt::com::PointerOutputKind::None | dynwinrt::com::PointerOutputKind::Unclassified => { + com::PointerProvenance::UnclassifiedOutput + } + dynwinrt::com::PointerOutputKind::Com => com::PointerProvenance::ComOutput, + dynwinrt::com::PointerOutputKind::CoTaskMem => com::PointerProvenance::CoTaskMemOutput, + dynwinrt::com::PointerOutputKind::Bstr => com::PointerProvenance::BstrOutput, + } } else { com::PointerProvenance::None }; Self(value, None, provenance) } + + fn release_native_pointer_output(&mut self) { + let ptr = match &self.0 { + dynwinrt::WinRTValue::RawPtr(ptr) => *ptr, + _ => return, + }; + let provenance = self.2; + self.0 = dynwinrt::WinRTValue::Null; + self.2 = com::PointerProvenance::None; + if ptr.is_null() { + return; + } + match provenance { + com::PointerProvenance::ComOutput => { + drop(unsafe { IUnknown::from_raw(ptr) }); + } + com::PointerProvenance::CoTaskMemOutput => unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(ptr)); + }, + com::PointerProvenance::BstrOutput => { + drop(unsafe { windows::core::BSTR::from_raw(ptr.cast()) }); + } + com::PointerProvenance::None + | com::PointerProvenance::Borrowed + | com::PointerProvenance::UnclassifiedOutput => {} + } + } } impl Drop for DynWinRTValue { fn drop(&mut self) { + self.release_native_pointer_output(); + // After Application.Start returns, XAML has already torn down its thread // state. Leaking late projected COM references is safer than releasing // them into a destroyed DXamlCore; normal application teardown must call @@ -623,6 +662,7 @@ impl Drop for DynWinRTValue { impl DynWinRTValue { #[napi] pub fn release(&mut self) { + self.release_native_pointer_output(); self.0 = dynwinrt::WinRTValue::Null; self.1 = None; self.2 = com::PointerProvenance::None; @@ -1491,8 +1531,8 @@ pub fn has_package_identity() -> bool { pub fn get_computer_name() -> napi::Result { #[cfg(target_os = "windows")] { - use windows::Win32::System::WindowsProgramming::GetComputerNameW; use windows::core::PWSTR; + use windows::Win32::System::WindowsProgramming::GetComputerNameW; let mut buffer = [0u16; 256]; let mut size = buffer.len() as u32; @@ -1695,8 +1735,8 @@ impl DynWinRtDelegate { #[napi(ts_arg_type = "(...args: DynWinRTValue[]) => void")] callback: napi::bindgen_prelude::Function<'static, Vec, ()>, ) -> napi::Result { - use napi::JsValue; use napi::bindgen_prelude::ToNapiValue; + use napi::JsValue; use windows::Win32::System::Threading::GetCurrentThreadId; // Track the thread we were registered on. WinRT delegate callbacks that @@ -1915,8 +1955,8 @@ impl DynWinRtElementFactory { #[napi(ts_arg_type = "(args: DynWinRtValue) => void")] recycle_element: ElementFactoryRecycleFunction, ) -> napi::Result { - use napi::JsValue; use napi::bindgen_prelude::{FromNapiValue, ToNapiValue}; + use napi::JsValue; use windows::Win32::System::Threading::GetCurrentThreadId; const E_FAIL: windows::core::HRESULT = windows::core::HRESULT(0x80004005u32 as i32); diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index cabf9d40..0717ecfb 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -211,6 +211,16 @@ fn input_abi_value(value: &WinRTValue) -> windows_core::Result { Ok(value) } +fn cleanup_failed_outputs(parameters: &[Parameter], out_values: &mut [AbiValue]) { + for parameter in parameters.iter().filter(|parameter| parameter.is_out()) { + let Some(AbiValue::Pointer(ptr)) = out_values.get_mut(parameter.value_index) else { + continue; + }; + unsafe { parameter.cleanup_failed_pointer(*ptr) }; + *ptr = std::ptr::null_mut(); + } +} + pub fn call_method_dynamic( vtable_index: usize, obj: *mut c_void, @@ -389,12 +399,18 @@ pub fn call_method_dynamic( match return_kind { MethodReturn::HResult => { let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); - hr.ok()?; + if hr.is_err() { + cleanup_failed_outputs(parameters, &mut out_values); + hr.ok()?; + } None } MethodReturn::SemanticHResult => { let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); - hr.ok()?; + if hr.is_err() { + cleanup_failed_outputs(parameters, &mut out_values); + hr.ok()?; + } Some(WinRTValue::HResult(hr)) } MethodReturn::Void => { diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index 118bd258..c0585eee 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -4,6 +4,7 @@ use core::ffi::c_void; use std::{ cell::RefCell, + collections::BTreeMap, sync::{Arc, RwLock}, }; @@ -15,7 +16,7 @@ use windows_core::{GUID, IUnknown, Interface as WindowsInterface}; use crate::{ MetadataTable, TypeHandle, WinRTValue, - native_call::{AbiMethodSignature, Method as NativeMethod, ParameterType}, + native_call::{AbiMethodSignature, Method as NativeMethod, OutputCleanup, ParameterType}, result, }; @@ -36,58 +37,142 @@ impl InterfaceBase { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PointerOutputKind { + None, + Unclassified, + Com, + CoTaskMem, + Bstr, +} + #[derive(Debug, Clone)] -pub struct Type(ParameterType); +pub struct Type { + abi: ParameterType, + pointer_output: PointerOutputKind, +} impl Type { pub fn winrt(typ: TypeHandle) -> Self { - Self(ParameterType::winrt(typ)) + Self { + abi: ParameterType::winrt(typ), + pointer_output: PointerOutputKind::None, + } } pub fn pointer() -> Self { - Self(ParameterType::pointer()) + Self::pointer_with_output(PointerOutputKind::Unclassified) + } + + pub fn owned_com_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::Com) + } + + pub fn co_task_mem_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::CoTaskMem) + } + + pub fn bstr_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::Bstr) + } + + fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { + Self { + abi: ParameterType::pointer(), + pointer_output, + } } } #[derive(Debug, Clone)] -pub struct MethodSignature(AbiMethodSignature); +pub struct MethodSignature { + abi: AbiMethodSignature, + output_kinds: Vec, + return_kind: Option, +} impl MethodSignature { pub fn new(table: &std::sync::Arc) -> Self { - Self(AbiMethodSignature::new(table)) + Self { + abi: AbiMethodSignature::new(table), + output_kinds: Vec::new(), + return_kind: None, + } + } + + pub fn add_in(mut self, typ: Type) -> Self { + self.abi = self.abi.add_in_type(typ.abi); + self } - pub fn add_in(self, typ: Type) -> Self { - Self(self.0.add_in_type(typ.0)) + pub fn add_out(mut self, typ: Type) -> Self { + self.output_kinds.push(typ.pointer_output); + self.abi = match typ.pointer_output { + PointerOutputKind::Com => self + .abi + .add_out_type_with_cleanup(typ.abi, OutputCleanup::ComRelease), + PointerOutputKind::CoTaskMem => self + .abi + .add_out_type_with_cleanup(typ.abi, OutputCleanup::CoTaskMemFree), + PointerOutputKind::Bstr => self + .abi + .add_out_type_with_cleanup(typ.abi, OutputCleanup::BstrFree), + PointerOutputKind::None | PointerOutputKind::Unclassified => { + self.abi.add_out_type(typ.abi) + } + }; + self } - pub fn add_out(self, typ: Type) -> Self { - Self(self.0.add_out_type(typ.0)) + pub fn add_in_out(mut self, typ: Type) -> Self { + self.output_kinds.push(PointerOutputKind::Unclassified); + self.abi = self.abi.add_in_out_type(typ.abi); + self } - pub fn add_in_out(self, typ: Type) -> Self { - Self(self.0.add_in_out_type(typ.0)) + pub fn add_out_fill(mut self, typ: Type) -> Self { + self.output_kinds.push(PointerOutputKind::None); + self.abi = self.abi.add_out_fill_type(typ.abi); + self } - pub fn add_out_fill(self, typ: Type) -> Self { - Self(self.0.add_out_fill_type(typ.0)) + pub fn returns(mut self, typ: Type) -> Self { + self.return_kind = Some(typ.pointer_output); + self.abi = self.abi.returns_type(typ.abi); + self } - pub fn returns(self, typ: Type) -> Self { - Self(self.0.returns_type(typ.0)) + pub fn returns_void(mut self) -> Self { + self.return_kind = None; + self.abi = self.abi.returns_void(); + self } - pub fn returns_void(self) -> Self { - Self(self.0.returns_void()) + pub fn preserve_hresult(mut self) -> Self { + self.return_kind = Some(PointerOutputKind::None); + self.abi = self.abi.preserve_hresult(); + self } - pub fn preserve_hresult(self) -> Self { - Self(self.0.preserve_hresult()) + fn build(self, vtable_index: usize) -> RegisteredMethod { + let mut result_kinds = + Vec::with_capacity(self.output_kinds.len() + usize::from(self.return_kind.is_some())); + if let Some(kind) = self.return_kind { + result_kinds.push(kind); + } + result_kinds.extend(self.output_kinds); + RegisteredMethod { + native: self.abi.build(vtable_index), + result_kinds, + } } } #[derive(Debug)] -struct RegisteredMethod(NativeMethod); +struct RegisteredMethod { + native: NativeMethod, + result_kinds: Vec, +} // Safety: a RegisteredMethod is fully built before publication and remains // immutable. NativeMethod invokes libffi's CIF only through shared references; @@ -100,7 +185,7 @@ pub struct Interface { name: String, iid: GUID, base_slot: usize, - methods: Arc)>>>, + methods: Arc)>>>, } impl Interface { @@ -113,26 +198,49 @@ impl Interface { } pub fn add_method(self, name: &str, signature: MethodSignature) -> Self { + let vtable_index = self + .methods + .read() + .unwrap() + .last_key_value() + .map_or(self.base_slot, |(slot, _)| slot + 1); + self.add_method_at(vtable_index, name, signature) + .expect("sequential COM method registration must use a free vtable slot") + } + + pub fn add_method_at( + self, + vtable_index: usize, + name: &str, + signature: MethodSignature, + ) -> result::Result { + if vtable_index < self.base_slot { + return Err(invalid_argument(format!( + "COM method '{name}' uses vtable slot {vtable_index}, before the interface base slot {}", + self.base_slot + ))); + } + let mut methods = self.methods.write().unwrap(); - if methods.iter().any(|(existing, _)| existing == name) { - drop(methods); - return self; + if methods.contains_key(&vtable_index) { + return Err(invalid_argument(format!( + "COM vtable slot {vtable_index} is already registered on '{}'", + self.name + ))); } - let vtable_index = self.base_slot + methods.len(); - methods.push(( - name.to_string(), - Arc::new(RegisteredMethod(signature.0.build(vtable_index))), - )); + methods.insert( + vtable_index, + (name.to_string(), Arc::new(signature.build(vtable_index))), + ); drop(methods); - self + Ok(self) } pub fn method(&self, vtable_index: usize) -> Option { - let local_index = vtable_index.checked_sub(self.base_slot)?; self.methods .read() .unwrap() - .get(local_index) + .get(&vtable_index) .map(|(_, method)| MethodHandle(Arc::clone(method))) } } @@ -149,14 +257,33 @@ impl std::fmt::Debug for MethodHandle { impl MethodHandle { pub fn invoke(&self, obj: *mut c_void, args: &[WinRTValue]) -> result::Result> { self.0 - .0 + .native .call_dynamic(obj, args) .map_err(result::Error::WindowsError) } + pub fn invoke_with_output_kinds( + &self, + obj: *mut c_void, + args: &[WinRTValue], + ) -> result::Result> { + let values = self.invoke(obj, args)?; + if values.len() != self.0.result_kinds.len() { + return Err(invalid_argument(format!( + "COM result plan mismatch: native call returned {} value(s), signature describes {}", + values.len(), + self.0.result_kinds.len() + ))); + } + Ok(values + .into_iter() + .zip(self.0.result_kinds.iter().copied()) + .collect()) + } + pub fn call_getter_hstring(&self, obj: *mut c_void) -> result::Result { self.0 - .0 + .native .call_getter_hstring(obj) .map_err(result::Error::WindowsError) } @@ -172,10 +299,17 @@ pub fn register_interface( name: name.to_string(), iid, base_slot: base.first_method_slot(), - methods: Arc::new(RwLock::new(Vec::new())), + methods: Arc::new(RwLock::new(BTreeMap::new())), } } +fn invalid_argument(message: String) -> result::Error { + result::Error::WindowsError(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &message, + )) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ApartmentType { SingleThreaded, @@ -265,8 +399,8 @@ pub fn call_method( args: &[WinRTValue], ) -> result::Result> { signature - .0 .build(vtable_index) + .native .call_dynamic(obj, args) .map_err(result::Error::WindowsError) } @@ -338,6 +472,65 @@ mod tests { vtable: *const *mut c_void, } + #[repr(C)] + struct TrackedComObject { + vtable: *const windows_core::IUnknown_Vtbl, + releases: AtomicU32, + } + + unsafe extern "system" fn tracked_query_interface( + _this: *mut c_void, + _iid: *const GUID, + result: *mut *mut c_void, + ) -> windows_core::HRESULT { + unsafe { *result = std::ptr::null_mut() }; + E_NOINTERFACE + } + + unsafe extern "system" fn tracked_add_ref(_this: *mut c_void) -> u32 { + 2 + } + + unsafe extern "system" fn tracked_release(this: *mut c_void) -> u32 { + let object = unsafe { &*(this as *const TrackedComObject) }; + object.releases.fetch_add(1, Ordering::Relaxed); + 1 + } + + static TRACKED_VTABLE: windows_core::IUnknown_Vtbl = windows_core::IUnknown_Vtbl { + QueryInterface: tracked_query_interface, + AddRef: tracked_add_ref, + Release: tracked_release, + }; + + #[repr(C)] + struct FailingOutCall { + vtable: *const *mut c_void, + output: *mut c_void, + } + + unsafe extern "system" fn write_object_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { *output = call.output }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn write_object_and_i32_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + number: *mut i32, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + *output = call.output; + *number = 42; + } + windows_core::HRESULT(0x80004005u32 as i32) + } + #[test] fn interface_and_method_handle_are_send_and_sync() { fn assert_send_sync() {} @@ -549,6 +742,86 @@ mod tests { )); } + #[test] + fn failing_hresult_releases_written_interface_output_on_direct_path() { + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + releases: AtomicU32::new(0), + }; + let vtable = [write_object_then_fail as *mut c_void]; + let mut call = FailingOutCall { + vtable: vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let table = MetadataTable::new(); + + let error = call_method( + 0, + (&mut call as *mut FailingOutCall).cast(), + MethodSignature::new(&table).add_out(Type::owned_com_pointer()), + &[], + ) + .unwrap_err(); + + assert!(error.message().contains("80004005")); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + } + + #[test] + fn failing_hresult_releases_written_interface_output_on_libffi_path() { + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + releases: AtomicU32::new(0), + }; + let vtable = [write_object_and_i32_then_fail as *mut c_void]; + let mut call = FailingOutCall { + vtable: vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let table = MetadataTable::new(); + + let error = call_method( + 0, + (&mut call as *mut FailingOutCall).cast(), + MethodSignature::new(&table) + .add_out(Type::owned_com_pointer()) + .add_out(Type::winrt(table.i32_type())), + &[], + ) + .unwrap_err(); + + assert!(error.message().contains("80004005")); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + } + + #[test] + fn semantic_pointer_outputs_lower_exact_failure_cleanup_plans() { + let table = MetadataTable::new(); + let cases = [ + ( + Type::owned_com_pointer(), + OutputCleanup::ComRelease, + PointerOutputKind::Com, + ), + ( + Type::co_task_mem_pointer(), + OutputCleanup::CoTaskMemFree, + PointerOutputKind::CoTaskMem, + ), + ( + Type::bstr_pointer(), + OutputCleanup::BstrFree, + PointerOutputKind::Bstr, + ), + ]; + + for (typ, expected_cleanup, expected_output) in cases { + let registered = MethodSignature::new(&table).add_out(typ).build(0); + assert_eq!(registered.native.output_cleanup(0), expected_cleanup); + assert_eq!(registered.result_kinds, [expected_output]); + } + } + #[test] fn multi_output_guid_uses_full_sized_storage() { let table = MetadataTable::new(); @@ -605,6 +878,80 @@ mod tests { assert!(!Arc::ptr_eq(&first.methods, &second.methods)); } + #[test] + fn duplicate_method_names_preserve_distinct_vtable_slots() { + let table = MetadataTable::new(); + let iface = register_interface( + &table, + "Windows.Win32.Example.IOverloaded", + GUID::from_u128(3), + InterfaceBase::IUnknown, + ) + .add_method("SetValue", MethodSignature::new(&table)) + .add_method("SetValue", MethodSignature::new(&table)) + .add_method("AfterOverload", MethodSignature::new(&table)); + + assert!(iface.method(3).is_some()); + assert!(iface.method(4).is_some()); + assert!(iface.method(5).is_some()); + } + + #[test] + fn explicit_method_registration_rejects_duplicate_slots() { + let table = MetadataTable::new(); + let iface = register_interface( + &table, + "Windows.Win32.Example.IExplicitSlots", + GUID::from_u128(4), + InterfaceBase::IUnknown, + ) + .add_method_at(7, "First", MethodSignature::new(&table)) + .unwrap(); + + let error = iface + .add_method_at(7, "Second", MethodSignature::new(&table)) + .unwrap_err(); + assert!(error.message().contains("slot 7")); + } + + #[test] + fn method_results_preserve_pointer_ownership_kind() { + let table = MetadataTable::new(); + let iface = register_interface( + &table, + "Windows.Win32.Example.IOwnedOutput", + GUID::from_u128(5), + InterfaceBase::IUnknown, + ) + .add_method_at( + 3, + "GetOwned", + MethodSignature::new(&table).add_out(Type::owned_com_pointer()), + ) + .unwrap(); + let vtable = [ + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + write_native_pointer as *mut c_void, + ]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + + let results = iface + .method(3) + .unwrap() + .invoke_with_output_kinds((&mut object as *mut FakeComObject).cast(), &[]) + .unwrap(); + + assert!(matches!( + results.as_slice(), + [(WinRTValue::RawPtr(ptr), PointerOutputKind::Com)] + if *ptr == 0x1234usize as *mut c_void + )); + } + fn shell_link_interface(table: &std::sync::Arc) -> Interface { register_interface( table, diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 9e69d6ec..a125092e 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -21,6 +21,35 @@ pub(crate) enum ParameterType { Pointer, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum OutputCleanup { + None, + ComRelease, + HStringDelete, + CoTaskMemFree, + BstrFree, +} + +impl OutputCleanup { + unsafe fn cleanup(self, ptr: *mut std::ffi::c_void) { + if ptr.is_null() { + return; + } + match self { + Self::None => {} + Self::ComRelease => drop(unsafe { windows_core::IUnknown::from_raw(ptr) }), + Self::HStringDelete => { + let value: windows_core::HSTRING = unsafe { core::mem::transmute(ptr) }; + drop(value); + } + Self::CoTaskMemFree => unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(ptr)); + }, + Self::BstrFree => drop(unsafe { windows_core::BSTR::from_raw(ptr.cast()) }), + } + } +} + impl ParameterType { pub(crate) fn winrt(typ: TypeHandle) -> Self { Self::WinRT(typ) @@ -158,6 +187,16 @@ impl ParameterType { )), } } + + fn default_output_cleanup(&self) -> OutputCleanup { + match self { + Self::WinRT(typ) if typ.kind().is_com_pointer() => OutputCleanup::ComRelease, + Self::WinRT(typ) if matches!(typ.kind(), TypeKind::HString) => { + OutputCleanup::HStringDelete + } + Self::WinRT(_) | Self::Pointer => OutputCleanup::None, + } + } } /// How a parameter is passed at the ABI level. @@ -174,6 +213,7 @@ pub enum ParamKind { #[derive(Debug, Clone)] pub struct Parameter { pub(crate) typ: ParameterType, + pub(crate) output_cleanup: OutputCleanup, /// Index in the method result vector for out and FillArray parameters. pub value_index: usize, /// Index in the caller-provided argument slice. FillArray parameters have @@ -201,6 +241,10 @@ impl Parameter { pub fn is_fill_array(&self) -> bool { self.kind == ParamKind::OutFillArray } + + pub(crate) unsafe fn cleanup_failed_pointer(&self, ptr: *mut std::ffi::c_void) { + unsafe { self.output_cleanup.cleanup(ptr) }; + } } #[derive(Debug, Clone)] @@ -251,6 +295,7 @@ impl AbiMethodSignature { self.parameters.push(Parameter { kind: ParamKind::In, typ, + output_cleanup: OutputCleanup::None, value_index: input_index, input_index: Some(input_index), }); @@ -258,9 +303,20 @@ impl AbiMethodSignature { } pub(crate) fn add_out_type(mut self, typ: ParameterType) -> Self { + let cleanup = typ.default_output_cleanup(); + self = self.add_out_type_with_cleanup(typ, cleanup); + self + } + + pub(crate) fn add_out_type_with_cleanup( + mut self, + typ: ParameterType, + output_cleanup: OutputCleanup, + ) -> Self { self.parameters.push(Parameter { kind: ParamKind::Out, typ, + output_cleanup, value_index: self.out_count, input_index: None, }); @@ -278,6 +334,7 @@ impl AbiMethodSignature { self.parameters.push(Parameter { kind: ParamKind::InOut, typ, + output_cleanup: OutputCleanup::None, value_index: self.out_count, input_index: Some(input_index), }); @@ -291,6 +348,7 @@ impl AbiMethodSignature { self.parameters.push(Parameter { kind: ParamKind::OutFillArray, typ, + output_cleanup: OutputCleanup::None, value_index: self.out_count, input_index: Some(input_index), }); @@ -435,6 +493,7 @@ impl AbiMethodSignature { info: MethodInfo { index, parameters: self.parameters, + input_count: self.input_count, out_count: self.out_count, return_kind: self.return_kind, }, @@ -447,6 +506,7 @@ impl AbiMethodSignature { pub struct MethodInfo { pub index: usize, pub parameters: Vec, + pub input_count: usize, pub out_count: usize, pub(crate) return_kind: MethodReturn, } @@ -635,6 +695,97 @@ fn validate_input_struct(expected: &TypeHandle, value: &WinRTValue) -> windows_c Ok(()) } +fn coerce_scalar_input( + expected: &TypeHandle, + value: &WinRTValue, +) -> windows_core::Result> { + let projected_alias = match (expected.kind(), value) { + (TypeKind::I8, WinRTValue::I32(value)) => { + Some(WinRTValue::I8(i8::try_from(*value).map_err(|_| { + invalid_argument("I32 projection value does not fit the expected i8 ABI") + })?)) + } + (TypeKind::U8, WinRTValue::I32(value)) => { + Some(WinRTValue::U8(u8::try_from(*value).map_err(|_| { + invalid_argument("I32 projection value does not fit the expected u8 ABI") + })?)) + } + (TypeKind::Char16, WinRTValue::I32(value)) => { + Some(WinRTValue::U16(u16::try_from(*value).map_err(|_| { + invalid_argument("I32 projection value does not fit the expected char16 ABI") + })?)) + } + _ => None, + }; + if projected_alias.is_some() { + return Ok(projected_alias); + } + + let matches = match expected.kind() { + TypeKind::Bool => matches!(value, WinRTValue::Bool(_)), + TypeKind::I8 => matches!(value, WinRTValue::I8(_)), + TypeKind::U8 => matches!(value, WinRTValue::U8(_)), + TypeKind::I16 => matches!(value, WinRTValue::I16(_)), + TypeKind::U16 | TypeKind::Char16 => matches!(value, WinRTValue::U16(_)), + TypeKind::I32 => matches!(value, WinRTValue::I32(_)), + TypeKind::U32 => matches!(value, WinRTValue::U32(_)), + TypeKind::I64 => matches!(value, WinRTValue::I64(_)), + TypeKind::U64 => matches!(value, WinRTValue::U64(_)), + TypeKind::F32 => matches!(value, WinRTValue::F32(_)), + TypeKind::F64 => matches!(value, WinRTValue::F64(_)), + TypeKind::Guid => matches!(value, WinRTValue::Guid(_)), + TypeKind::HString => matches!(value, WinRTValue::HString(_)), + TypeKind::HResult => matches!(value, WinRTValue::HResult(_) | WinRTValue::I32(_)), + TypeKind::Enum(_) => { + matches!(value, WinRTValue::I32(_)) + || matches!( + value, + WinRTValue::Enum { type_handle, .. } if type_handle == expected + ) + } + TypeKind::Struct(_) => { + validate_input_struct(expected, value)?; + true + } + TypeKind::Array(_) => { + return Err(invalid_argument( + "array input reached scalar COM/WinRT validation", + )); + } + kind if kind.is_com_pointer() => { + return Err(invalid_argument( + "COM object input reached scalar COM/WinRT validation", + )); + } + _ => false, + }; + + if matches { + Ok(None) + } else { + Err(invalid_argument(&format!( + "Argument type mismatch: expected {}, found {:?}", + expected.signature_string(), + value.get_type_kind() + ))) + } +} + +fn validate_pointer_input(value: &WinRTValue) -> windows_core::Result<()> { + if matches!(value, WinRTValue::RawPtr(_) | WinRTValue::Null) { + Ok(()) + } else { + Err(invalid_argument(&format!( + "Argument type mismatch: expected a native pointer, found {:?}", + value.get_type_kind() + ))) + } +} + +fn invalid_argument(message: &str) -> windows_core::Error { + windows_core::Error::new(windows_core::HRESULT(0x80070057u32 as i32), message) +} + fn validate_array_element( expected: &TypeHandle, value: &WinRTValue, @@ -718,6 +869,11 @@ impl call::ArgumentList for InvocationArgs<'_> { } impl Method { + #[cfg(test)] + pub(crate) fn output_cleanup(&self, parameter_index: usize) -> OutputCleanup { + self.info.parameters[parameter_index].output_cleanup + } + // --- Fast getter paths: zero Vec/WinRTValue allocation --- /// Getter → i32 (0 in, 1 out). Writes directly to stack i32. @@ -786,18 +942,28 @@ impl Method { obj: *mut std::ffi::c_void, args: &[WinRTValue], ) -> windows_core::Result> { + if args.len() != self.info.input_count { + return Err(invalid_argument(&format!( + "Argument count mismatch: expected {}, received {}", + self.info.input_count, + args.len() + ))); + } + let mut args = InvocationArgs::new(args); for parameter in self.info.parameters.iter().filter(|p| p.is_input()) { let input_index = parameter.input_index.expect("input parameter index"); let value = args.get_value(input_index); let coerced = if let Some(typ) = parameter.typ.as_winrt() { - validate_input_struct(typ, value)?; if typ.is_array() { coerce_input_array(typ, value)? - } else { + } else if expected_object_iid(typ).is_some() { coerce_input_object(typ, value)? + } else { + coerce_scalar_input(typ, value)? } } else { + validate_pointer_input(value)?; None }; if let Some(value) = coerced { @@ -817,7 +983,13 @@ impl Method { let param = &self.info.parameters[0]; let mut out = param.typ.default_value(); let hr = call::call_winrt_method_1(self.info.index, obj, out.out_ptr()); - hr.ok()?; + if hr.is_err() { + if let WinRTValue::RawPtr(ptr) = &mut out { + unsafe { param.cleanup_failed_pointer(*ptr) }; + *ptr = std::ptr::null_mut(); + } + hr.ok()?; + } // COM pointer types use RawPtr(null) as buffer to avoid IUnknown::from_raw(null) UB. // After COM writes the pointer, convert via from_out. if let WinRTValue::RawPtr(raw_ptr) = out { @@ -840,7 +1012,13 @@ impl Method { let mut out = out_param.typ.default_value(); let hr = call::call_1in_1out(self.info.index, obj, args.get_value(0), out.out_ptr()); - hr.ok()?; + if hr.is_err() { + if let WinRTValue::RawPtr(ptr) = &mut out { + unsafe { out_param.cleanup_failed_pointer(*ptr) }; + *ptr = std::ptr::null_mut(); + } + hr.ok()?; + } if let WinRTValue::RawPtr(raw_ptr) = out { out = out_param.typ.from_out(raw_ptr).map_err(|e| { windows_core::Error::new(windows_core::HRESULT(-1), &format!("{:?}", e)) @@ -908,7 +1086,13 @@ impl Method { -> windows_core::HRESULT = std::mem::transmute(fptr); method(obj, array_data.len() as u32, buffer.as_ptr(), out.out_ptr()) }; - hr.ok()?; + if hr.is_err() { + if let WinRTValue::RawPtr(ptr) = &mut out { + unsafe { out_param.cleanup_failed_pointer(*ptr) }; + *ptr = std::ptr::null_mut(); + } + hr.ok()?; + } if let WinRTValue::RawPtr(raw_ptr) = out { out = out_param.typ.from_out(raw_ptr).map_err(|e| { windows_core::Error::new(windows_core::HRESULT(-1), &format!("{:?}", e)) @@ -1049,6 +1233,15 @@ mod tests { windows_core::HRESULT(0) } + unsafe extern "system" fn record_i32( + this: *mut std::ffi::c_void, + _value: i32, + ) -> windows_core::HRESULT { + let object = unsafe { &*(this as *const FakeComObject) }; + object.calls.fetch_add(1, Ordering::Relaxed); + windows_core::HRESULT(0) + } + fn struct_in_out_method( table: &Arc, expected: TypeHandle, @@ -1081,6 +1274,96 @@ mod tests { assert_eq!(method.info.parameters[2].input_index, None); } + #[test] + fn rejects_incorrect_argument_count_before_native_call() { + let table = MetadataTable::new(); + let method = AbiMethodSignature::new(&table) + .add_in_type(ParameterType::winrt(table.i32_type())) + .build(0); + let vtable = Box::new([record_i32 as *mut std::ffi::c_void]); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + + let error = method + .call_dynamic((&mut object as *mut FakeComObject).cast(), &[]) + .unwrap_err(); + + assert_eq!(error.code().0, 0x80070057u32 as i32); + assert!(error.message().contains("Argument count mismatch")); + assert_eq!(object.calls.load(Ordering::Relaxed), 0); + } + + #[test] + fn rejects_wrong_native_pointer_value_before_native_call() { + let table = MetadataTable::new(); + let method = AbiMethodSignature::new(&table) + .add_in_type(ParameterType::pointer()) + .build(0); + let vtable = Box::new([record_i32 as *mut std::ffi::c_void]); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + + let error = method + .call_dynamic( + (&mut object as *mut FakeComObject).cast(), + &[WinRTValue::I32(42)], + ) + .unwrap_err(); + + assert_eq!(error.code().0, 0x80070057u32 as i32); + assert!(error.message().contains("native pointer")); + assert_eq!(object.calls.load(Ordering::Relaxed), 0); + } + + #[test] + fn rejects_wrong_in_out_scalar_width_before_native_call() { + let table = MetadataTable::new(); + let method = AbiMethodSignature::new(&table) + .add_in_out_type(ParameterType::winrt(table.u64_type())) + .build(0); + let vtable = Box::new([increment_struct_first_field as *mut std::ffi::c_void]); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + calls: AtomicU32::new(0), + }; + + let error = method + .call_dynamic( + (&mut object as *mut FakeComObject).cast(), + &[WinRTValue::I32(42)], + ) + .unwrap_err(); + + assert_eq!(error.code().0, 0x80070057u32 as i32); + assert!(error.message().contains("Argument type mismatch")); + assert_eq!(object.calls.load(Ordering::Relaxed), 0); + } + + #[test] + fn coerces_established_winrt_i32_narrow_integer_projections() { + let table = MetadataTable::new(); + + assert!(matches!( + coerce_scalar_input(&table.i8_type(), &WinRTValue::I32(-128)).unwrap(), + Some(WinRTValue::I8(-128)) + )); + assert!(matches!( + coerce_scalar_input(&table.u8_type(), &WinRTValue::I32(255)).unwrap(), + Some(WinRTValue::U8(255)) + )); + assert!(matches!( + coerce_scalar_input(&table.char16_type(), &WinRTValue::I32(0xffff)).unwrap(), + Some(WinRTValue::U16(0xffff)) + )); + assert!(coerce_scalar_input(&table.i8_type(), &WinRTValue::I32(128)).is_err()); + assert!(coerce_scalar_input(&table.u8_type(), &WinRTValue::I32(-1)).is_err()); + assert!(coerce_scalar_input(&table.char16_type(), &WinRTValue::I32(0x1_0000)).is_err()); + } + #[test] fn coerces_object_inputs_to_the_expected_interface() -> windows_core::Result<()> { let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; diff --git a/docs/classic-com-support.md b/docs/classic-com-support.md index fa49e0ae..6bb38688 100644 --- a/docs/classic-com-support.md +++ b/docs/classic-com-support.md @@ -379,11 +379,27 @@ not be described as solving every problem in the map above. | Explicit COM initialization | Activation no longer silently chooses MTA; callers select STA or MTA with `DynCom.initialize()`. | | Fail-closed generation | Unsupported structs, arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | | Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. Mixed and incremental generation preserve the WinRT-only root barrel; COM-only output retains its legacy root entrypoint. | +| Explicit vtable registration | Every generated method is registered with `.addMethodAt(vtableIndex, name, signature)`, keyed by its actual metadata-derived vtable slot. Methods are never deduplicated by name, so same-name overloads at different slots both register correctly. | +| Same-name overload projection | Overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) are grouped once during projection (not by renderer heuristics). A single public JS method dispatches to a private per-slot implementation using only a validated, mutually-distinguishable arity/shape key (`typeof`-based: boolean/number/bigint/string/object); ambiguous groups fail generation closed with a diagnostic naming the interface, method, and reason. The `.d.ts` emits one TypeScript overload signature per branch, contiguously. | +| Lifecycle ergonomics | Every generated class declares a private constructor (`private constructor(obj: unknown);`) and a public, idempotent `release()` that delegates to the managed native value. Generated `create()` JSDoc reminds callers that `DynCom.initialize()` must run first. | +| Doc-link rendering | When win32metadata attaches a `DocumentationAttribute` (a `learn.microsoft.com` URL) to a method, the generator renders it as an `@see {@link ...}` comment in both `.js` and `.d.ts`. No raw metadata is imported into the renderer — the URL is threaded through `ProjectedComMethod.doc`, populated once during projection. | +| Acronym-aware parameter casing | Parameter names are lowered using the same acronym-run-aware rule as method names, so a Hungarian-prefixed trailing acronym like `hwndMDI` projects as `mdi` (not the previous naive `mDI`). | +| Wide/ANSI string pointer split | `PointerAliasKind::StringPointer` now carries a `StringEncoding` (`Wide`/`Ansi`). Generated wrappers call the semantically distinct `DynCom.wideStringPointer(value)` / `DynCom.ansiStringPointer(value)` constructors instead of one unqualified pointer helper; the renderer never infers encoding — it only renders the encoding decision already made during projection. | +| Output ownership provenance | Signature expressions for pointer-shaped `[out]` values are chosen from `ProjectedComResult` ownership/conversion facts, not from type names: `DynCom.ownedComPointerType()` for dynamic-IID `+1` COM outputs, `DynCom.coTaskMemPointerType()` for `CoTaskMem` `PWSTR`/`PSTR` outputs, `DynCom.bstrPointerType()` for BSTR outputs, and plain `pointerType()` (never consumable as an owned value) for everything unclassified/borrowed. | +| Invocation validation | The completed native-call plan validates the exact argument count and ABI-compatible value shape before selecting a direct or libffi path. Native pointers reject scalar/object values, mismatched widths fail before dispatch, and established WinRT JS aliases (`I32` projected as `i8`/`u8`/`char16`) are range-checked and converted to exact ABI storage. | +| Failure-path cleanup | Each output parameter carries an explicit cleanup plan. If a callee writes an owned value and then returns a failing HRESULT, interface references are released, HSTRING/BSTR values are deleted with their matching APIs, and CoTaskMem outputs are freed on both direct and libffi paths. Unconsumed successful outputs retain the same allocator-specific ownership until converted, adopted, released, or garbage-collected. | +| Authoritative count-param detection | String-buffer/count relationships are read solely from the metadata's own `NativeArrayInfo(CountParamIndex)`. The previous `pfd`/`finddata` substring/adjacency heuristic has been removed entirely; unsupported writable native arrays fail closed instead of guessing a direction from parameter names. | +| Atomic multi-interface writes | When a single `generate` invocation projects several COM interfaces, every interface is projected into memory first; files (and the `com/` index/package barrel) are only written once the whole batch has projected successfully. A later interface's projection failure no longer leaves an earlier interface's files partially written to disk. | +| Coclass projection | GUID-bearing Classic COM coclasses such as `TaskbarList`, `FileOperation`, and `FileOpenDialog` generate as independently constructible JS classes (`new TaskbarList()`). Interface wrappers remain non-publicly constructible and expose an IID descriptor plus `_fromNative` for runtime QueryInterface views. | +| Interface views | Generated coclasses expose `as(InterfaceClass)`, `tryAs(InterfaceClass)`, and `supports(InterfaceClass)`. These execute real QueryInterface calls; `tryAs` returns `null` only for `E_NOINTERFACE`, while other errors remain visible. | +| Conservative primary interface | Windows.Win32 coclass TypeDefs do not carry `InterfaceImpl`/`DefaultAttribute` rows. The generator associates only exact metadata naming candidates, constructs the real interface inheritance graph, and selects a primary only when there is one unique most-derived leaf. Multiple unrelated leaves fail closed rather than choosing by numeric suffix. | +| CommonJS and ESM | COM implementation files use the same CommonJS format as generated WinRT files. `com/index.js` is the CommonJS barrel, while `com/index.mjs` is the ESM facade. Package exports provide explicit `require` and `import` conditions for the COM barrel and deep imports. | ### Generated package layout When WinRT and Classic COM are generated together, WinRT remains at the package -root and Classic COM uses an ESM-only subpackage: +root and Classic COM uses a domain-specific CommonJS subpackage with an ESM +facade: ```text bindings/ @@ -394,8 +410,10 @@ bindings/ ├── com/ │ ├── package.json │ ├── index.js +│ ├── index.mjs │ ├── index.d.ts -│ └── ITaskbarList3.js +│ ├── TaskbarList.js +│ └── ITaskbarList4.js └── package.json ``` @@ -405,10 +423,23 @@ namespaces in one invocation by using fully qualified names: ```powershell dynwinrt-codegen generate ` --winmd "C:\path\to\Windows.winmd;C:\path\to\Windows.Win32.winmd" ` - --class-name Windows.Foundation.Uri,Windows.Win32.UI.Shell.ITaskbarList3 ` + --class-name Windows.Foundation.Uri,Windows.Win32.UI.Shell.TaskbarList ` --output .\.winapp\bindings ``` +Generated coclasses follow the WinRT runtime-class convention: + +```js +import { TaskbarList, ITaskbarList3, TBPFLAG } from './bindings/com/index.mjs'; + +const taskbar = new TaskbarList(); +taskbar.setProgressState(hwnd, TBPFLAG.TBPF_NORMAL); + +const v3 = taskbar.as(ITaskbarList3); // real QueryInterface +v3.release(); +taskbar.release(); +``` + Separate WinRT and COM invocations may target the same output directory in either order. The generated package manifest is rebuilt from both domains without adding COM exports to the WinRT root. Legacy COM-only output is @@ -500,6 +531,7 @@ of every type in the 24 MB metadata file. | `SAFEARRAY` | Automation and Office-style COM APIs | Requires rank, bounds, element type, locking, and element cleanup semantics. | Win32 winmd Automation signatures | | `FORMATETC` / `STGMEDIUM` | `IDataObject`, clipboard, drag-and-drop | `STGMEDIUM` is a union of handles and interfaces with type-specific release behavior. | Win32 winmd + codegen diagnostic | | Arbitrary unions, bitfields, and nested pointer-rich structs | `D3D11_COUNTER_INFO`, `STATSTG`, `STRRET`, `POINTL`, `BIND_OPTS`, audio/media formats | The current generator has no general native C layout engine. | Win32 winmd + codegen diagnostics | +| `WIN32_FIND_DATAA`/`WIN32_FIND_DATAW` writable out-params | `IShellLinkW::GetPath` (`pfd`) | Multi-field struct with no recognized native layout; there is no safe way to size or write into it from the caller side. Generation fails closed for the whole interface. The COM E2E suite therefore exercises `IPersistFile` through direct Shell Link activation instead of generating `IShellLinkW`. | Win32 winmd + codegen diagnostic | | Writable caller-sized native arrays | `IDispatch::GetIDsOfNames`, counted byte/element output buffers | A scalar pointee is not sufficient storage. These are rejected unless a supported string-buffer projection applies. | Win32 winmd `NativeArrayInfo` + codegen diagnostic | | `BSTR**` arrays and BSTR in/out arrays | Automation collection APIs | Each element has independent allocation and release semantics. | Win32 winmd signature + ownership analysis | | Caller-owned ANSI output buffers | `PSTR` output-buffer APIs | Safe sizing and decoding are not yet projected. | Win32 winmd signature + projection limitation | @@ -581,8 +613,8 @@ against the resolved namespace. | 22 | `IFileOpenDialog` | 2,536 | 92 | Yes | Generates and live-tested without showing UI | | 23 | `IRunningObjectTable` | 2,532 | 50 | Yes | Fail closed: native `FILETIME` layout | | 24 | `IAudioClient` | 2,500 | 82 | Yes | Fail closed: format pointer/output ownership | -| 25 | `IShellLinkW` | 2,128 | 67 | Yes | Generates and live-tested | -| 26 | `ITaskbarList3` | 1,672 | 87 | Yes | Generates and live-tested | +| 25 | `IShellLinkW` | 2,128 | 67 | Yes | Fail closed: writable `WIN32_FIND_DATAW` layout | +| 26 | `ITaskbarList3` / `TaskbarList` | 1,672 | 87 | Yes | Interface and newable coclass generate and are live-tested | | 27 | `ICoreWebView2` | 1,608 | 35 | **No** | Defined in WebView2 metadata, not Windows.Win32.winmd | | 28 | `IFileSaveDialog` | 1,188 | 96 | Yes | Generates; live test still needed | | 29 | `IFileOperation` | 768 | 79 | Yes | Generates and live-tested | @@ -604,10 +636,10 @@ against the resolved namespace. - explicit output ownership (`DXGI`, audio); - interface in/out semantics (WMI); and - Property System types (`PROPERTYKEY`, `PROPVARIANT`). -- Seven frequency-survey candidates have generated live coverage: +- Six frequency-survey candidates have generated live coverage: `IPersistFile`, `IWICImagingFactory`, `IFileDialog` through - `IFileOpenDialog`, `IFileOpenDialog`, `IShellLinkW`, `ITaskbarList3`, and - `IFileOperation`. `IMalloc` and `IStream` add runtime-only live coverage. + `FileOpenDialog`, `TaskbarList`, and `FileOperation`. `IShellLinkW`, + `IMalloc`, and `IStream` add runtime-only live coverage. This means the current ten-interface suite provides useful ABI breadth, but it does **not** cover every high-frequency interface. In particular, @@ -624,12 +656,12 @@ hardware, and whether it adds a distinct ABI shape. |---|---|---| | `IStream` | OLE streams, imaging, shell, serialization | Core live test covers counted buffers, seek, and interface output. | | `IMalloc` | COM task allocator | Core live test covers direct pointer, pointer-sized, scalar, and void returns. | -| `IPersistFile` | Loading and saving persistent COM objects | Core and Node tests query it from `IShellLinkW` and verify `GetClassID`. | -| `IShellLinkW` | Shortcut creation and inspection | Core and Node tests cover strings, `u16`, enums, and scalar outputs. | -| `IFileOpenDialog` | Desktop file selection | Node test covers activation and option round-trip without showing UI. | -| `IFileOperation` | Shell copy/move/delete operations | Node test covers activation, unsigned flags, and state without modifying files. | +| `IPersistFile` | Loading and saving persistent COM objects | Core tests query it from `IShellLinkW`; Node activates the Shell Link coclass directly as `IPersistFile` and verifies `GetClassID`. | +| `IShellLinkW` | Shortcut creation and inspection | Core runtime tests cover strings, `u16`, enums, and scalar outputs; metadata codegen fails closed on `WIN32_FIND_DATAW`. | +| `FileOpenDialog` | Desktop file selection | Node test covers coclass construction and option round-trip without showing UI. | +| `FileOperation` | Shell copy/move/delete operations | Node test covers coclass construction, unsigned flags, and state without modifying files. | | `IWICImagingFactory` | Windows Imaging Component | Node test activates WIC and creates an interface-valued stream. | -| `ITaskbarList3` | Taskbar progress and window state | Node test covers inherited vtable slots, HWND values, BOOL, enums, and `u64`. | +| `TaskbarList` / `ITaskbarList3` | Taskbar progress and window state | Node test covers `new`, inherited vtable slots, HWND values, BOOL, enums, `u64`, and `as`/`tryAs`/`supports`. | | `IDataTransferManagerInterop` | HWND-to-WinRT data-transfer bridge | Core and Node tests cover `IUnknown`-rooted interop and interface output. | | `ISystemMediaTransportControlsInterop` | HWND-to-WinRT media controls | Node test covers `IInspectable`-rooted interop and use of the returned WinRT object. | | `IClassFactory` | Low-level COM activation | High-value next test; needs a public `CoGetClassObject` acquisition path. | @@ -651,17 +683,23 @@ and executed by [`tests/e2e_test.ps1`](../tests/e2e_test.ps1). | Interface | Test layer | Representative coverage | |---|---|---| -| `IShellLinkW` | Core + Node E2E | Activation, wide strings, hotkeys, show command, and deterministic release. | -| `IPersistFile` | Core + Node E2E | `QueryInterface`, owned returned reference, and GUID output. | +| `IShellLinkW` | Core | Manual ABI coverage for activation, wide strings, hotkeys, and show command; codegen intentionally fails closed. | +| `IPersistFile` | Core + Node E2E | `QueryInterface`/direct IID activation, owned returned reference, GUID output, and deterministic release. | | `IMalloc` | Core | Direct pointer return, `usize` return, direct `i32`, direct `void`, allocation cleanup. | | `IStream` | Core | Counted byte buffer, `u32` output, `i64` seek, `u64` output, and `IStream**` clone. | -| `ITaskbarList3` | Node E2E | Inherited slots, HWND, BOOL, enum, and `u64`. | -| `IFileOperation` | Node E2E | Coclass activation, unsigned flags, and state query. | -| `IFileOpenDialog` | Node E2E | STA activation and get/set options without user interaction. | +| `TaskbarList` / `ITaskbarList3` | Node E2E | Coclass construction, inherited slots, runtime QI views, HWND, BOOL, enum, and `u64`. | +| `FileOperation` | Node E2E | Coclass construction, unsigned flags, and state query. | +| `FileOpenDialog` | Node E2E | STA coclass construction and get/set options without user interaction. | | `IWICImagingFactory` | Node E2E | Explicit CLSID activation and typed interface output. | | `IDataTransferManagerInterop` | Core + Node E2E | `IUnknown` base, HWND, REFIID, and WinRT interface output. | | `ISystemMediaTransportControlsInterop` | Node E2E | `IInspectable` base and meaningful use of the returned WinRT projection. | +`IShellLinkW` is deliberately excluded from generated E2E coverage because +`GetPath` contains a writable `WIN32_FIND_DATAW*` without a modeled native +layout. The core runtime retains manual ABI coverage, while the Node E2E uses +the same Shell Link coclass through the safely generated `IPersistFile` +interface. + Additional regression tests cover: - rejection of duplicate ownership through exported pointer bits; @@ -702,6 +740,11 @@ The JavaScript ownership provenance checks intentionally prevent turning a borrowed numeric or TypedArray pointer into a second owner. This avoids two wrappers releasing the same COM reference. +Every generated Classic COM class also exposes a public `release()` method +delegating to the wrapped `DynWinRTValue`'s own `release()`. Calling +`release()` more than once is safe (the underlying value is cleared to null +the first time). + ## Test selection guidance Prefer new CI tests that: diff --git a/tests/e2e_test.ps1 b/tests/e2e_test.ps1 index 271cac0b..9dc94c9c 100644 --- a/tests/e2e_test.ps1 +++ b/tests/e2e_test.ps1 @@ -182,7 +182,7 @@ if ("com" -in $Lang) { & cargo run -p dynwinrt-codegen --release --quiet -- generate ` --winmd $win32Winmd ` --namespace Windows.Win32.UI.Shell ` - --class-name "ITaskbarList3,IDataTransferManagerInterop,IShellLinkW,IFileOperation,IFileOpenDialog" ` + --class-name "TaskbarList,IDataTransferManagerInterop,FileOperation,FileOpenDialog" ` --output $comShellDir ` --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM Shell generation failed"; exit 1 } @@ -268,9 +268,10 @@ if ("com" -in $Lang) { Write-Host "`n--- Classic COM E2E ---" -ForegroundColor Yellow $comRunners = @( "pointer-reject-object.mjs", + "module-commonjs.cjs", "taskbarlist.mjs", "electron-hwnd-buffer.mjs", - "shelllink-buffer.mjs", + "persist-file.mjs", "file-operation.mjs", "file-open-dialog.mjs", "wic-imaging-factory.mjs", diff --git a/tests/runners/com/electron-hwnd-buffer.mjs b/tests/runners/com/electron-hwnd-buffer.mjs index 6a35c691..22a12242 100644 --- a/tests/runners/com/electron-hwnd-buffer.mjs +++ b/tests/runners/com/electron-hwnd-buffer.mjs @@ -6,7 +6,7 @@ // contents as the handle value. Other Buffer-backed pointers retain address // semantics. -import { ITaskbarList3 } from '../../e2e_generated/com/shell/com/ITaskbarList3.js'; +import { TaskbarList } from '../../e2e_generated/com/shell/com/TaskbarList.js'; import { TBPFLAG } from '../../e2e_generated/com/shell/com/TBPFLAG.js'; import { acquireHwndBigInt } from './hwnd.mjs'; @@ -31,7 +31,7 @@ if (pointerWidth === 8) { console.log('[e2e] step 3: creating ITaskbarList3'); let taskbar; try { - taskbar = ITaskbarList3.create(); + taskbar = new TaskbarList(); taskbar.hrInit(); } catch (e) { fail(`ITaskbarList3 activation/HrInit threw: ${e && e.message ? e.message : e}`); @@ -46,5 +46,6 @@ try { fail(`Electron HWND Buffer pattern threw: ${e && e.message ? e.message : e}`); } +taskbar.release(); console.log('PASS'); process.exit(0); diff --git a/tests/runners/com/file-open-dialog.mjs b/tests/runners/com/file-open-dialog.mjs index 3b3c2411..5cfd2655 100644 --- a/tests/runners/com/file-open-dialog.mjs +++ b/tests/runners/com/file-open-dialog.mjs @@ -3,14 +3,14 @@ import assert from 'node:assert/strict'; import { DynCom } from '../../../bindings/js/dist/com.js'; -import { IFileOpenDialog } from '../../e2e_generated/com/shell/com/IFileOpenDialog.js'; +import { FileOpenDialog } from '../../e2e_generated/com/shell/com/FileOpenDialog.js'; DynCom.initialize(0); -const dialog = IFileOpenDialog.create(); +const dialog = new FileOpenDialog(); const options = dialog.getOptions(); dialog.setOptions(options); assert.equal(dialog.getOptions(), options); -dialog._obj.release(); +dialog.release(); console.log('file-open-dialog ok'); diff --git a/tests/runners/com/file-operation.mjs b/tests/runners/com/file-operation.mjs index 51973670..a0791d11 100644 --- a/tests/runners/com/file-operation.mjs +++ b/tests/runners/com/file-operation.mjs @@ -4,11 +4,11 @@ import assert from 'node:assert/strict'; import { DynCom } from '../../../bindings/js/dist/com.js'; import { FILEOPERATION_FLAGS } from '../../e2e_generated/com/shell/com/FILEOPERATION_FLAGS.js'; -import { IFileOperation } from '../../e2e_generated/com/shell/com/IFileOperation.js'; +import { FileOperation } from '../../e2e_generated/com/shell/com/FileOperation.js'; DynCom.initialize(1); -const operation = IFileOperation.create(); +const operation = new FileOperation(); const flags = FILEOPERATION_FLAGS.FOF_NO_UI + FILEOPERATION_FLAGS.FOFX_DONTDISPLAYLOCATIONS; @@ -16,6 +16,6 @@ const flags = assert.equal(flags, 2147485204); operation.setOperationFlags(flags); assert.equal(operation.getAnyOperationsAborted(), false); -operation._obj.release(); +operation.release(); console.log('file-operation ok'); diff --git a/tests/runners/com/module-commonjs.cjs b/tests/runners/com/module-commonjs.cjs new file mode 100644 index 00000000..c18a5c7e --- /dev/null +++ b/tests/runners/com/module-commonjs.cjs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +const assert = require('node:assert/strict'); +const { DynCom } = require('../../../bindings/js/dist/com.js'); +const barrel = require('../../e2e_generated/com/shell/com/index.js'); +const deep = require('../../e2e_generated/com/shell/com/TaskbarList.js'); + +assert.equal(typeof barrel.TaskbarList, 'function'); +assert.equal(typeof barrel.ITaskbarList3, 'function'); +assert.strictEqual(barrel.TaskbarList, deep.TaskbarList); + +DynCom.initialize(1); +const taskbar = new barrel.TaskbarList(); +taskbar.hrInit(); +assert.equal(taskbar.supports(barrel.ITaskbarList3), true); +taskbar.release(); + +console.log('module-commonjs ok'); diff --git a/tests/runners/com/persist-file.mjs b/tests/runners/com/persist-file.mjs new file mode 100644 index 00000000..25c5ff0b --- /dev/null +++ b/tests/runners/com/persist-file.mjs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict'; +import { DynCom } from '../../../bindings/js/dist/com.js'; +import { + IID_IPersistFile, + IPersistFile, +} from '../../e2e_generated/com/shell/com/IPersistFile.js'; + +const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; +DynCom.initialize(1); + +const persist = IPersistFile._fromNative( + DynCom.coCreateInstance(CLSID_SHELL_LINK, IID_IPersistFile), +); +assert.equal(persist.getClassID().toLowerCase(), CLSID_SHELL_LINK); +persist.release(); + +console.log('persist-file ok'); diff --git a/tests/runners/com/shelllink-buffer.mjs b/tests/runners/com/shelllink-buffer.mjs deleted file mode 100644 index 519f4cee..00000000 --- a/tests/runners/com/shelllink-buffer.mjs +++ /dev/null @@ -1,44 +0,0 @@ -import assert from 'node:assert/strict'; -import { DynCom } from '../../../bindings/js/dist/com.js'; -import { IShellLinkW, IID_IShellLinkW } from '../../e2e_generated/com/shell/com/IShellLinkW.js'; -import { IPersistFile, IID_IPersistFile } from '../../e2e_generated/com/shell/com/IPersistFile.js'; -import { SHOW_WINDOW_CMD } from '../../e2e_generated/com/shell/com/SHOW_WINDOW_CMD.js'; - -const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; -DynCom.initialize(1); - -function wide(text) { - return Buffer.from(`${text}\0`, 'utf16le'); -} - -const link = IShellLinkW._fromNative( - DynCom.coCreateInstance(CLSID_SHELL_LINK, IID_IShellLinkW), -); - -const expectedPath = 'C:\\Windows\\explorer.exe'; -link.setPath(wide(expectedPath)); -assert.equal(link.getPath(260, 0n, 0).toLowerCase(), expectedPath.toLowerCase()); -const pidl = link.getIDList(); -assert.equal(pidl.isNull(), false); -pidl.release(); - -const expectedDescription = 'dynwinrt shelllink buffer'; -link.setDescription(wide(expectedDescription)); -assert.equal(link.getDescription(), expectedDescription); - -// Proves the u16 arg-wrapper codegen fix: setHotkey takes a [in] u16 (WORD). -// Before the fix, codegen emitted the non-existent DynWinRtValue.u16Value(...) -// and this call threw a TypeError. It must now complete without throwing. -const expectedHotkey = 0x0341; // Ctrl+Alt+'A' -assert.doesNotThrow(() => link.setHotkey(expectedHotkey)); -assert.equal(link.getHotkey(), expectedHotkey); - -link.setShowCmd(SHOW_WINDOW_CMD.SW_SHOWMAXIMIZED); -assert.equal(link.getShowCmd(), SHOW_WINDOW_CMD.SW_SHOWMAXIMIZED); - -const persist = IPersistFile._fromNative(link._obj.cast(IID_IPersistFile)); -assert.equal(persist.getClassID().toLowerCase(), CLSID_SHELL_LINK); -persist._obj.release(); -link._obj.release(); - -console.log('shelllink-buffer ok'); diff --git a/tests/runners/com/taskbarlist.mjs b/tests/runners/com/taskbarlist.mjs index 7e685450..efef00cc 100644 --- a/tests/runners/com/taskbarlist.mjs +++ b/tests/runners/com/taskbarlist.mjs @@ -6,8 +6,11 @@ // // Run: .\tests\e2e_test.ps1 -SkipBuild -Lang com -import { ITaskbarList3 } from '../../e2e_generated/com/shell/com/ITaskbarList3.js'; -import { TBPFLAG } from '../../e2e_generated/com/shell/com/TBPFLAG.js'; +import { + ITaskbarList3, + TaskbarList, + TBPFLAG, +} from '../../e2e_generated/com/shell/com/index.mjs'; import { acquireHwndBigInt } from './hwnd.mjs'; function fail(msg) { @@ -26,13 +29,23 @@ if (hwndBig === 0n) fail('acquireHwndBigInt returned NULL'); console.log('[e2e] step 2: CoCreateInstance(CLSID_TaskbarList, IID_ITaskbarList3)'); -let t; +let taskbar; try { - t = ITaskbarList3.create(); + taskbar = new TaskbarList(); } catch (e) { - fail(`ITaskbarList3.create() threw: ${e && e.message ? e.message : e}`); + fail(`new TaskbarList() threw: ${e && e.message ? e.message : e}`); } -console.log(`[e2e] ITaskbarList3 = ${t}`); +console.log(`[e2e] TaskbarList = ${taskbar}`); + +if (!taskbar.supports(ITaskbarList3)) { + fail('TaskbarList.supports(ITaskbarList3) returned false'); +} +const optionalV3 = taskbar.tryAs(ITaskbarList3); +if (optionalV3 === null) { + fail('TaskbarList.tryAs(ITaskbarList3) returned null'); +} +optionalV3.release(); +const t = taskbar.as(ITaskbarList3); console.log('[e2e] step 3: HrInit() (vtable slot 3)'); try { @@ -78,5 +91,14 @@ try { fail(`MarkFullscreenWindow(hwnd, false) threw: ${e && e.message ? e.message : e}`); } +console.log('[e2e] step 8: SetThumbnailTooltip(hwnd, string) — proves PWSTR string projection'); +try { + t.setThumbnailTooltip(hwndBig, 'dynwinrt COM E2E'); +} catch (e) { + fail(`SetThumbnailTooltip(hwnd, string) threw: ${e && e.message ? e.message : e}`); +} + +t.release(); +taskbar.release(); console.log('PASS'); process.exit(0); diff --git a/tests/runners/com/wic-imaging-factory.mjs b/tests/runners/com/wic-imaging-factory.mjs index 7d5f2222..b6551df0 100644 --- a/tests/runners/com/wic-imaging-factory.mjs +++ b/tests/runners/com/wic-imaging-factory.mjs @@ -18,6 +18,6 @@ const factory = IWICImagingFactory._fromNative( const stream = factory.createStream(); assert.equal(stream.isNull(), false); stream.release(); -factory._obj.release(); +factory.release(); console.log('wic-imaging-factory ok'); diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index cf8129c0..32bafc09 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -42,11 +42,17 @@ pub(super) enum ComScalarRepr { NativeUsize, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum StringEncoding { + Wide, + Ansi, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub(super) enum PointerAliasKind { HandleValue, DataPointer, - StringPointer, + StringPointer(StringEncoding), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -121,12 +127,6 @@ pub(super) enum ComReturnConvention { Direct(ComType), } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum StringEncoding { - Wide, - Ansi, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ResultConversion { Value, @@ -171,6 +171,49 @@ pub(super) enum ProjectedComMethodKind { }, } +/// The JS runtime `typeof`/shape category a validated value uses at a call +/// site. Only types with a single, unambiguous JS shape participate in +/// overload dispatch — anything that can present as more than one shape (or +/// that overlaps another candidate's shape, e.g. `Buffer` inputs being +/// `typeof 'object'` just like a projected COM object) is deliberately left +/// unclassified (`None` from `dispatch_shape`) so overload grouping fails +/// closed instead of guessing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum DispatchShape { + Boolean, + Number, + BigInt, + String, + Object, +} + +/// How a single method within an overload group is selected at a call site. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum OverloadDispatch { + /// This method is the only overload with this argument count; dispatch by + /// `arguments.length` alone. + Arity, + /// Multiple overloads share this argument count; dispatch by inspecting + /// the JS shape of the argument at `key_param_index`. + ArityAndShape { + key_param_index: usize, + shape: DispatchShape, + }, +} + +/// Identifies a method as one branch of a same-name overload set, and how the +/// public dispatcher routes to it. Built once during projection (see +/// `project::group_overloads`) — the renderer only *renders* this decision, +/// it never re-derives it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct OverloadInfo { + /// The public JS name shared by every method in the group (e.g. `setOpacity`). + pub(super) public_name: String, + /// The private per-branch implementation name (e.g. `_setOpacity_7`). + pub(super) impl_name: String, + pub(super) dispatch: OverloadDispatch, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ProjectedComMethod { pub(super) name: String, @@ -182,6 +225,50 @@ pub(super) struct ProjectedComMethod { pub(super) string_buffer: Option, pub(super) kind: ProjectedComMethodKind, pub(super) doc: Option, + pub(super) overload: Option, +} + +/// Classifies the JS runtime shape a validated `ComType` presents as, for +/// overload-dispatch purposes. Returns `None` for any type whose JS +/// representation is ambiguous or overlaps another candidate shape (pointer +/// types accept `Buffer`/`bigint`/`number` in ways that collide with other +/// categories), so overload grouping can fail closed rather than guess. +pub(super) fn dispatch_shape(typ: &ComType) -> Option { + match typ { + ComType::Primitive(ComPrimitive::Bool) | ComType::Win32Bool => Some(DispatchShape::Boolean), + ComType::Primitive( + ComPrimitive::I8 + | ComPrimitive::U8 + | ComPrimitive::I16 + | ComPrimitive::U16 + | ComPrimitive::I32 + | ComPrimitive::U32 + | ComPrimitive::F32 + | ComPrimitive::F64 + | ComPrimitive::Char16, + ) + | ComType::HResult => Some(DispatchShape::Number), + ComType::Primitive(ComPrimitive::I64 | ComPrimitive::U64) + | ComType::NativeIsize + | ComType::NativeUsize => Some(DispatchShape::BigInt), + ComType::Guid | ComType::HString => Some(DispatchShape::String), + ComType::Enum { underlying, .. } => match underlying { + ComEnumUnderlying::I64 | ComEnumUnderlying::U64 => Some(DispatchShape::BigInt), + _ => Some(DispatchShape::Number), + }, + ComType::ScalarAlias { underlying, .. } => match underlying { + ComScalarRepr::Primitive(ComPrimitive::I64 | ComPrimitive::U64) + | ComScalarRepr::NativeIsize + | ComScalarRepr::NativeUsize => Some(DispatchShape::BigInt), + ComScalarRepr::Primitive(_) => Some(DispatchShape::Number), + }, + ComType::ManagedInterface { .. } => Some(DispatchShape::Object), + // Raw/aliased pointers and BSTR accept multiple overlapping JS input + // shapes (`bigint`, `number`, `Buffer`, `Uint8Array`, or `string`) + // depending on position, so they can collide with any other category + // and are never safe overload-dispatch keys. + ComType::RawPointer | ComType::PointerAlias { .. } | ComType::Bstr => None, + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -227,3 +314,12 @@ pub(super) struct ProjectedComInterface { pub(super) activation: ActivationPlan, pub(super) referenced_enums: Vec, } + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ProjectedComCoclass { + pub(super) name: String, + pub(super) namespace: String, + pub(super) clsid: String, + pub(super) primary_interface: ProjectedComInterface, + pub(super) associated_interfaces: Vec, +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs index 4ab4c002..6b95c41a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/naming.rs @@ -5,6 +5,17 @@ pub(in crate::codegen::com) fn camel_case(name: &str) -> String { if name.is_empty() { return String::new(); } + lower_leading_acronym(name) +} + +/// Lowercases a leading run of uppercase ASCII letters the way common +/// camelCase acronym conventions expect: a whole-string acronym (e.g. `URL`) +/// lowercases entirely; a single leading capital (e.g. `Set...`) just +/// lowercases that one letter; and a multi-letter acronym followed by a new +/// word (e.g. `MDIWindow`, `IOHandle`) lowercases all but the run's last +/// letter, since that last letter starts the next word (`mdiWindow`, +/// `ioHandle`). +fn lower_leading_acronym(name: &str) -> String { let chars: Vec = name.chars().collect(); let mut run = 0usize; while run < chars.len() && chars[run].is_ascii_uppercase() { @@ -43,14 +54,10 @@ pub(super) fn js_param_name(raw: &str, index: usize) -> String { raw.to_string() }; let stripped = strip_hungarian(&base); - let mut out = String::with_capacity(stripped.len()); - let mut chars = stripped.chars(); - if let Some(first) = chars.next() { - out.push(first.to_ascii_lowercase()); - } - for c in chars { - out.push(c); - } + // Use the same acronym-run-aware lowering as method names (`camel_case`) + // so a Hungarian-prefixed acronym remainder like `hwndMDI` -> `MDI` casts + // down to `mdi`, not a naive first-letter-only `mDI`. + let out = lower_leading_acronym(stripped); match out.as_str() { "class" | "return" | "function" | "default" | "this" | "new" | "delete" | "let" | "const" | "var" | "if" | "else" | "for" | "while" | "do" | "switch" | "case" @@ -83,3 +90,21 @@ pub(super) fn strip_hungarian(s: &str) -> &str { } s } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn js_param_name_lowercases_a_whole_leading_acronym_after_stripping_hungarian() { + // Regression test for ITaskbarList3::SetTabActive(HWND hwndTab, HWND + // hwndMDI, DWORD dwReserved): the Hungarian-stripped remainder `MDI` + // is a whole acronym, so it must lowercase entirely (`mdi`), not just + // its first letter (`mDI`). + assert_eq!(js_param_name("hwndMDI", 0), "mdi"); + // A single leading capital still lowercases just that letter. + assert_eq!(js_param_name("hwndTab", 0), "tab"); + // An acronym followed by a new word keeps the word capitalized. + assert_eq!(js_param_name("IOHandle", 0), "ioHandle"); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index be9dc88b..df2cedda 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -9,14 +9,15 @@ use std::collections::BTreeMap; use super::super::ir::ProjectedComEnumMember; use super::super::ir::{ ActivationPlan, ComEnumUnderlying, ComParamDirection, ComReturnConvention, ComType, - PointerAliasKind, ProjectedComEnum, ProjectedComInterface, ProjectedComMethod, - ProjectedComMethodKind, ProjectedComParam, ProjectedEnumValue, ResultConversion, - StringEncoding, + DispatchShape, OverloadDispatch, PointerAliasKind, ProjectedComCoclass, ProjectedComEnum, + ProjectedComInterface, ProjectedComMethod, ProjectedComMethodKind, ProjectedComParam, + ProjectedEnumValue, ResultConversion, ResultSource, StringEncoding, }; use super::naming::js_param_name; use super::types::{ abi_type_js, input_type_dts, result_type_dts, scalar_type_dts, unwrap_result_js, wrap_arg_js, }; +use crate::codegen::winrt::javascript::render::javascript::commonjs::convert_to_cjs_with_eager; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ComGeneratedOutput { @@ -28,22 +29,108 @@ pub struct ComGeneratedOutput { pub(in crate::codegen::com) fn render_com_interface( meta: &ProjectedComInterface, ) -> ComGeneratedOutput { - let js = render_js(meta); + render_projected_interface(meta) +} + +fn render_projected_interface(meta: &ProjectedComInterface) -> ComGeneratedOutput { + let js = com_esm_to_cjs(&render_js(meta)); let dts = render_dts(meta); - let mut extra_files = Vec::new(); + let mut extra_files = BTreeMap::new(); for en in &meta.referenced_enums { let (enum_js, enum_dts) = render_enum_files(en); - extra_files.push((format!("{}.js", en.name), enum_js)); - extra_files.push((format!("{}.d.ts", en.name), enum_dts)); + extra_files.insert(format!("{}.js", en.name), enum_js); + extra_files.insert(format!("{}.d.ts", en.name), enum_dts); + } + ComGeneratedOutput { + js, + dts, + extra_files: extra_files.into_iter().collect(), + } +} + +pub(in crate::codegen::com) fn render_com_coclass( + meta: &ProjectedComCoclass, +) -> ComGeneratedOutput { + let (js, dts) = render_coclass_files(&meta.name, &meta.clsid, &meta.primary_interface); + let mut extra_files = BTreeMap::new(); + for interface in &meta.associated_interfaces { + let output = render_projected_interface(interface); + extra_files.insert(format!("{}.js", interface.name), output.js); + extra_files.insert(format!("{}.d.ts", interface.name), output.dts); + for (name, content) in output.extra_files { + extra_files.entry(name).or_insert(content); + } } - extra_files.sort_by(|a, b| a.0.cmp(&b.0)); ComGeneratedOutput { js, dts, - extra_files, + extra_files: extra_files.into_iter().collect(), } } +fn render_coclass_files( + name: &str, + clsid: &str, + primary_interface: &ProjectedComInterface, +) -> (String, String) { + let mut js = String::new(); + js.push_str("// Generated by dynwinrt-codegen — do not edit\n"); + js.push_str(&format!( + "import {{ DynCom }} from '{}';\n", + com_runtime_import_name() + )); + js.push_str(&format!( + "import {{ {}, IID_{} }} from './{}.js';\n\n", + primary_interface.name, primary_interface.name, primary_interface.name + )); + js.push_str(&format!("export const CLSID_{name} = '{clsid}';\n\n")); + js.push_str(&format!( + "export class {name} extends {} {{\n", + primary_interface.name + )); + js.push_str(&format!( + " constructor() {{\n super(DynCom.coCreateInstance(CLSID_{name}, IID_{}));\n }}\n", + primary_interface.name + )); + js.push_str(&format!( + " static _fromNative(obj) {{\n const cast = obj.cast(IID_{});\n return Object.assign(Object.create({name}.prototype), {{ _obj: cast }});\n }}\n", + primary_interface.name + )); + js.push_str(" as(InterfaceClass) {\n return InterfaceClass._fromNative(this._obj.cast(InterfaceClass.IID));\n }\n"); + js.push_str(" tryAs(InterfaceClass) {\n const obj = DynCom.tryCast(this._obj, InterfaceClass.IID);\n return obj === null ? null : InterfaceClass._fromNative(obj);\n }\n"); + js.push_str(" supports(InterfaceClass) {\n const obj = DynCom.tryCast(this._obj, InterfaceClass.IID);\n if (obj === null) return false;\n obj.release();\n return true;\n }\n"); + js.push_str("}\n"); + + let descriptor = "{ readonly IID: unknown; _fromNative(obj: unknown): T }"; + let mut dts = String::new(); + dts.push_str("// Generated by dynwinrt-codegen — do not edit\n"); + dts.push_str(&format!( + "import {{ {} }} from './{}.js';\n\n", + primary_interface.name, primary_interface.name + )); + dts.push_str(&format!("export declare const CLSID_{name}: string;\n\n")); + dts.push_str(&format!( + "export declare class {name} extends {} {{\n", + primary_interface.name + )); + dts.push_str(" constructor();\n"); + dts.push_str(&format!(" static _fromNative(obj: unknown): {name};\n")); + dts.push_str(&format!(" as(InterfaceClass: {descriptor}): T;\n")); + dts.push_str(&format!( + " tryAs(InterfaceClass: {descriptor}): T | null;\n" + )); + dts.push_str(&format!( + " supports(InterfaceClass: {descriptor}): boolean;\n" + )); + dts.push_str("}\n"); + (com_esm_to_cjs(&js), dts) +} + +fn com_esm_to_cjs(esm: &str) -> String { + let runtime_sources = std::collections::HashSet::from([com_runtime_import_name()]); + convert_to_cjs_with_eager(esm, &runtime_sources) +} + fn render_js(meta: &ProjectedComInterface) -> String { let mut out = String::new(); out.push_str("// Generated by dynwinrt-codegen — do not edit\n"); @@ -106,7 +193,8 @@ fn render_js(meta: &ProjectedComInterface) -> String { )); for method in &meta.methods { out.push_str(&format!( - " .addMethod('{}', {})\n", + " .addMethodAt({}, '{}', {})\n", + method.vtable_index, method.name, build_method_sig_js(method) )); @@ -117,34 +205,47 @@ fn render_js(meta: &ProjectedComInterface) -> String { out.push_str(";\n"); out.push_str(&format!(" const value = {cache_var}[prop];\n return typeof value === 'function' ? value.bind({cache_var}) : value;\n }},\n}});\n\n")); out.push_str(&format!("export class {} {{\n", meta.name)); + out.push_str(&format!(" static IID = IID_{};\n", meta.name)); out.push_str(" _obj;\n constructor(obj) { this._obj = obj; }\n"); out.push_str(&format!( - " static _fromNative(obj) {{ return new {}(obj); }}\n", + " static _fromNative(obj) {{ return Object.assign(Object.create({}.prototype), {{ _obj: obj }}); }}\n", meta.name )); + out.push_str(" /** Release the underlying native COM reference. Safe to call more than once. */\n release() {\n this._obj.release();\n }\n"); match &meta.activation { ActivationPlan::None => {} - ActivationPlan::Coclass { - clsid, - coclass_name, - } => { - out.push_str(&format!( - " /** Create a new `{}` via `CoCreateInstance` on `CLSID_{coclass_name}`. */\n", - meta.name - )); - out.push_str(&format!(" static create() {{\n const _obj = DynCom.coCreateInstance('{clsid}', IID_{});\n return new {}(_obj);\n }}\n", meta.name, meta.name)); - } + ActivationPlan::Coclass { .. } => {} ActivationPlan::WinRtFactory { class_name, class_namespace, .. } => { let full = format!("{class_namespace}.{class_name}"); - out.push_str(&format!(" /** Create a new `{}` by activating the `{full}` factory and QI'ing to the interop. */\n", meta.name)); + out.push_str(&format!(" /** Create a new `{}` by activating the `{full}` factory and QI'ing to the interop.\n * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */\n", meta.name)); out.push_str(&format!(" static create() {{\n const factory = DynWinRtValue.activationFactory('{full}');\n const _obj = factory.cast(IID_{});\n return new {}(_obj);\n }}\n", meta.name, meta.name)); } } + let mut emitted_groups = std::collections::HashSet::new(); for method in &meta.methods { + if let Some(overload) = &method.overload { + if !emitted_groups.insert(overload.public_name.clone()) { + continue; + } + let group: Vec<&ProjectedComMethod> = meta + .methods + .iter() + .filter(|candidate| { + candidate + .overload + .as_ref() + .is_some_and(|candidate_overload| { + candidate_overload.public_name == overload.public_name + }) + }) + .collect(); + emit_overload_group_js(&mut out, &group, &iface_var); + continue; + } match method.kind { ProjectedComMethodKind::Normal => emit_method_js(&mut out, method, &iface_var), ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -182,7 +283,10 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { }) { parts.push(".addIn(DynCom.pointerType())".into()); } else { - parts.push(format!(".addOut({})", abi_type_js(¶m.typ))); + parts.push(format!( + ".addOut({})", + out_abi_type_js(method, index, ¶m.typ) + )); } } } @@ -200,6 +304,32 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { } } +/// Selects the ABI output type for an `Out` parameter, using the projected +/// result's ownership/conversion facts (not the parameter's raw type name) to +/// pick a semantically correct, provenance-tagged pointer type where the +/// runtime needs to know how to (or whether it may) reclaim the output value. +/// Any pointer output that isn't classified with a known ownership contract +/// falls back to the unclassified `pointerType()`, which the runtime does not +/// allow callers to adopt as an owned value. +fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComType) -> String { + let conversion = method + .results + .iter() + .find(|result| result.source == ResultSource::Param(param_index)) + .map(|result| &result.conversion); + match conversion { + Some(ResultConversion::DynamicIidAdoption) => "DynCom.ownedComPointerType()".into(), + Some(ResultConversion::Bstr) => "DynCom.bstrPointerType()".into(), + Some(ResultConversion::CoTaskMemString(_) | ResultConversion::CoTaskMemData) => { + "DynCom.coTaskMemPointerType()".into() + } + Some( + ResultConversion::ManagedCom | ResultConversion::HString | ResultConversion::Value, + ) + | None => abi_type_js(typ), + } +} + fn input_params(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> { method .params @@ -210,6 +340,32 @@ fn input_params(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> } fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str) { + emit_method_doc_js(out, &method.doc); + emit_method_js_named(out, method, iface_var, &method.camel_name); +} + +/// Emits a one-line `@see` JSDoc comment above a method when metadata +/// supplied a doc reference (win32metadata's `DocumentationAttribute`, a +/// `learn.microsoft.com` URL — see `com_metadata::parse_methods`). Renders +/// nothing when `doc` is `None`; the renderer never invents documentation. +fn emit_method_doc_js(out: &mut String, doc: &Option) { + if let Some(url) = doc { + out.push_str(&format!(" /** @see {{@link {url}}} */\n")); + } +} + +/// Renders a single method body under `js_name`. Used both for standalone +/// methods (`js_name == method.camel_name`) and for each private per-overload +/// implementation of a grouped overload set (`js_name == +/// overload.impl_name`), so the JS body-emission logic is shared regardless +/// of whether the method is dispatched to directly or via the public +/// overload dispatcher. +fn emit_method_js_named( + out: &mut String, + method: &ProjectedComMethod, + iface_var: &str, + js_name: &str, +) { let inputs = input_params(method); let params = inputs .iter() @@ -228,11 +384,7 @@ fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str name }) .collect::>(); - out.push_str(&format!( - " {}({}) {{\n", - method.camel_name, - params.join(", ") - )); + out.push_str(&format!(" {js_name}({}) {{\n", params.join(", "))); if let Some(plan) = &method.string_buffer { emit_string_buffer_method_body(out, method, plan, &inputs, iface_var); out.push_str(" }\n"); @@ -247,6 +399,68 @@ fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str out.push_str(" }\n"); } +/// Renders one same-name overload group: every branch's private +/// implementation (named per `OverloadInfo::impl_name`, e.g. +/// `_setOpacity_7`), followed by a single public dispatcher method that picks +/// a branch using only the validated, distinguishable dispatch decision +/// computed during projection (`OverloadInfo::dispatch`) — never a +/// renderer-invented heuristic. +fn emit_overload_group_js(out: &mut String, group: &[&ProjectedComMethod], iface_var: &str) { + for method in group { + let overload = method + .overload + .as_ref() + .expect("group members are always overloaded"); + emit_method_js_named(out, method, iface_var, &overload.impl_name); + } + let public_name = &group[0] + .overload + .as_ref() + .expect("group members are always overloaded") + .public_name; + // Attach the first branch's doc reference (if any) to the public + // dispatcher, since that's the method callers actually see and call. + emit_method_doc_js(out, &group.iter().find_map(|method| method.doc.clone())); + out.push_str(&format!(" {public_name}(...args) {{\n")); + for method in group { + let overload = method + .overload + .as_ref() + .expect("group members are always overloaded"); + let arity = input_params(method).len(); + let condition = match overload.dispatch { + OverloadDispatch::Arity => format!("args.length === {arity}"), + OverloadDispatch::ArityAndShape { + key_param_index, + shape, + } => format!( + "args.length === {arity} && {}", + dispatch_shape_check_js(shape, key_param_index) + ), + }; + out.push_str(&format!( + " if ({condition}) return this.{}(...args);\n", + overload.impl_name + )); + } + out.push_str(&format!( + " throw new TypeError(`No overload of {public_name} matches the given arguments`);\n" + )); + out.push_str(" }\n"); +} + +fn dispatch_shape_check_js(shape: DispatchShape, index: usize) -> String { + match shape { + DispatchShape::Boolean => format!("typeof args[{index}] === 'boolean'"), + DispatchShape::Number => format!("typeof args[{index}] === 'number'"), + DispatchShape::BigInt => format!("typeof args[{index}] === 'bigint'"), + DispatchShape::String => format!("typeof args[{index}] === 'string'"), + DispatchShape::Object => { + format!("(args[{index}] !== null && typeof args[{index}] === 'object')") + } + } +} + fn emit_string_buffer_method_body( out: &mut String, method: &ProjectedComMethod, @@ -467,7 +681,15 @@ fn render_dts(meta: &ProjectedComInterface) -> String { match kind { PointerAliasKind::HandleValue => out.push_str(&format!("/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */\nexport type {name} = bigint | number;\n")), PointerAliasKind::DataPointer => out.push_str(&format!("/** Opaque native data address. Inputs may also use a `Buffer`/`Uint8Array`, whose backing-store address is passed and retained for the call. */\nexport type {name} = bigint | number;\n")), - PointerAliasKind::StringPointer => out.push_str(&format!("/** Win32 NUL-terminated string pointer. Pass a `Buffer` holding the string bytes (including the NUL terminator), or pass a raw pointer as `bigint`. */\nexport type {name} = bigint | Buffer;\n")), + PointerAliasKind::StringPointer(encoding) => { + let description = match encoding { + StringEncoding::Wide => "Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`.", + StringEncoding::Ansi => "Pass an ASCII JS `string` (encoded automatically via DynCom.ansiStringPointer), a `Buffer`/`Uint8Array` holding explicitly ANSI-encoded bytes (including the NUL terminator), or a raw pointer as `bigint`. Non-ASCII text must use pre-encoded bytes.", + }; + out.push_str(&format!( + "/** Win32 NUL-terminated string pointer. {description} */\nexport type {name} = string | Buffer | Uint8Array | bigint;\n" + )); + } } } if !collect_pointer_aliases(meta).is_empty() { @@ -477,19 +699,50 @@ fn render_dts(meta: &ProjectedComInterface) -> String { "export declare const IID_{}: unknown;\n\nexport declare class {} {{\n", meta.name, meta.name )); + out.push_str(&format!( + " static readonly IID: typeof IID_{};\n", + meta.name + )); + out.push_str(" protected constructor(obj: unknown);\n"); match &meta.activation { ActivationPlan::None => {} - ActivationPlan::Coclass { .. } => out.push_str(&format!( - " /** Create a new instance via the coclass activation path. */\n static create(): {};\n", - meta.name - )), + ActivationPlan::Coclass { .. } => {} ActivationPlan::WinRtFactory { .. } => out.push_str(&format!( - " /** Activate the projected WinRT class and QI to the interop. */\n static create(): {};\n", + " /** Activate the projected WinRT class and QI to the interop.\n * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */\n static create(): {};\n", meta.name )), } out.push_str(&format!(" /** Wrap an existing native COM pointer (for QueryInterface bridging). */\n static _fromNative(obj: unknown): {};\n", meta.name)); + out.push_str(" /** Release the underlying native COM reference. Safe to call more than once. */\n release(): void;\n"); + let mut emitted_groups = std::collections::HashSet::new(); for method in &meta.methods { + if let Some(overload) = &method.overload { + if !emitted_groups.insert(overload.public_name.clone()) { + continue; + } + let group_methods: Vec<_> = meta + .methods + .iter() + .filter(|candidate| { + candidate + .overload + .as_ref() + .is_some_and(|candidate_overload| { + candidate_overload.public_name == overload.public_name + }) + }) + .collect(); + emit_method_doc_dts(&mut out, &group_methods.iter().find_map(|m| m.doc.clone())); + for group_method in &group_methods { + out.push_str(&format!( + " {}({}): {};\n", + overload.public_name, + dts_params(group_method).join(", "), + dts_return_type(group_method) + )); + } + continue; + } let (params, ret) = match method.kind { ProjectedComMethodKind::Normal => (dts_params(method), dts_return_type(method)), ProjectedComMethodKind::CallerSuppliedDynamicIid { @@ -507,6 +760,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { "DynWinRtValue".into(), ), }; + emit_method_doc_dts(&mut out, &method.doc); out.push_str(&format!( " {}({}): {};\n", method.camel_name, @@ -518,6 +772,15 @@ fn render_dts(meta: &ProjectedComInterface) -> String { out } +/// Emits a one-line `@see` TSDoc comment above a `.d.ts` method signature +/// when metadata supplied a doc reference. Mirrors `emit_method_doc_js`; +/// renders nothing when `doc` is `None`. +fn emit_method_doc_dts(out: &mut String, doc: &Option) { + if let Some(url) = doc { + out.push_str(&format!(" /** @see {{@link {url}}} */\n")); + } +} + fn dts_natural_params(method: &ProjectedComMethod, count: usize) -> Vec { method.params[..count] .iter() @@ -697,7 +960,7 @@ fn render_enum_files(en: &ProjectedComEnum) -> (String, String) { )); } dts.push_str("};\n"); - (js, dts) + (com_esm_to_cjs(&js), dts) } fn render_enum_value(value: &ProjectedEnumValue, underlying: ComEnumUnderlying) -> String { diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index 09bff2d6..5ab38988 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -29,6 +29,56 @@ fn renderer_api_accepts_only_projected_ir() { assert!(output.dts.contains("export declare class ITest")); } +#[test] +fn coclass_renderer_uses_new_and_runtime_query_interface_views() { + let primary = ProjectedComInterface { + name: "ITest4".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000004".into(), + is_iunknown_rooted: true, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + let coclass = ProjectedComCoclass { + name: "Test".into(), + namespace: "Tests".into(), + clsid: "10000000-0000-0000-0000-000000000001".into(), + primary_interface: primary.clone(), + associated_interfaces: vec![primary], + }; + + let output = render_com_coclass(&coclass); + + assert!(output.js.contains("class Test extends ITest4")); + assert!( + output + .js + .contains("const { ITest4, IID_ITest4 } = require('./ITest4.js');") + ); + assert!(output.js.contains("exports.Test = Test;")); + assert!(output.js.contains("constructor()")); + assert!( + output + .js + .contains("DynCom.coCreateInstance(CLSID_Test, IID_ITest4)") + ); + assert!(output.js.contains("as(InterfaceClass)")); + assert!(output.js.contains("DynCom.tryCast")); + assert!( + output + .dts + .contains("export declare class Test extends ITest4") + ); + assert!(output.dts.contains("tryAs")); + assert!( + output + .extra_files + .iter() + .any(|(name, _)| name == "ITest4.js") + ); +} + #[test] fn allocator_contract_rejects_trailing_separator_and_whitespace() { for free_with in ["CoTaskMemFree:", " CoTaskMemFree", "CoTaskMemFree "] { @@ -278,7 +328,11 @@ fn handle_alias_kind_distinguishes_handle_values_from_string_pointers() { assert_eq!(handle_alias_kind(&hwnd), Some(HandleAliasKind::HandleValue)); assert_eq!( handle_alias_kind(&pwstr_struct()), - Some(HandleAliasKind::StringPointer) + Some(HandleAliasKind::StringPointer(StringEncoding::Wide)) + ); + assert_eq!( + handle_alias_kind(&pstr_struct()), + Some(HandleAliasKind::StringPointer(StringEncoding::Ansi)) ); let psid = TypeMeta::Struct { namespace: "Windows.Win32.Security".into(), @@ -392,7 +446,7 @@ fn hresult_input_projects_as_number_and_i32_value() { let js = render_js(&com, None); let dts = render_dts(&com, None); assert!( - js.contains(".addMethod('Close', new DynComMethodSig().addIn(DynCom.i32Type()))"), + js.contains(".addMethodAt(4, 'Close', new DynComMethodSig().addIn(DynCom.i32Type()))"), ".js must register HRESULT in-param as i32:\n{}", js ); @@ -418,6 +472,63 @@ fn hresult_input_projects_as_number_and_i32_value() { ); } +#[test] +fn method_doc_url_renders_as_see_link_in_js_and_dts() { + let m = MethodMeta { + name: "Close".into(), + vtable_index: 4, + params: vec![ParamMeta { + name: "hr".into(), + typ: make_hresult(), + direction: ParamDirection::In, + }], + return_type: Some(make_hresult()), + doc: Some( + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-ipersist-close".into(), + ), + ..Default::default() + }; + let com = plain_iface_with_method(m); + let js = render_js(&com, None); + let dts = render_dts(&com, None); + let expected_doc = "/** @see {@link https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-ipersist-close} */"; + assert!( + js.contains(expected_doc), + ".js must render the metadata doc URL as an @see JSDoc comment above the method:\n{}", + js + ); + assert!( + dts.contains(expected_doc), + ".d.ts must render the metadata doc URL as an @see JSDoc comment above the signature:\n{}", + dts + ); +} + +#[test] +fn method_without_doc_renders_no_see_comment() { + let m = MethodMeta { + name: "Close".into(), + vtable_index: 4, + params: vec![ParamMeta { + name: "hr".into(), + typ: make_hresult(), + direction: ParamDirection::In, + }], + return_type: Some(make_hresult()), + doc: None, + ..Default::default() + }; + let com = plain_iface_with_method(m); + let js = render_js(&com, None); + let dts = render_dts(&com, None); + assert!( + !js.contains("@see"), + "renderer must not invent documentation when metadata has none:\n{}", + js + ); + assert!(!dts.contains("@see"), "same for .d.ts:\n{}", dts); +} + // ---- Fix 3 (REFIID-guarded interop heuristic) ---- /// Helper: construct a MethodMeta with HRESULT return type. @@ -862,6 +973,38 @@ fn plain_method_single_out_guid_projects_as_string() { ); } +#[test] +fn generated_interface_exposes_release_iid_and_protected_constructor() { + let m = MethodMeta { + name: "Close".into(), + vtable_index: 4, + params: Vec::new(), + return_type: Some(make_hresult()), + ..Default::default() + }; + let com = plain_iface_with_method(m); + let js = render_js(&com, None); + let dts = render_dts(&com, None); + + assert!( + js.contains("release()") && js.contains("this._obj.release();"), + ".js class must expose a release() method delegating to the managed native value:\n{}", + js + ); + assert!( + dts.contains("release(): void;"), + ".d.ts must declare release(): void;:\n{}", + dts + ); + assert!( + dts.contains("protected constructor(obj: unknown);") + && dts.contains("static readonly IID:"), + ".d.ts must make the interface non-publicly constructible while allowing generated coclass subclasses:\n{}", + dts + ); + assert!(js.contains("Object.create(IHasOut.prototype)")); +} + #[test] fn plain_method_single_out_enum_projects_as_underlying() { // Model: `HRESULT GetKind([out] MyKind* pk)` where MyKind is an I32 @@ -1094,20 +1237,23 @@ fn handle_value_arg_accepts_buffer_and_string_pointer_keeps_buffer() { // HWND inputs accept Electron's pointer-width Buffer, but the HWND // output alias remains a numeric handle value. assert!(dts.contains("export type HWND = bigint | number;")); - assert!(dts.contains("export type PWSTR = bigint | Buffer;")); - assert!(dts.contains("Pass a `Buffer` holding the string bytes")); + assert!(dts.contains("export type PWSTR = string | Buffer | Uint8Array | bigint;")); + assert!( + dts.contains("Pass a JS `string` (encoded automatically via DynCom.wideStringPointer)") + ); assert!( dts.contains("setOverlayIcon(hwnd: HWND | Buffer | Uint8Array, description: PWSTR): void;") ); // Handle-value conversion is centralized in the runtime; string - // pointers continue to pass their backing-store address. + // pointers use the encoding-aware wide/ANSI constructors so the runtime + // knows how to marshal a JS `string` input. assert!( js.contains("DynCom.pointer(DynCom.handleValue(hwnd))"), "HWND arg must use DynCom.handleValue:\n{js}" ); assert!(!js.contains("function _handleArg(")); - assert!(!js.contains("handleValue(description)")); + assert!(js.contains("DynCom.wideStringPointer(description)")); } #[test] @@ -1301,6 +1447,17 @@ fn pwstr_struct() -> TypeMeta { } } +fn pstr_struct() -> TypeMeta { + TypeMeta::Struct { + namespace: "Windows.Win32.Foundation".into(), + name: "PSTR".into(), + fields: vec![crate::types::FieldMeta { + name: "Value".into(), + typ: TypeMeta::Object, + }], + } +} + #[test] fn out_string_buffer_allocates_decodes_and_returns_string() { let m = MethodMeta { @@ -1332,7 +1489,7 @@ fn out_string_buffer_allocates_decodes_and_returns_string() { js ); assert!( - js.contains(".addMethod('GetDescription', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type()))"), + js.contains(".addMethodAt(6, 'GetDescription', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type()))"), ".js must register string buffer as an input pointer:\n{}", js ); diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs index a3f6c2a8..b984c4b3 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -124,6 +124,14 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { } if name == "HWND" => { format!("DynCom.pointer(DynCom.handleValue({variable}))") } + ComType::PointerAlias { + kind: PointerAliasKind::StringPointer(StringEncoding::Wide), + .. + } => format!("DynCom.wideStringPointer({variable})"), + ComType::PointerAlias { + kind: PointerAliasKind::StringPointer(StringEncoding::Ansi), + .. + } => format!("DynCom.ansiStringPointer({variable})"), ComType::PointerAlias { .. } => format!("DynCom.pointer({variable})"), ComType::ManagedInterface { .. } => variable.to_string(), } diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index 67d0f914..35a14444 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -7,7 +7,7 @@ mod ir; mod javascript; mod project; -use crate::com_metadata::ComInterfaceMeta; +use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; pub use javascript::render::ComGeneratedOutput; @@ -18,3 +18,11 @@ pub fn generate_com_interface_files( let projected = project::project_com_interface(meta, winmd_paths)?; Ok(javascript::render::render_com_interface(&projected)) } + +pub fn generate_com_coclass_files( + meta: &ComCoclassMeta, + winmd_paths: &str, +) -> Result { + let projected = project::project_com_coclass(meta, winmd_paths)?; + Ok(javascript::render::render_com_coclass(&projected)) +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 81a852d2..17e82beb 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -4,14 +4,17 @@ mod interop; pub(super) mod types; -use crate::com_metadata::{ComEnumValue, ComInterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; +use crate::com_metadata::{ + ComCoclassMeta, ComEnumValue, ComInterfaceMeta, MethodMeta, ParamDirection, +}; use crate::types::TypeMeta; use super::ir::{ - ActivationPlan, ComParamDirection, ComReturnConvention, ComType, ProjectedComEnum, - ProjectedComEnumMember, ProjectedComInterface, ProjectedComMethod, ProjectedComMethodKind, - ProjectedComParam, ProjectedComResult, ProjectedEnumValue, ResultConversion, ResultSource, - StringBufferPlan, StringEncoding, UnsupportedComType, + ActivationPlan, ComParamDirection, ComReturnConvention, ComType, OverloadDispatch, + OverloadInfo, ProjectedComCoclass, ProjectedComEnum, ProjectedComEnumMember, + ProjectedComInterface, ProjectedComMethod, ProjectedComMethodKind, ProjectedComParam, + ProjectedComResult, ProjectedEnumValue, ResultConversion, ResultSource, StringBufferPlan, + StringEncoding, UnsupportedComType, dispatch_shape, }; use super::javascript::naming::camel_case; use interop::resolve_projected_default_iid; @@ -28,6 +31,7 @@ pub(super) fn project_com_interface( .iter() .map(|method| project_method(meta, method, interop_target.as_ref())) .collect::, _>>()?; + let methods = group_overloads(methods, &meta.interface.name)?; let activation = if let Some((class_name, class_namespace, target_iid)) = interop_target { ActivationPlan::WinRtFactory { class_name, @@ -79,6 +83,195 @@ pub(super) fn project_com_interface( }) } +pub(super) fn project_com_coclass( + meta: &ComCoclassMeta, + winmd_paths: &str, +) -> Result { + let associated_interfaces = meta + .associated_interfaces + .iter() + .map(|interface| project_com_interface(interface, winmd_paths)) + .collect::, _>>()?; + let primary_interface = associated_interfaces + .iter() + .find(|interface| interface.iid == meta.primary_interface.interface.iid) + .cloned() + .ok_or_else(|| { + format!( + "{}.{} primary interface {} was not projected", + meta.namespace, meta.name, meta.primary_interface.interface.name + ) + })?; + for method in &primary_interface.methods { + let public_name = method + .overload + .as_ref() + .map_or(method.camel_name.as_str(), |overload| { + overload.public_name.as_str() + }); + if matches!(public_name, "as" | "tryAs" | "supports") { + return Err(format!( + "{}.{} primary interface method `{public_name}` conflicts with the coclass interface-view API", + meta.namespace, meta.name + )); + } + } + + Ok(ProjectedComCoclass { + name: meta.name.clone(), + namespace: meta.namespace.clone(), + clsid: meta.clsid.clone(), + primary_interface, + associated_interfaces, + }) +} + +/// Counts the JS-surfaced ("input" direction) parameters of a method — this +/// is the argument count a caller actually sees and the value overload +/// dispatch bucketing keys off of. +fn input_arity(method: &ProjectedComMethod) -> usize { + method + .params + .iter() + .filter(|param| param.direction.is_input()) + .count() +} + +/// Groups same-name COM methods (real, metadata-driven overloads — e.g. +/// `IDCompositionEffectGroup::SetOpacity(float)` vs +/// `SetOpacity(IDCompositionAnimation*)`) into a single public JS method with +/// a validated runtime dispatcher, per the classic-COM-ABI skill's mandate to +/// resolve overloads in the projected IR rather than with renderer +/// heuristics. +/// +/// Grouping never merges methods by *name* alone: it computes, for every +/// group with more than one member, whether the members are safely +/// distinguishable at a call site (same-arity siblings must have one +/// parameter position with mutually distinct, unambiguous JS dispatch +/// shapes). If they cannot be safely distinguished, this fails closed with a +/// diagnostic naming the interface, method, and reason, rather than silently +/// keeping only the last-declared overload (the pre-existing bug) or +/// guessing at a heuristic disambiguation. +fn group_overloads( + methods: Vec, + interface_name: &str, +) -> Result, String> { + // Preserve first-seen order of each public name so `.d.ts`/`.js` render + // overload signatures contiguously even if metadata interleaves them with + // other members. + let mut order: Vec = Vec::new(); + let mut groups: std::collections::HashMap> = + std::collections::HashMap::new(); + for (index, method) in methods.iter().enumerate() { + groups + .entry(method.camel_name.clone()) + .or_insert_with(|| { + order.push(method.camel_name.clone()); + Vec::new() + }) + .push(index); + } + + let mut overloads: Vec> = vec![None; methods.len()]; + for name in &order { + let indices = &groups[name]; + if indices.len() < 2 { + continue; + } + for &index in indices { + let method = &methods[index]; + if method.kind != ProjectedComMethodKind::Normal { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one is a synthesized/dynamic-IID method, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } + if method.string_buffer.is_some() { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one uses a caller-allocated string buffer, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } + } + + let mut arity_buckets: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for &index in indices { + arity_buckets + .entry(input_arity(&methods[index])) + .or_default() + .push(index); + } + + for (arity, bucket) in arity_buckets { + if bucket.len() == 1 { + overloads[bucket[0]] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), + dispatch: OverloadDispatch::Arity, + }); + continue; + } + let key_param_index = (0..arity).find(|&key_index| { + let mut seen = Vec::new(); + bucket.iter().all(|&index| { + let (_, param) = input_params_of(&methods[index])[key_index]; + match dispatch_shape(¶m.typ) { + Some(shape) if !seen.contains(&shape) => { + seen.push(shape); + true + } + _ => false, + } + }) + }); + let Some(key_param_index) = key_param_index else { + return Err(format!( + "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ + position has mutually distinguishable JS shapes (arity/type/category); \ + overload dispatch cannot be safely generated", + bucket.len() + )); + }; + for &index in &bucket { + let (_, param) = input_params_of(&methods[index])[key_param_index]; + let shape = + dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); + overloads[index] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[index].vtable_index), + dispatch: OverloadDispatch::ArityAndShape { + key_param_index, + shape, + }, + }); + } + } + } + + Ok(methods + .into_iter() + .zip(overloads) + .map(|(mut method, overload)| { + method.overload = overload; + method + }) + .collect()) +} + +fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> { + method + .params + .iter() + .enumerate() + .filter(|(_, param)| param.direction.is_input()) + .collect() +} + fn project_method( interface: &ComInterfaceMeta, method: &MethodMeta, @@ -184,7 +377,7 @@ fn project_method( && matches!( typ, ComType::PointerAlias { - kind: super::ir::PointerAliasKind::StringPointer, + kind: super::ir::PointerAliasKind::StringPointer(_), .. } ) @@ -305,6 +498,7 @@ fn project_method( string_buffer, kind, doc: method.doc.clone(), + overload: None, }) } @@ -378,7 +572,7 @@ fn validate_owned_outputs( ComType::RawPointer | ComType::PointerAlias { kind: super::ir::PointerAliasKind::DataPointer - | super::ir::PointerAliasKind::StringPointer, + | super::ir::PointerAliasKind::StringPointer(_), .. } ) @@ -505,47 +699,29 @@ fn project_string_buffer(method: &MethodMeta) -> Result } fn string_buffer_param_is_optional(method: &MethodMeta, param_index: usize) -> bool { - let Some((_, count_index)) = - method - .params - .iter() - .enumerate() - .find_map(|(buffer_index, param)| match param.direction { - ParamDirection::OutStringBuffer { count_param_index } => { - Some((buffer_index, count_param_index)) - } - _ => None, - }) + let Some(count_index) = method + .params + .iter() + .find_map(|param| match param.direction { + ParamDirection::OutStringBuffer { count_param_index } => Some(count_param_index), + _ => None, + }) else { return false; }; - let Some(param) = method.params.get(param_index) else { - return false; - }; - let optional_shape = - param_index == count_index || (param_index > count_index && is_optional_find_data(param)); - optional_shape + // The count parameter is optional (defaultable) only when no other required + // input parameter follows it — otherwise a caller could not omit it without + // also omitting later required arguments. This authoritative, metadata-driven + // count relationship replaces any name-based ("cch..."/"pfd"/find-data) shape + // guessing. + param_index == count_index && method .params .iter() .skip(param_index + 1) .filter(|param| param.direction.is_input()) - .all(is_optional_find_data) -} - -fn is_optional_find_data(param: &ParamMeta) -> bool { - if !matches!(param.direction, ParamDirection::In | ParamDirection::Out) { - return false; - } - let name = param.name.to_ascii_lowercase(); - name == "pfd" - || name.contains("finddata") - || name.contains("find_data") - || matches!( - ¶m.typ, - TypeMeta::Struct { name, .. } - if name == "WIN32_FIND_DATAW" || name == "WIN32_FIND_DATAA" - ) + .count() + == 0 } fn pointer_alias_name(typ: &TypeMeta) -> Option<&str> { diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/types.rs b/tools/dynwinrt-codegen/src/codegen/com/project/types.rs index 45d27a77..4226df10 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/types.rs @@ -5,7 +5,8 @@ use crate::com_metadata::{is_native_isize, is_native_usize}; use crate::types::TypeMeta; use super::super::ir::{ - ComEnumUnderlying, ComPrimitive, ComScalarRepr, ComType, PointerAliasKind, UnsupportedComType, + ComEnumUnderlying, ComPrimitive, ComScalarRepr, ComType, PointerAliasKind, StringEncoding, + UnsupportedComType, }; pub(in crate::codegen::com) fn project_type(typ: &TypeMeta) -> Result { @@ -166,22 +167,14 @@ fn scalar_alias_underlying(name: &str, typ: &TypeMeta) -> Option fn classify_pointer_alias(name: &str) -> Option { if matches!( name, - "PWSTR" - | "PCWSTR" - | "PSTR" - | "PCSTR" - | "LPWSTR" - | "LPCWSTR" - | "LPSTR" - | "LPCSTR" - | "PWCHAR" - | "PCWCHAR" - | "LPWCH" - | "LPCWCH" - | "LPCH" - | "LPCCH" + "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR" | "PWCHAR" | "PCWCHAR" | "LPWCH" | "LPCWCH" ) { - Some(PointerAliasKind::StringPointer) + Some(PointerAliasKind::StringPointer(StringEncoding::Wide)) + } else if matches!( + name, + "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR" | "LPCH" | "LPCCH" + ) { + Some(PointerAliasKind::StringPointer(StringEncoding::Ansi)) } else if matches!( name, "PSID" diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index 6af6df7c..fc595442 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -114,15 +114,16 @@ fn render_com_only_package(com_subpath_names: &BTreeSet) -> String { let mut out = String::new(); out.push_str("{\n"); out.push_str(" \"name\": \"@winapp/bindings\",\n"); - out.push_str(" \"type\": \"module\",\n"); + out.push_str(" \"type\": \"commonjs\",\n"); out.push_str(" \"sideEffects\": false,\n"); out.push_str(" \"main\": \"./index.js\",\n"); out.push_str(" \"types\": \"./index.d.ts\",\n"); out.push_str(" \"exports\": {\n"); out.push_str(" \".\": {\n"); - out.push_str(" \"types\": \"./index.d.ts\",\n"); - out.push_str(" \"import\": \"./index.js\",\n"); - out.push_str(" \"default\": \"./index.js\"\n"); + out.push_str(" \"types\": \"./com/index.d.ts\",\n"); + out.push_str(" \"import\": \"./com/index.mjs\",\n"); + out.push_str(" \"require\": \"./com/index.js\",\n"); + out.push_str(" \"default\": \"./com/index.js\"\n"); out.push_str(" }"); // Preserve the original COM-only deep-import paths while storing all COM @@ -132,6 +133,7 @@ fn render_com_only_package(com_subpath_names: &BTreeSet) -> String { out.push_str(&format!(" \"./{}\": {{\n", name)); out.push_str(&format!(" \"types\": \"./com/{}.d.ts\",\n", name)); out.push_str(&format!(" \"import\": \"./com/{}.js\",\n", name)); + out.push_str(&format!(" \"require\": \"./com/{}.js\",\n", name)); out.push_str(&format!(" \"default\": \"./com/{}.js\"\n", name)); out.push_str(" }"); } @@ -150,11 +152,13 @@ fn append_com_exports(out: &mut String, com_subpath_names: &BTreeSet) { out.push_str(",\n"); out.push_str(" \"./com\": {\n"); out.push_str(" \"types\": \"./com/index.d.ts\",\n"); - out.push_str(" \"import\": \"./com/index.js\"\n"); + out.push_str(" \"import\": \"./com/index.mjs\",\n"); + out.push_str(" \"require\": \"./com/index.js\"\n"); out.push_str(" },\n"); out.push_str(" \"./com/*\": {\n"); out.push_str(" \"types\": \"./com/*.d.ts\",\n"); - out.push_str(" \"import\": \"./com/*.js\"\n"); + out.push_str(" \"import\": \"./com/*.js\",\n"); + out.push_str(" \"require\": \"./com/*.js\"\n"); out.push_str(" }"); } @@ -233,7 +237,8 @@ mod tests { assert!(out.contains("\"./com/*\"")); assert!(out.contains("\"types\": \"./com/*.d.ts\"")); assert!(out.contains("\"import\": \"./com/*.js\"")); - assert!(!out.contains("\"require\": \"./com/")); + assert!(out.contains("\"require\": \"./com/index.js\"")); + assert!(out.contains("\"require\": \"./com/*.js\"")); } #[test] @@ -246,10 +251,13 @@ mod tests { com_subpath_names: &com, }); - assert!(out.contains("\"type\": \"module\"")); + assert!(out.contains("\"type\": \"commonjs\"")); assert!(out.contains("\"./ITaskbarList3\"")); assert!(out.contains("\"types\": \"./com/ITaskbarList3.d.ts\"")); assert!(out.contains("\"import\": \"./com/ITaskbarList3.js\"")); + assert!(out.contains("\"require\": \"./com/ITaskbarList3.js\"")); + assert!(out.contains("\"import\": \"./com/index.mjs\"")); + assert!(out.contains("\"require\": \"./com/index.js\"")); assert!(out.contains("\"./com/*\"")); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs index 44750772..fbae8ca0 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs @@ -195,9 +195,89 @@ pub(super) fn convert_to_cjs_with_lazy( out } +/// Convert generated ESM to CommonJS while loading every relative import +/// eagerly. Classic COM uses this mode because coclass modules inherit from +/// interface classes at module initialization time and therefore require the +/// real base constructor, not a lazy getter/proxy. +pub(crate) fn convert_to_cjs_with_eager( + esm: &str, + runtime_sources: &std::collections::HashSet, +) -> String { + use std::collections::BTreeMap; + + let mut imports: Vec<(Vec, String)> = Vec::new(); + let mut relative_order = Vec::new(); + let mut relative_symbols: BTreeMap> = BTreeMap::new(); + let mut body = String::with_capacity(esm.len()); + let mut in_header = true; + + for line in esm.split_inclusive('\n') { + if in_header { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with("//") { + continue; + } + if let Some((symbols, source)) = parse_import_line(trimmed) { + if runtime_sources.contains(&source) || !source.starts_with("./") { + imports.push((symbols, source)); + } else { + if !relative_symbols.contains_key(&source) { + relative_order.push(source.clone()); + } + let entry = relative_symbols.entry(source).or_default(); + for symbol in symbols { + if !entry.contains(&symbol) { + entry.push(symbol); + } + } + } + continue; + } + in_header = false; + } + body.push_str(line); + } + + let (transformed_body, exported_names) = strip_exports_and_collect(&body); + let mut out = String::with_capacity(esm.len() + 1024); + out.push_str("// Generated by dynwinrt-codegen \u{2014} do not edit\n"); + for (symbols, source) in imports { + let symbols = dedupe_preserving_order(&symbols); + if !symbols.is_empty() { + out.push_str(&format!( + "const {{ {} }} = require('{}');\n", + symbols.join(", "), + source + )); + } + } + for source in relative_order { + let symbols = dedupe_preserving_order(&relative_symbols[&source]); + if !symbols.is_empty() { + out.push_str(&format!( + "const {{ {} }} = require('{}');\n", + symbols.join(", "), + source + )); + } + } + out.push('\n'); + out.push_str(&resolve_ref_markers( + &transformed_body, + &std::collections::HashSet::new(), + )); + if !out.ends_with('\n') { + out.push('\n'); + } + for name in exported_names { + out.push_str(&format!("exports.{name} = {name};\n")); + } + out +} + #[cfg(test)] mod tests { - use super::convert_to_cjs_with_lazy; + use super::{convert_to_cjs_with_eager, convert_to_cjs_with_lazy}; use std::collections::HashSet; #[test] @@ -231,6 +311,24 @@ export function cast(value) {\n\ "{cjs}" ); } + + #[test] + fn eager_mode_preserves_real_base_class_imports() { + let esm = "\ +import { DynCom } from '@microsoft/dynwinrt/com';\n\ +import { IThing4, IID_IThing4 } from './IThing4.js';\n\ +export class Thing extends IThing4 {\n\ + constructor() { super(DynCom.coCreateInstance('clsid', IID_IThing4)); }\n\ +}\n"; + let runtime = HashSet::from(["@microsoft/dynwinrt/com".to_string()]); + + let cjs = convert_to_cjs_with_eager(esm, &runtime); + + assert!(cjs.contains("const { IThing4, IID_IThing4 } = require('./IThing4.js');")); + assert!(cjs.contains("class Thing extends IThing4")); + assert!(cjs.contains("exports.Thing = Thing;")); + assert!(!cjs.contains("__get_IThing4")); + } } /// Parse `import { A, B } from 'source';` (single-line). Returns Some(symbols, source) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs index d14e0a1f..c0d00968 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs @@ -7,7 +7,7 @@ //! lazy sibling requires. This keeps the projection layer simple (still emits //! ESM shapes) while giving consumers fast startup. -mod commonjs; +pub(crate) mod commonjs; mod helpers; use crate::codegen::winrt::javascript::ir::*; diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 93d3fad2..d8b5e18b 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -85,6 +85,15 @@ pub struct ComInterfaceMeta { pub referenced_enums: Vec, } +#[derive(Debug, Clone)] +pub struct ComCoclassMeta { + pub name: String, + pub namespace: String, + pub clsid: String, + pub primary_interface: ComInterfaceMeta, + pub associated_interfaces: Vec, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum ComEnumValue { Signed(i64), @@ -115,6 +124,17 @@ pub fn parse_com_interface( parse_com_interface_from_index(&index, namespace, name) } +pub fn parse_com_coclass( + winmd_paths: &str, + namespace: &str, + name: &str, +) -> Result, String> { + let Some(index) = crate::meta::load_index(winmd_paths) else { + return Ok(None); + }; + parse_com_coclass_from_index(&index, namespace, name) +} + pub fn parse_com_enum(winmd_paths: &str, namespace: &str, name: &str) -> Option { let index = crate::meta::load_index(winmd_paths)?; let def = index.get(namespace, name).next()?; @@ -243,6 +263,95 @@ fn parse_com_interface_from_index( }) } +fn parse_com_coclass_from_index( + index: &reader::Index, + namespace: &str, + name: &str, +) -> Result, String> { + let Some(def) = index.get(namespace, name).next() else { + return Ok(None); + }; + if !is_com_coclass(&def) { + return Ok(None); + } + let clsid = crate::meta::extract_iid(&def); + if clsid.is_empty() { + return Err(format!( + "{namespace}.{name} is coclass-shaped but has no CLSID" + )); + } + + // Windows.Win32.winmd represents coclasses as GUID-bearing ValueType + // definitions without InterfaceImpl rows. Associate interfaces using the + // metadata naming convention already used for interface activation, then + // choose a primary from the real interface inheritance graph. Numeric + // suffixes never determine which interface is most derived. + let mut associated_interfaces = index + .all() + .filter(|candidate| { + candidate.namespace() == namespace + && candidate + .flags() + .contains(windows_metadata::TypeAttributes::Interface) + && coclass_name_candidates(candidate.name()) + .iter() + .any(|candidate_name| candidate_name == name) + }) + .filter_map(|candidate| { + parse_com_interface_from_index(index, namespace, candidate.name()) + .filter(|interface| interface.is_iunknown_rooted) + }) + .collect::>(); + associated_interfaces.sort_by(|left, right| { + left.own_methods_start + .cmp(&right.own_methods_start) + .then_with(|| left.interface.name.cmp(&right.interface.name)) + }); + associated_interfaces.dedup_by(|left, right| left.interface.iid == right.interface.iid); + + let primary_interface = + select_primary_coclass_interface(namespace, name, &associated_interfaces)?; + + Ok(Some(ComCoclassMeta { + name: name.to_string(), + namespace: namespace.to_string(), + clsid, + primary_interface, + associated_interfaces, + })) +} + +fn select_primary_coclass_interface( + namespace: &str, + coclass_name: &str, + associated_interfaces: &[ComInterfaceMeta], +) -> Result { + let leaves = associated_interfaces + .iter() + .filter(|candidate| { + !associated_interfaces.iter().any(|other| { + other.interface.iid != candidate.interface.iid + && other.base_chain.contains(&candidate.interface.name) + }) + }) + .collect::>(); + match leaves.as_slice() { + [primary] => Ok((*primary).clone()), + [] => Err(format!( + "{namespace}.{coclass_name} has no safely associated IUnknown-rooted interface" + )), + multiple => Err(format!( + "{namespace}.{coclass_name} has multiple unrelated most-derived interfaces ({}); \ + Windows.Win32 metadata does not identify a default interface", + multiple + .iter() + .map(|interface| interface.interface.name.as_str()) + .collect::>() + .join(", ") + )), + } +} + fn parse_methods( index: &reader::Index, def: &reader::TypeDef, @@ -279,8 +388,17 @@ fn parse_methods( matches!(typ, windows_metadata::Type::Array(_)), ); let mapped_type = map_parameter_type(typ, &direction, index); + // Use the metadata's own `NativeArrayInfo(CountParamIndex = ...)` as the sole, + // authoritative source for buffer/count relationships. A `[out]` `PWSTR`/`PSTR` + // buffer with an authoritative count becomes a caller-owned string buffer; any + // other `[out]`/`[out, in]` array-shaped output with a count relationship is an + // unsupported native buffer (no name- or adjacency-based guessing). if let Some(count_param_index) = native_array_count_param(¶m) { - if direction.is_output() && !is_string_buffer(&mapped_type) { + if direction == ParamDirection::Out && is_string_buffer(&mapped_type) { + if let Some(count_param_index) = count_param_index { + direction = ParamDirection::OutStringBuffer { count_param_index }; + } + } else if direction.is_output() { direction = ParamDirection::UnsupportedNativeArray { count_param_index }; } } @@ -311,18 +429,34 @@ fn parse_methods( direction, }); } - mark_caller_owned_string_buffers(&mut params); let return_type = (signature.return_type != windows_metadata::Type::Void) .then(|| map_return_type(&signature.return_type, index)); let preserve_hresult = method.has_attribute("CanReturnMultipleSuccessValuesAttribute") || is_known_semantic_hresult(def.namespace(), def.name(), method.name()); + // win32metadata does not embed textual doc comments (no sibling + // `.xml` file like WinRT's `xml_doc.rs`), but it does attach a + // `DocumentationAttribute` with a `learn.microsoft.com` reference + // URL to most methods. Surface that as the method's `doc`, so + // generated code can at least link back to the canonical docs. + let doc = method + .find_attribute("DocumentationAttribute") + .and_then(|attribute| { + attribute + .value() + .into_iter() + .next() + .and_then(|(_, value)| match value { + windows_metadata::Value::Utf8(value) => Some(value), + _ => None, + }) + }); MethodMeta { name, vtable_index: base_offset + index_in_interface, params, return_type, preserve_hresult, - doc: None, + doc, owned_outputs, } }) @@ -604,8 +738,23 @@ fn find_coclass( namespace: &str, interface_name: &str, ) -> (Option, Option) { + for candidate in coclass_name_candidates(interface_name) { + let Some(def) = index.get(namespace, &candidate).next() else { + continue; + }; + if is_com_coclass(&def) { + let clsid = crate::meta::extract_iid(&def); + if !clsid.is_empty() { + return (Some(candidate), Some(clsid)); + } + } + } + (None, None) +} + +fn coclass_name_candidates(interface_name: &str) -> Vec { let Some(stripped) = interface_name.strip_prefix('I') else { - return (None, None); + return Vec::new(); }; let mut candidates = vec![stripped.to_string()]; let without_version = stripped @@ -614,23 +763,18 @@ fn find_coclass( if without_version != stripped { candidates.push(without_version); } - for candidate in candidates { - let Some(def) = index.get(namespace, &candidate).next() else { - continue; - }; - let is_coclass = matches!( + candidates +} + +fn is_com_coclass(def: &reader::TypeDef) -> bool { + !def.flags() + .contains(windows_metadata::TypeAttributes::Interface) + && matches!( def.extends() .map(|base| (base.namespace().to_string(), base.name().to_string())), Some((namespace, name)) if namespace == "System" && name == "ValueType" - ); - if is_coclass { - let clsid = crate::meta::extract_iid(&def); - if !clsid.is_empty() { - return (Some(candidate), Some(clsid)); - } - } - } - (None, None) + ) + && !crate::meta::extract_iid(def).is_empty() } fn collect_referenced_enums(index: &reader::Index, interface: &InterfaceMeta) -> Vec { @@ -662,42 +806,6 @@ fn collect_referenced_enums(index: &reader::Index, interface: &InterfaceMeta) -> result } -fn mark_caller_owned_string_buffers(params: &mut [ParamMeta]) { - for index in 0..params.len().saturating_sub(1) { - if params[index].direction == ParamDirection::Out - && is_string_buffer(¶ms[index].typ) - && params[index + 1].direction == ParamDirection::In - && is_string_buffer_count(¶ms[index].typ, ¶ms[index + 1]) - { - params[index].direction = ParamDirection::OutStringBuffer { - count_param_index: index + 1, - }; - } - } - let count_index = params.iter().find_map(|param| match param.direction { - ParamDirection::OutStringBuffer { count_param_index } => Some(count_param_index), - _ => None, - }); - if let Some(count_index) = count_index { - for param in params.iter_mut().skip(count_index + 1) { - let name = param.name.to_ascii_lowercase(); - let is_find_data = name == "pfd" - || name.contains("finddata") - || matches!( - ¶m.typ, - TypeMeta::Struct { name, .. } - if name == "WIN32_FIND_DATAW" || name == "WIN32_FIND_DATAA" - ); - if is_find_data - && matches!(param.direction, ParamDirection::Out | ParamDirection::InOut) - { - param.direction = ParamDirection::In; - param.typ = TypeMeta::Object; - } - } - } -} - fn is_string_buffer(typ: &TypeMeta) -> bool { matches!( typ, @@ -706,21 +814,6 @@ fn is_string_buffer(typ: &TypeMeta) -> bool { ) } -fn is_string_buffer_count(buffer_type: &TypeMeta, param: &ParamMeta) -> bool { - let name = param.name.to_ascii_lowercase(); - let is_wide = matches!( - buffer_type, - TypeMeta::Struct { namespace, name, .. } - if namespace == "Windows.Win32.Foundation" && name == "PWSTR" - ); - matches!(param.typ, TypeMeta::I32 | TypeMeta::U32) - && (name.starts_with("cch") - || (!is_wide && name.starts_with("cb")) - || matches!(name.as_str(), "len" | "length" | "size" | "max" | "count") - || name.starts_with("max") - || name.starts_with("size")) -} - pub fn find_runtime_class_default_iid( winmd_paths: &str, simple_name: &str, @@ -791,6 +884,46 @@ pub fn discover_newest_windows_winmd() -> Option { mod tests { use super::*; + fn interface(name: &str, iid: &str, base_chain: &[&str]) -> ComInterfaceMeta { + ComInterfaceMeta { + interface: InterfaceMeta { + name: name.into(), + namespace: "Tests".into(), + iid: iid.into(), + ..Default::default() + }, + base_offset: 3, + is_iunknown_rooted: true, + base_chain: base_chain.iter().map(|name| (*name).into()).collect(), + coclass_clsid: None, + coclass_name: None, + own_methods_start: 3, + referenced_enums: Vec::new(), + } + } + + #[test] + fn coclass_primary_uses_inheritance_leaf_not_numeric_suffix() { + let interfaces = vec![ + interface("IThing9", "1", &["IUnknown"]), + interface("IThing", "2", &["IThing9", "IUnknown"]), + ]; + + let primary = select_primary_coclass_interface("Tests", "Thing", &interfaces).unwrap(); + assert_eq!(primary.interface.name, "IThing"); + } + + #[test] + fn coclass_primary_rejects_unrelated_leaves() { + let interfaces = vec![ + interface("IThing", "1", &["IUnknown"]), + interface("IThing2", "2", &["IUnknown"]), + ]; + + let error = select_primary_coclass_interface("Tests", "Thing", &interfaces).unwrap_err(); + assert!(error.contains("multiple unrelated")); + } + #[test] fn in_out_is_com_only() { use windows_metadata::ParamAttributes; @@ -810,42 +943,6 @@ mod tests { assert!(!is_canonical_hstring_name("Contoso.Interop", "HSTRING")); } - #[test] - fn find_data_after_string_buffer_is_caller_owned_pointer() { - let mut params = vec![ - ParamMeta { - name: "pszFile".into(), - typ: TypeMeta::Struct { - namespace: "Windows.Win32.Foundation".into(), - name: "PWSTR".into(), - fields: Vec::new(), - }, - direction: ParamDirection::Out, - }, - ParamMeta { - name: "cch".into(), - typ: TypeMeta::I32, - direction: ParamDirection::In, - }, - ParamMeta { - name: "pfd".into(), - typ: TypeMeta::Object, - direction: ParamDirection::InOut, - }, - ]; - - mark_caller_owned_string_buffers(&mut params); - - assert_eq!( - params[0].direction, - ParamDirection::OutStringBuffer { - count_param_index: 1 - } - ); - assert_eq!(params[2].direction, ParamDirection::In); - assert!(matches!(params[2].typ, TypeMeta::Object)); - } - #[test] fn item_id_list_double_pointer_uses_cotaskmem_ownership() { let typ = windows_metadata::Type::PtrMut( diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 397fdfc2..9cb952f9 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -311,6 +311,7 @@ fn run() -> Result<(), String> { // First: partition into WinRT classes and classic-COM interfaces. let mut classes = Vec::new(); let mut com_interfaces: Vec = Vec::new(); + let mut com_coclasses: Vec = Vec::new(); for (ns, cls) in &class_requests { if let Some(com_iface) = com_metadata::parse_com_interface(&winmd, ns, cls) { // Route through classic-COM path when: @@ -339,6 +340,10 @@ fn run() -> Result<(), String> { )); } } + if let Some(coclass) = com_metadata::parse_com_coclass(&winmd, ns, cls)? { + com_coclasses.push(coclass); + continue; + } match meta::parse_class(&winmd, ns, cls) { Some(mut c) => { doc_table.apply_to_class(&mut c); @@ -357,7 +362,7 @@ fn run() -> Result<(), String> { // JS files into a Python output directory would produce the // wrong artifact types with no diagnostic. Reject the // combination up front. - if lang != "js" && !com_interfaces.is_empty() { + if lang != "js" && (!com_interfaces.is_empty() || !com_coclasses.is_empty()) { let mut offenders: Vec = Vec::new(); for ci in &com_interfaces { offenders.push(format!( @@ -365,6 +370,12 @@ fn run() -> Result<(), String> { ci.interface.namespace, ci.interface.name )); } + for coclass in &com_coclasses { + offenders.push(format!( + "{}.{} (classic-COM coclass)", + coclass.namespace, coclass.name + )); + } return Err(format!( "`--lang {}` is not supported for classic-COM interfaces \ (they emit only `.js` + `.d.ts` today). \ @@ -379,17 +390,19 @@ fn run() -> Result<(), String> { // Classic COM occupies its own ESM subpackage so its symbols // cannot collide with or leak into the WinRT root barrel. - if !com_interfaces.is_empty() { + if !com_interfaces.is_empty() || !com_coclasses.is_empty() { let com_output_dir = output_dir.join("com"); - if !dry_run { - fs::create_dir_all(&com_output_dir).map_err(|e| { - format!( - "Failed to create COM output directory '{}': {}", - com_output_dir.display(), - e - ) - })?; - } + + // Project every requested COM interface into memory FIRST, + // before writing anything. A later interface's projection + // failure (e.g. an unsupported native struct) must not + // leave an earlier interface's files newly written on + // disk — this batch is all-or-nothing. Pre-existing files + // from a prior, separate invocation (incremental + // generation) are untouched either way, since we never + // delete anything here. + let mut generated = + Vec::with_capacity(com_interfaces.len() + com_coclasses.len()); for com_iface in &com_interfaces { let out = com::generate_com_interface_files(com_iface, &winmd).map_err(|e| { @@ -398,25 +411,62 @@ fn run() -> Result<(), String> { com_iface.interface.name, e ) })?; - let js_name = format!("{}.js", com_iface.interface.name); - let dts_name = format!("{}.d.ts", com_iface.interface.name); - if !dry_run { - fs::write(com_output_dir.join(&js_name), &out.js) - .map_err(|e| format!("Failed to write {}: {}", js_name, e))?; - fs::write(com_output_dir.join(&dts_name), &out.dts) - .map_err(|e| format!("Failed to write {}: {}", dts_name, e))?; - for (name, content) in &out.extra_files { - fs::write(com_output_dir.join(name), content) - .map_err(|e| format!("Failed to write {}: {}", name, e))?; + generated.push((com_iface.interface.name.clone(), out)); + } + for coclass in &com_coclasses { + let out = + com::generate_com_coclass_files(coclass, &winmd).map_err(|e| { + format!( + "Classic-COM coclass codegen for {} failed: {}", + coclass.name, e + ) + })?; + generated.push((coclass.name.clone(), out)); + } + + let mut planned_files = BTreeMap::new(); + for (name, out) in &generated { + let mut files = vec![ + (format!("{name}.js"), out.js.clone()), + (format!("{name}.d.ts"), out.dts.clone()), + ]; + files.extend(out.extra_files.iter().cloned()); + for (file_name, content) in files { + if let Some(existing) = planned_files.get(&file_name) + && existing != &content + { + return Err(format!( + "Classic-COM generation produced conflicting `{file_name}` outputs; \ + request a single primary interface for each coclass" + )); } + planned_files.insert(file_name, content); + } + } + + if !dry_run { + fs::create_dir_all(&com_output_dir).map_err(|e| { + format!( + "Failed to create COM output directory '{}': {}", + com_output_dir.display(), + e + ) + })?; + for (file_name, content) in &planned_files { + fs::write(com_output_dir.join(file_name), content) + .map_err(|e| format!("Failed to write {}: {}", file_name, e))?; + } + } + for (name, out) in &generated { + if dry_run { + println!("[dry-run] Would generate {}", name); + } else { println!( "Generated {} ({} .js/.d.ts + {} extras)", - com_iface.interface.name, + name, 2, out.extra_files.len() ); - } else { - println!("[dry-run] Would generate {}", com_iface.interface.name); } } if !dry_run { @@ -1186,7 +1236,7 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { } let content = fs::read_to_string(&path) .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - let exports = collect_com_esm_exports(&content); + let exports = collect_com_cjs_exports(&content); if !exports.is_empty() { modules.insert(module.to_string(), exports); } @@ -1199,12 +1249,16 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { exports.iter().cloned().collect::>().join(", ") )); } - fs::write(com_output_dir.join("index.js"), &index) + let cjs_index = typescript::esm_index_to_cjs_getter(&index); + let esm_index = typescript::esm_index_to_esm(&index); + fs::write(com_output_dir.join("index.js"), &cjs_index) .map_err(|error| format!("Failed to write COM index.js: {error}"))?; + fs::write(com_output_dir.join("index.mjs"), &esm_index) + .map_err(|error| format!("Failed to write COM index.mjs: {error}"))?; fs::write(com_output_dir.join("index.d.ts"), &index) .map_err(|error| format!("Failed to write COM index.d.ts: {error}"))?; - let package = "{\n \"type\": \"module\",\n \"sideEffects\": false\n}\n"; + let package = "{\n \"type\": \"commonjs\",\n \"sideEffects\": false\n}\n"; fs::write(com_output_dir.join("package.json"), package) .map_err(|error| format!("Failed to write COM package boundary: {error}"))?; Ok(()) @@ -1218,13 +1272,18 @@ fn finalize_com_generation(output_dir: &Path) -> Result<(), String> { } fn write_com_root_compatibility_barrels(output_dir: &Path) -> Result<(), String> { - let com_index_path = output_dir.join("com").join("index.js"); - let com_index = fs::read_to_string(&com_index_path) - .map_err(|error| format!("Failed to read {}: {error}", com_index_path.display()))?; - let root_index = com_index.replace("from './", "from './com/"); - fs::write(output_dir.join("index.js"), &root_index) + let com_dir = output_dir.join("com"); + let com_js_path = com_dir.join("index.js"); + let com_dts_path = com_dir.join("index.d.ts"); + let com_js = fs::read_to_string(&com_js_path) + .map_err(|error| format!("Failed to read {}: {error}", com_js_path.display()))?; + let com_dts = fs::read_to_string(&com_dts_path) + .map_err(|error| format!("Failed to read {}: {error}", com_dts_path.display()))?; + let root_js = com_js.replace(", './", ", './com/"); + let root_dts = com_dts.replace("from './", "from './com/"); + fs::write(output_dir.join("index.js"), &root_js) .map_err(|error| format!("Failed to write COM compatibility index.js: {error}"))?; - fs::write(output_dir.join("index.d.ts"), root_index) + fs::write(output_dir.join("index.d.ts"), root_dts) .map_err(|error| format!("Failed to write COM compatibility index.d.ts: {error}"))?; Ok(()) } @@ -1236,16 +1295,17 @@ fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { let package_path = output_dir.join("package.json"); let index_path = output_dir.join("index.js"); - if !package_path.is_file() || !index_path.is_file() { + let index_dts_path = output_dir.join("index.d.ts"); + if !package_path.is_file() || !index_path.is_file() || !index_dts_path.is_file() { return Ok(()); } let package = fs::read_to_string(&package_path) .map_err(|error| format!("Failed to read {}: {error}", package_path.display()))?; - let index = fs::read_to_string(&index_path) - .map_err(|error| format!("Failed to read {}: {error}", index_path.display()))?; + let index = fs::read_to_string(&index_dts_path) + .map_err(|error| format!("Failed to read {}: {error}", index_dts_path.display()))?; if !package.contains("\"name\": \"@winapp/bindings\"") - || !package.contains("\"type\": \"module\"") - || !index.starts_with("// Generated by dynwinrt-codegen - do not edit\n") + || !(package.contains("\"type\": \"module\"") || package.contains("\"type\": \"commonjs\"")) + || !index.starts_with("// Generated by dynwinrt-codegen") { return Ok(()); } @@ -1273,6 +1333,7 @@ fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { for path in [ output_dir.join("index.js"), + output_dir.join("index.mjs"), output_dir.join("index.d.ts"), package_path, ] { @@ -1351,7 +1412,7 @@ fn write_bindings_manifest(output_dir: &Path) -> Result<(), String> { } fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { - let index_path = com_output_dir.join("index.js"); + let index_path = com_output_dir.join("index.d.ts"); if !index_path.is_file() { return Ok(BTreeSet::new()); } @@ -1360,22 +1421,19 @@ fn collect_com_subpath_names(com_output_dir: &Path) -> Result, Ok(collect_com_index_modules(&index)) } -fn collect_com_esm_exports(content: &str) -> BTreeSet { - const PREFIXES: &[&str] = &["export const ", "export class ", "export function "]; +fn collect_com_cjs_exports(content: &str) -> BTreeSet { content .lines() .filter_map(|line| { let line = line.trim_start(); - let rest = PREFIXES - .iter() - .find_map(|prefix| line.strip_prefix(prefix))?; + let rest = line.strip_prefix("exports.")?; let name = rest .chars() .take_while(|character| { character.is_ascii_alphanumeric() || *character == '_' || *character == '$' }) .collect::(); - (!name.is_empty()).then_some(name) + (!name.is_empty() && rest[name.len()..].trim_start().starts_with('=')).then_some(name) }) .collect() } diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts index ecf25267..ae963063 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts @@ -7,10 +7,17 @@ export type HWND = bigint | number; export declare const IID_IDataTransferManagerInterop: unknown; export declare class IDataTransferManagerInterop { - /** Activate the projected WinRT class and QI to the interop. */ + static readonly IID: typeof IID_IDataTransferManagerInterop; + protected constructor(obj: unknown); + /** Activate the projected WinRT class and QI to the interop. + * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */ static create(): IDataTransferManagerInterop; /** Wrap an existing native COM pointer (for QueryInterface bridging). */ static _fromNative(obj: unknown): IDataTransferManagerInterop; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-idatatransfermanagerinterop-getforwindow} */ getForWindow(appWindow: HWND | Buffer | Uint8Array): DynWinRtValue; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-idatatransfermanagerinterop-showshareuiforwindow} */ showShareUIForWindow(appWindow: HWND | Buffer | Uint8Array): void; } diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js index c33d6ba3..2cdb160b 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js @@ -1,25 +1,31 @@ // Generated by dynwinrt-codegen — do not edit -import { DynCom, DynComMethodSig, DynWinRtValue, WinGuid } from '@microsoft/dynwinrt/com'; +const { DynCom, DynComMethodSig, DynWinRtValue, WinGuid } = require('@microsoft/dynwinrt/com'); -export const IID_IDataTransferManagerInterop = WinGuid.parse('3a3dcd6c-3eab-43dc-bcde-45671ce800c8'); +const IID_IDataTransferManagerInterop = WinGuid.parse('3a3dcd6c-3eab-43dc-bcde-45671ce800c8'); const IID_DataTransferManager_default = WinGuid.parse('a5caee9b-8708-49d1-8d36-67d25a8da00c'); let _IDataTransferManagerInteropCache; const _IDataTransferManagerInterop = new Proxy({}, { get(_target, prop) { _IDataTransferManagerInteropCache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.IDataTransferManagerInterop', IID_IDataTransferManagerInterop) - .addMethod('GetForWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addOut(DynCom.pointerType())) - .addMethod('ShowShareUIForWindow', new DynComMethodSig().addIn(DynCom.pointerType())); + .addMethodAt(3, 'GetForWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addOut(DynCom.ownedComPointerType())) + .addMethodAt(4, 'ShowShareUIForWindow', new DynComMethodSig().addIn(DynCom.pointerType())); const value = _IDataTransferManagerInteropCache[prop]; return typeof value === 'function' ? value.bind(_IDataTransferManagerInteropCache) : value; }, }); -export class IDataTransferManagerInterop { +class IDataTransferManagerInterop { + static IID = IID_IDataTransferManagerInterop; _obj; constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return new IDataTransferManagerInterop(obj); } - /** Create a new `IDataTransferManagerInterop` by activating the `Windows.ApplicationModel.DataTransfer.DataTransferManager` factory and QI'ing to the interop. */ + static _fromNative(obj) { return Object.assign(Object.create(IDataTransferManagerInterop.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); + } + /** Create a new `IDataTransferManagerInterop` by activating the `Windows.ApplicationModel.DataTransfer.DataTransferManager` factory and QI'ing to the interop. + * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */ static create() { const factory = DynWinRtValue.activationFactory('Windows.ApplicationModel.DataTransfer.DataTransferManager'); const _obj = factory.cast(IID_IDataTransferManagerInterop); @@ -30,7 +36,10 @@ export class IDataTransferManagerInterop { const _out = DynCom.adoptComPointer(_raw, IID_DataTransferManager_default); return _out; } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-idatatransfermanagerinterop-showshareuiforwindow} */ showShareUIForWindow(appWindow) { _IDataTransferManagerInterop.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(appWindow))]); } } +exports.IID_IDataTransferManagerInterop = IID_IDataTransferManagerInterop; +exports.IDataTransferManagerInterop = IDataTransferManagerInterop; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts new file mode 100644 index 00000000..3194de17 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts @@ -0,0 +1,25 @@ +// Generated by dynwinrt-codegen — do not edit + +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HWND = bigint | number; + +export declare const IID_ITaskbarList: unknown; + +export declare class ITaskbarList { + static readonly IID: typeof IID_ITaskbarList; + protected constructor(obj: unknown); + /** Wrap an existing native COM pointer (for QueryInterface bridging). */ + static _fromNative(obj: unknown): ITaskbarList; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd: HWND | Buffer | Uint8Array): void; +} diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js new file mode 100644 index 00000000..8ee04d3e --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js @@ -0,0 +1,51 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); + +const IID_ITaskbarList = WinGuid.parse('56fdf342-fd6d-11d0-958a-006097c9a090'); + +let _ITaskbarListCache; +const _ITaskbarList = new Proxy({}, { + get(_target, prop) { + _ITaskbarListCache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.ITaskbarList', IID_ITaskbarList) + .addMethodAt(3, 'HrInit', new DynComMethodSig()) + .addMethodAt(4, 'AddTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(5, 'DeleteTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(6, 'ActivateTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(7, 'SetActiveAlt', new DynComMethodSig().addIn(DynCom.pointerType())); + const value = _ITaskbarListCache[prop]; + return typeof value === 'function' ? value.bind(_ITaskbarListCache) : value; + }, +}); + +class ITaskbarList { + static IID = IID_ITaskbarList; + _obj; + constructor(obj) { this._obj = obj; } + static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit() { + _ITaskbarList.method(3).invoke(this._obj, []); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd) { + _ITaskbarList.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd) { + _ITaskbarList.method(5).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd) { + _ITaskbarList.method(6).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd) { + _ITaskbarList.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } +} +exports.IID_ITaskbarList = IID_ITaskbarList; +exports.ITaskbarList = ITaskbarList; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts new file mode 100644 index 00000000..d971c8a8 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts @@ -0,0 +1,27 @@ +// Generated by dynwinrt-codegen — do not edit + +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HWND = bigint | number; + +export declare const IID_ITaskbarList2: unknown; + +export declare class ITaskbarList2 { + static readonly IID: typeof IID_ITaskbarList2; + protected constructor(obj: unknown); + /** Wrap an existing native COM pointer (for QueryInterface bridging). */ + static _fromNative(obj: unknown): ITaskbarList2; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ + markFullscreenWindow(hwnd: HWND | Buffer | Uint8Array, fFullscreen: boolean): void; +} diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js new file mode 100644 index 00000000..42beba4f --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js @@ -0,0 +1,56 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); + +const IID_ITaskbarList2 = WinGuid.parse('602d4995-b13a-429b-a66e-1935e44f4317'); + +let _ITaskbarList2Cache; +const _ITaskbarList2 = new Proxy({}, { + get(_target, prop) { + _ITaskbarList2Cache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.ITaskbarList2', IID_ITaskbarList2) + .addMethodAt(3, 'HrInit', new DynComMethodSig()) + .addMethodAt(4, 'AddTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(5, 'DeleteTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(6, 'ActivateTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(7, 'SetActiveAlt', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(8, 'MarkFullscreenWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())); + const value = _ITaskbarList2Cache[prop]; + return typeof value === 'function' ? value.bind(_ITaskbarList2Cache) : value; + }, +}); + +class ITaskbarList2 { + static IID = IID_ITaskbarList2; + _obj; + constructor(obj) { this._obj = obj; } + static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList2.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit() { + _ITaskbarList2.method(3).invoke(this._obj, []); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd) { + _ITaskbarList2.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd) { + _ITaskbarList2.method(5).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd) { + _ITaskbarList2.method(6).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd) { + _ITaskbarList2.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ + markFullscreenWindow(hwnd, fFullscreen) { + _ITaskbarList2.method(8).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(fFullscreen ? 1 : 0)]); + } +} +exports.IID_ITaskbarList2 = IID_ITaskbarList2; +exports.ITaskbarList2 = ITaskbarList2; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts index 67b26bbd..b089fbbf 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts @@ -7,32 +7,52 @@ export type HICON = bigint | number; export type HIMAGELIST = bigint | number; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HWND = bigint | number; -/** Win32 NUL-terminated string pointer. Pass a `Buffer` holding the string bytes (including the NUL terminator), or pass a raw pointer as `bigint`. */ -export type PWSTR = bigint | Buffer; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`. */ +export type PWSTR = string | Buffer | Uint8Array | bigint; export declare const IID_ITaskbarList3: unknown; export declare class ITaskbarList3 { - /** Create a new instance via the coclass activation path. */ - static create(): ITaskbarList3; + static readonly IID: typeof IID_ITaskbarList3; + protected constructor(obj: unknown); /** Wrap an existing native COM pointer (for QueryInterface bridging). */ static _fromNative(obj: unknown): ITaskbarList3; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ hrInit(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ addTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ deleteTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ activateTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ setActiveAlt(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ markFullscreenWindow(hwnd: HWND | Buffer | Uint8Array, fFullscreen: boolean): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressvalue} */ setProgressValue(hwnd: HWND | Buffer | Uint8Array, ullCompleted: bigint, ullTotal: bigint): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate} */ setProgressState(hwnd: HWND | Buffer | Uint8Array, tbpFlags: TBPFLAG): void; - registerTab(tab: HWND | Buffer | Uint8Array, mDI: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-registertab} */ + registerTab(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-unregistertab} */ unregisterTab(tab: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settaborder} */ setTabOrder(tab: HWND | Buffer | Uint8Array, insertBefore: HWND | Buffer | Uint8Array): void; - setTabActive(tab: HWND | Buffer | Uint8Array, mDI: HWND | Buffer | Uint8Array, reserved: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ + setTabActive(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array, reserved: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd: HWND | Buffer | Uint8Array, himl: HIMAGELIST): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ setOverlayIcon(hwnd: HWND | Buffer | Uint8Array, hIcon: HICON, description: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ setThumbnailTooltip(hwnd: HWND | Buffer | Uint8Array, tip: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: bigint | Buffer): void; } diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js index 9006398f..1970f747 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js @@ -1,97 +1,117 @@ // Generated by dynwinrt-codegen — do not edit -import { DynCom, DynComMethodSig, WinGuid } from '@microsoft/dynwinrt/com'; -import { TBPFLAG } from './TBPFLAG.js'; +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { TBPFLAG } = require('./TBPFLAG.js'); -export const IID_ITaskbarList3 = WinGuid.parse('ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf'); +const IID_ITaskbarList3 = WinGuid.parse('ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf'); let _ITaskbarList3Cache; const _ITaskbarList3 = new Proxy({}, { get(_target, prop) { _ITaskbarList3Cache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.ITaskbarList3', IID_ITaskbarList3) - .addMethod('HrInit', new DynComMethodSig()) - .addMethod('AddTab', new DynComMethodSig().addIn(DynCom.pointerType())) - .addMethod('DeleteTab', new DynComMethodSig().addIn(DynCom.pointerType())) - .addMethod('ActivateTab', new DynComMethodSig().addIn(DynCom.pointerType())) - .addMethod('SetActiveAlt', new DynComMethodSig().addIn(DynCom.pointerType())) - .addMethod('MarkFullscreenWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) - .addMethod('SetProgressValue', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u64Type()).addIn(DynCom.u64Type())) - .addMethod('SetProgressState', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) - .addMethod('RegisterTab', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethod('UnregisterTab', new DynComMethodSig().addIn(DynCom.pointerType())) - .addMethod('SetTabOrder', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethod('SetTabActive', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) - .addMethod('ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) - .addMethod('ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) - .addMethod('ThumbBarSetImageList', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethod('SetOverlayIcon', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethod('SetThumbnailTooltip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethod('SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())); + .addMethodAt(3, 'HrInit', new DynComMethodSig()) + .addMethodAt(4, 'AddTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(5, 'DeleteTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(6, 'ActivateTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(7, 'SetActiveAlt', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(8, 'MarkFullscreenWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(9, 'SetProgressValue', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u64Type()).addIn(DynCom.u64Type())) + .addMethodAt(10, 'SetProgressState', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(11, 'RegisterTab', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(12, 'UnregisterTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(13, 'SetTabOrder', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(14, 'SetTabActive', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) + .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(17, 'ThumbBarSetImageList', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(18, 'SetOverlayIcon', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(19, 'SetThumbnailTooltip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())); const value = _ITaskbarList3Cache[prop]; return typeof value === 'function' ? value.bind(_ITaskbarList3Cache) : value; }, }); -export class ITaskbarList3 { +class ITaskbarList3 { + static IID = IID_ITaskbarList3; _obj; constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return new ITaskbarList3(obj); } - /** Create a new `ITaskbarList3` via `CoCreateInstance` on `CLSID_TaskbarList`. */ - static create() { - const _obj = DynCom.coCreateInstance('56fdf344-fd6d-11d0-958a-006097c9a090', IID_ITaskbarList3); - return new ITaskbarList3(_obj); + static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList3.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ hrInit() { _ITaskbarList3.method(3).invoke(this._obj, []); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ addTab(hwnd) { _ITaskbarList3.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ deleteTab(hwnd) { _ITaskbarList3.method(5).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ activateTab(hwnd) { _ITaskbarList3.method(6).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ setActiveAlt(hwnd) { _ITaskbarList3.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ markFullscreenWindow(hwnd, fFullscreen) { _ITaskbarList3.method(8).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(fFullscreen ? 1 : 0)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressvalue} */ setProgressValue(hwnd, ullCompleted, ullTotal) { _ITaskbarList3.method(9).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u64(BigInt(ullCompleted)), DynCom.u64(BigInt(ullTotal))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate} */ setProgressState(hwnd, tbpFlags) { _ITaskbarList3.method(10).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(tbpFlags)]); } - registerTab(tab, mDI) { - _ITaskbarList3.method(11).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mDI))]); + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-registertab} */ + registerTab(tab, mdi) { + _ITaskbarList3.method(11).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-unregistertab} */ unregisterTab(tab) { _ITaskbarList3.method(12).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab))]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settaborder} */ setTabOrder(tab, insertBefore) { _ITaskbarList3.method(13).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(insertBefore))]); } - setTabActive(tab, mDI, reserved) { - _ITaskbarList3.method(14).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mDI)), DynCom.u32(reserved)]); + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ + setTabActive(tab, mdi, reserved) { + _ITaskbarList3.method(14).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi)), DynCom.u32(reserved)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ thumbBarAddButtons(hwnd, cButtons, pButton) { _ITaskbarList3.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ thumbBarUpdateButtons(hwnd, cButtons, pButton) { _ITaskbarList3.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd, himl) { _ITaskbarList3.method(17).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(himl)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ setOverlayIcon(hwnd, hIcon, description) { - _ITaskbarList3.method(18).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(hIcon), DynCom.pointer(description)]); + _ITaskbarList3.method(18).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(hIcon), DynCom.wideStringPointer(description)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ setThumbnailTooltip(hwnd, tip) { - _ITaskbarList3.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(tip)]); + _ITaskbarList3.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.wideStringPointer(tip)]); } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ setThumbnailClip(hwnd, prcClip) { _ITaskbarList3.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(prcClip)]); } } +exports.IID_ITaskbarList3 = IID_ITaskbarList3; +exports.ITaskbarList3 = ITaskbarList3; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts new file mode 100644 index 00000000..b0ca74a4 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts @@ -0,0 +1,61 @@ +// Generated by dynwinrt-codegen — do not edit +import { TBPFLAG } from './TBPFLAG.js'; +import { STPFLAG } from './STPFLAG.js'; + +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HICON = bigint | number; +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HIMAGELIST = bigint | number; +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HWND = bigint | number; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`. */ +export type PWSTR = string | Buffer | Uint8Array | bigint; + +export declare const IID_ITaskbarList4: unknown; + +export declare class ITaskbarList4 { + static readonly IID: typeof IID_ITaskbarList4; + protected constructor(obj: unknown); + /** Wrap an existing native COM pointer (for QueryInterface bridging). */ + static _fromNative(obj: unknown): ITaskbarList4; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ + markFullscreenWindow(hwnd: HWND | Buffer | Uint8Array, fFullscreen: boolean): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressvalue} */ + setProgressValue(hwnd: HWND | Buffer | Uint8Array, ullCompleted: bigint, ullTotal: bigint): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate} */ + setProgressState(hwnd: HWND | Buffer | Uint8Array, tbpFlags: TBPFLAG): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-registertab} */ + registerTab(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-unregistertab} */ + unregisterTab(tab: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settaborder} */ + setTabOrder(tab: HWND | Buffer | Uint8Array, insertBefore: HWND | Buffer | Uint8Array): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ + setTabActive(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array, reserved: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ + thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ + thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ + thumbBarSetImageList(hwnd: HWND | Buffer | Uint8Array, himl: HIMAGELIST): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ + setOverlayIcon(hwnd: HWND | Buffer | Uint8Array, hIcon: HICON, description: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ + setThumbnailTooltip(hwnd: HWND | Buffer | Uint8Array, tip: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ + setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist4-settabproperties} */ + setTabProperties(tab: HWND | Buffer | Uint8Array, stpFlags: STPFLAG): void; +} diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js new file mode 100644 index 00000000..344990d4 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js @@ -0,0 +1,123 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { TBPFLAG } = require('./TBPFLAG.js'); +const { STPFLAG } = require('./STPFLAG.js'); + +const IID_ITaskbarList4 = WinGuid.parse('c43dc798-95d1-4bea-9030-bb99e2983a1a'); + +let _ITaskbarList4Cache; +const _ITaskbarList4 = new Proxy({}, { + get(_target, prop) { + _ITaskbarList4Cache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.ITaskbarList4', IID_ITaskbarList4) + .addMethodAt(3, 'HrInit', new DynComMethodSig()) + .addMethodAt(4, 'AddTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(5, 'DeleteTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(6, 'ActivateTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(7, 'SetActiveAlt', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(8, 'MarkFullscreenWindow', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(9, 'SetProgressValue', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u64Type()).addIn(DynCom.u64Type())) + .addMethodAt(10, 'SetProgressState', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(11, 'RegisterTab', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(12, 'UnregisterTab', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(13, 'SetTabOrder', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(14, 'SetTabActive', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) + .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(17, 'ThumbBarSetImageList', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(18, 'SetOverlayIcon', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(19, 'SetThumbnailTooltip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(21, 'SetTabProperties', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())); + const value = _ITaskbarList4Cache[prop]; + return typeof value === 'function' ? value.bind(_ITaskbarList4Cache) : value; + }, +}); + +class ITaskbarList4 { + static IID = IID_ITaskbarList4; + _obj; + constructor(obj) { this._obj = obj; } + static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList4.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-hrinit} */ + hrInit() { + _ITaskbarList4.method(3).invoke(this._obj, []); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-addtab} */ + addTab(hwnd) { + _ITaskbarList4.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-deletetab} */ + deleteTab(hwnd) { + _ITaskbarList4.method(5).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-activatetab} */ + activateTab(hwnd) { + _ITaskbarList4.method(6).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist-setactivealt} */ + setActiveAlt(hwnd) { + _ITaskbarList4.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow} */ + markFullscreenWindow(hwnd, fFullscreen) { + _ITaskbarList4.method(8).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(fFullscreen ? 1 : 0)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressvalue} */ + setProgressValue(hwnd, ullCompleted, ullTotal) { + _ITaskbarList4.method(9).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u64(BigInt(ullCompleted)), DynCom.u64(BigInt(ullTotal))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate} */ + setProgressState(hwnd, tbpFlags) { + _ITaskbarList4.method(10).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(tbpFlags)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-registertab} */ + registerTab(tab, mdi) { + _ITaskbarList4.method(11).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-unregistertab} */ + unregisterTab(tab) { + _ITaskbarList4.method(12).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settaborder} */ + setTabOrder(tab, insertBefore) { + _ITaskbarList4.method(13).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(insertBefore))]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ + setTabActive(tab, mdi, reserved) { + _ITaskbarList4.method(14).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi)), DynCom.u32(reserved)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ + thumbBarAddButtons(hwnd, cButtons, pButton) { + _ITaskbarList4.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ + thumbBarUpdateButtons(hwnd, cButtons, pButton) { + _ITaskbarList4.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ + thumbBarSetImageList(hwnd, himl) { + _ITaskbarList4.method(17).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(himl)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ + setOverlayIcon(hwnd, hIcon, description) { + _ITaskbarList4.method(18).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(hIcon), DynCom.wideStringPointer(description)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ + setThumbnailTooltip(hwnd, tip) { + _ITaskbarList4.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.wideStringPointer(tip)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ + setThumbnailClip(hwnd, prcClip) { + _ITaskbarList4.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(prcClip)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist4-settabproperties} */ + setTabProperties(tab, stpFlags) { + _ITaskbarList4.method(21).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.i32(stpFlags)]); + } +} +exports.IID_ITaskbarList4 = IID_ITaskbarList4; +exports.ITaskbarList4 = ITaskbarList4; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.d.ts new file mode 100644 index 00000000..76d5670d --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.d.ts @@ -0,0 +1,9 @@ +// Generated by dynwinrt-codegen — do not edit +export type STPFLAG = (typeof STPFLAG)[keyof typeof STPFLAG]; +export declare const STPFLAG: { + readonly STPF_NONE: 0; + readonly STPF_USEAPPTHUMBNAILALWAYS: 1; + readonly STPF_USEAPPTHUMBNAILWHENACTIVE: 2; + readonly STPF_USEAPPPEEKALWAYS: 4; + readonly STPF_USEAPPPEEKWHENACTIVE: 8; +}; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.js new file mode 100644 index 00000000..d25ad2e0 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/STPFLAG.js @@ -0,0 +1,10 @@ +// Generated by dynwinrt-codegen — do not edit + +const STPFLAG = Object.freeze({ + STPF_NONE: 0, + STPF_USEAPPTHUMBNAILALWAYS: 1, + STPF_USEAPPTHUMBNAILWHENACTIVE: 2, + STPF_USEAPPPEEKALWAYS: 4, + STPF_USEAPPPEEKWHENACTIVE: 8, +}); +exports.STPFLAG = STPFLAG; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TBPFLAG.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TBPFLAG.js index 58af8cf8..027ffdb8 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TBPFLAG.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TBPFLAG.js @@ -1,8 +1,10 @@ // Generated by dynwinrt-codegen — do not edit -export const TBPFLAG = Object.freeze({ + +const TBPFLAG = Object.freeze({ TBPF_NOPROGRESS: 0, TBPF_INDETERMINATE: 1, TBPF_NORMAL: 2, TBPF_ERROR: 4, TBPF_PAUSED: 8, }); +exports.TBPFLAG = TBPFLAG; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.d.ts new file mode 100644 index 00000000..e462681f --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.d.ts @@ -0,0 +1,12 @@ +// Generated by dynwinrt-codegen — do not edit +import { ITaskbarList4 } from './ITaskbarList4.js'; + +export declare const CLSID_TaskbarList: string; + +export declare class TaskbarList extends ITaskbarList4 { + constructor(); + static _fromNative(obj: unknown): TaskbarList; + as(InterfaceClass: { readonly IID: unknown; _fromNative(obj: unknown): T }): T; + tryAs(InterfaceClass: { readonly IID: unknown; _fromNative(obj: unknown): T }): T | null; + supports(InterfaceClass: { readonly IID: unknown; _fromNative(obj: unknown): T }): boolean; +} diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js new file mode 100644 index 00000000..02128f7f --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js @@ -0,0 +1,30 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynCom } = require('@microsoft/dynwinrt/com'); +const { ITaskbarList4, IID_ITaskbarList4 } = require('./ITaskbarList4.js'); + +const CLSID_TaskbarList = '56fdf344-fd6d-11d0-958a-006097c9a090'; + +class TaskbarList extends ITaskbarList4 { + constructor() { + super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4)); + } + static _fromNative(obj) { + const cast = obj.cast(IID_ITaskbarList4); + return Object.assign(Object.create(TaskbarList.prototype), { _obj: cast }); + } + as(InterfaceClass) { + return InterfaceClass._fromNative(this._obj.cast(InterfaceClass.IID)); + } + tryAs(InterfaceClass) { + const obj = DynCom.tryCast(this._obj, InterfaceClass.IID); + return obj === null ? null : InterfaceClass._fromNative(obj); + } + supports(InterfaceClass) { + const obj = DynCom.tryCast(this._obj, InterfaceClass.IID); + if (obj === null) return false; + obj.release(); + return true; + } +} +exports.CLSID_TaskbarList = CLSID_TaskbarList; +exports.TaskbarList = TaskbarList; diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 459b2de9..1c15a036 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -6,8 +6,8 @@ //! These tests drive the implementation of: //! - Base-aware vtable slot computation (walks interface_impls chain) //! - IUnknown vs IInspectable base offset (3 vs 6) -//! - Coclass CLSID discovery for `create()` activation -//! - Natural TS/JS wrapper generation for classic-COM interfaces +//! - Coclass CLSID discovery and newable coclass wrappers +//! - Natural TS/JS wrapper generation for classic-COM interfaces and coclasses //! //! Tests are skipped (with an `eprintln!` note) when the Win32 winmd is not //! present at the well-known path. @@ -45,6 +45,22 @@ fn required_win32_metadata_is_present() { } } +/// Returns a clone of `iface` with the named method removed. +/// +/// `IShellLinkW::GetPath` takes a caller-writable `WIN32_FIND_DATAW*` (`pfd`) +/// that has no safe layout/size projection (see the classic-COM-ABI skill's +/// fail-closed requirement for unsupported writable native structs), so the +/// whole interface now fails closed if it is included. Tests that only need +/// `IShellLinkW`'s *other* members use this helper to exercise them without +/// tripping that (separately, correctly, regression-tested) failure. +fn without_method( + mut iface: com_metadata::ComInterfaceMeta, + name: &str, +) -> com_metadata::ComInterfaceMeta { + iface.interface.methods.retain(|method| method.name != name); + iface +} + /// Resolve a `Windows.winmd` from the newest installed Windows SDK, matching /// the discovery logic the codegen itself uses. Returns `None` if no SDK is /// installed on this machine (the test that calls this should skip in that @@ -103,10 +119,12 @@ fn assert_mixed_package_shape(output_dir: &Path) { assert!(package.contains("\"./com/*\"")); assert!(package.contains("\"types\": \"./com/*.d.ts\"")); assert!(package.contains("\"import\": \"./com/*.js\"")); - assert!(!package.contains("\"require\": \"./com/")); + assert!(package.contains("\"require\": \"./com/index.js\"")); + assert!(package.contains("\"require\": \"./com/*.js\"")); let com_package = fs::read_to_string(output_dir.join("com").join("package.json")).unwrap(); - assert!(com_package.contains("\"type\": \"module\"")); + assert!(com_package.contains("\"type\": \"commonjs\"")); + assert!(output_dir.join("com").join("index.mjs").is_file()); } // ------------------------------------------------------------------------- @@ -235,6 +253,68 @@ fn itaskbarlist3_clsid_resolution() { assert_eq!(com_iface.coclass_name.as_deref(), Some("TaskbarList")); } +#[test] +fn taskbarlist_coclass_selects_unique_most_derived_interface() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .expect("TaskbarList must be recognized as a COM coclass"); + + assert_eq!(coclass.clsid, "56fdf344-fd6d-11d0-958a-006097c9a090"); + assert_eq!(coclass.primary_interface.interface.name, "ITaskbarList4"); + assert_eq!( + coclass + .associated_interfaces + .iter() + .map(|interface| interface.interface.name.as_str()) + .collect::>(), + [ + "ITaskbarList", + "ITaskbarList2", + "ITaskbarList3", + "ITaskbarList4" + ] + ); +} + +#[test] +fn taskbarlist_coclass_generates_newable_class_and_interface_views() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .unwrap(); + let out = com::generate_com_coclass_files(&coclass, &win32_winmd()).unwrap(); + + assert!(out.js.contains("class TaskbarList extends ITaskbarList4")); + assert!(out.js.contains("exports.TaskbarList = TaskbarList;")); + assert!( + out.js + .contains("super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4))") + ); + assert!(out.js.contains("as(InterfaceClass)")); + assert!(out.js.contains("DynCom.tryCast")); + assert!(out.dts.contains("constructor();")); + for interface in [ + "ITaskbarList.js", + "ITaskbarList2.js", + "ITaskbarList3.js", + "ITaskbarList4.js", + ] { + assert!( + out.extra_files.iter().any(|(name, _)| name == interface), + "missing {interface}" + ); + } +} + /// 5. Param type mapping: HWND → pointer/handle, TBPFLAG → enum, HRESULT → void. #[test] fn param_type_mapping() { @@ -340,18 +420,20 @@ fn shelllink_scalar_out_pointers_preserve_pointee_types() { .find(|method| method.name == "GetIconLocation") .unwrap(); assert!(matches!(get_icon_location.params[2].typ, TypeMeta::I32)); - - let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); - assert!( - output - .js - .contains(".addMethod('GetHotkey', new DynComMethodSig().addOut(DynCom.u16Type()))") - ); - assert!( - output - .js - .contains(".addMethod('GetShowCmd', new DynComMethodSig().addOut(DynCom.i32Type()))") - ); + let get_hotkey_vtable = get_hotkey.vtable_index; + let get_show_cmd_vtable = get_show_cmd.vtable_index; + + // `GetPath` is intentionally unsupported (see `without_method`); it is + // covered by its own fail-closed regression test below. + let interface_without_get_path = without_method(interface, "GetPath"); + let output = + com::generate_com_interface_files(&interface_without_get_path, &win32_winmd()).unwrap(); + assert!(output.js.contains(&format!( + ".addMethodAt({get_hotkey_vtable}, 'GetHotkey', new DynComMethodSig().addOut(DynCom.u16Type()))" + ))); + assert!(output.js.contains(&format!( + ".addMethodAt({get_show_cmd_vtable}, 'GetShowCmd', new DynComMethodSig().addOut(DynCom.i32Type()))" + ))); assert!( output .dts @@ -481,8 +563,8 @@ fn dts_surface_is_natural_and_clean() { } } -/// 8. Generated `.js`: activation uses a CoCreateInstance path with CLSID + IID; -/// methods invoke at the correct base-aware slots. +/// 8. Generated interface `.js` contains only IID/vtable behavior; activation +/// is emitted by the separate coclass wrapper. #[test] fn js_body_uses_cocreateinstance_and_correct_slots() { if !win32_available() { @@ -499,24 +581,15 @@ fn js_body_uses_cocreateinstance_and_correct_slots() { .expect("codegen must succeed for classic-COM interface"); let js = out.js.as_str(); - // CLSID + IID appear in .js - assert!( - js.contains("56fdf344-fd6d-11d0-958a-006097c9a090"), - ".js must embed the CLSID:\n{}", - js - ); + // Only the IID appears in the interface wrapper. + assert!(!js.contains("56fdf344-fd6d-11d0-958a-006097c9a090")); assert!( js.contains("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"), ".js must embed the IID:\n{}", js ); - // Activation via coCreateInstance - assert!( - js.contains("coCreateInstance"), - ".js must use coCreateInstance for activation:\n{}", - js - ); + assert!(!js.contains("coCreateInstance")); // Classic COM registration is kept out of the WinRT type namespace. assert!( @@ -539,6 +612,93 @@ fn js_body_uses_cocreateinstance_and_correct_slots() { // This is covered by the exact per-method assertion above. } +/// Requirement 4 (acronym casing): `ITaskbarList3::SetTabActive(HWND hwndTab, +/// HWND hwndMDI, DWORD dwReserved)` must project `hwndMDI` as `mdi` (the +/// whole `MDI` acronym lowercased), not the naive first-letter-only `mDI`. +#[test] +fn taskbarlist3_settabactive_projects_hwndmdi_as_mdi_not_mdi_mixed_case() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + assert!( + js.contains("setTabActive(tab, mdi, reserved)"), + ".js must lowercase the whole `MDI` acronym in `hwndMDI` -> `mdi`, not `mDI`:\n{}", + js + ); + assert!( + !js.contains("mDI"), + ".js must not contain the naive-lowering artifact `mDI`:\n{}", + js + ); + let dts = out.dts.as_str(); + assert!( + dts.contains("mdi:"), + ".d.ts must also project the parameter as `mdi`:\n{}", + dts + ); +} + +/// Lifecycle ergonomics + doc rendering on a generated interface wrapper. +/// Activation lives on the separately generated coclass; the interface must +/// expose `release()`, a protected constructor/IID descriptor for generated +/// coclass inheritance and `as()`, and — since win32metadata attaches a +/// `DocumentationAttribute` (a `learn.microsoft.com` URL) to most methods — +/// an `@see` JSDoc comment referencing that URL. +#[test] +fn taskbarlist3_generated_output_has_lifecycle_members_and_doc_links() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + let dts = out.dts.as_str(); + + assert!( + js.contains("release()") && js.contains("this._obj.release();"), + ".js must expose release() delegating to the managed native value:\n{}", + js + ); + assert!( + dts.contains("release(): void;"), + ".d.ts must declare release(): void;:\n{}", + dts + ); + assert!( + dts.contains("protected constructor(obj: unknown);") + && dts.contains("static readonly IID:"), + ".d.ts must expose only the generated-coclass/interface-view construction surface:\n{}", + dts + ); + assert!( + js.contains("@see {@link https://learn.microsoft.com/"), + ".js must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", + js + ); + assert!( + dts.contains("@see {@link https://learn.microsoft.com/"), + ".d.ts must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", + dts + ); +} + // ------------------------------------------------------------------------- // CORNER tests // ------------------------------------------------------------------------- @@ -685,13 +845,13 @@ fn generation_is_deterministic() { // SNAPSHOT test // ------------------------------------------------------------------------- -/// Snapshot test: lock generated ITaskbarList3 .js + .d.ts against committed files. +/// Snapshot test: lock generated TaskbarList coclass and interface files. /// /// To update snapshots after an intentional change: /// cargo run -p dynwinrt-codegen -- generate \ /// --winmd C:\s\win32metadata\Windows.Win32.winmd \ /// --namespace Windows.Win32.UI.Shell \ -/// --class-name ITaskbarList3 \ +/// --class-name TaskbarList \ /// --output tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3 #[test] fn snapshot_itaskbarlist3() { @@ -699,14 +859,12 @@ fn snapshot_itaskbarlist3() { eprintln!("Skipping snapshot test: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .expect("ITaskbarList3 must exist"); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .expect("TaskbarList must exist"); + let out = com::generate_com_coclass_files(&coclass, &win32_winmd()) + .expect("codegen must succeed for TaskbarList"); let snapshot_dir: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/itaskbarlist3"); @@ -717,8 +875,8 @@ fn snapshot_itaskbarlist3() { ); let mut generated: Vec<(String, String)> = Vec::new(); - generated.push(("ITaskbarList3.js".into(), out.js.clone())); - generated.push(("ITaskbarList3.d.ts".into(), out.dts.clone())); + generated.push(("TaskbarList.js".into(), out.js.clone())); + generated.push(("TaskbarList.d.ts".into(), out.dts.clone())); for (name, content) in &out.extra_files { generated.push((name.clone(), content.clone())); } @@ -802,8 +960,8 @@ fn import_name_flag_is_honored_by_com_path() { // Custom import must appear on the runtime import line... assert!( - out.js.contains("from '../dist/com.js'"), - "classic-COM .js must honor --import-name (expected `from '../dist/com.js'`):\n{}", + out.js.contains("require('../dist/com.js')"), + "classic-COM .js must honor --import-name (expected `require('../dist/com.js')`):\n{}", out.js ); // ...and the hardcoded default must NOT be present in the generated body. @@ -825,7 +983,9 @@ fn import_name_flag_is_honored_by_com_path() { .expect("codegen must succeed for classic-COM interface") }; assert!( - default_out.js.contains("from '@microsoft/dynwinrt/com'"), + default_out + .js + .contains("require('@microsoft/dynwinrt/com')"), "after restoring, default import must use '@microsoft/dynwinrt/com':\n{}", default_out.js ); @@ -864,7 +1024,7 @@ fn import_name_flag_is_honored_by_interop_wrapper() { // The interop .js itself must honor the flag. assert!( - out.js.contains("from '../dist/com.js'"), + out.js.contains("require('../dist/com.js')"), "interop .js must honor --import-name:\n{}", out.js ); @@ -901,8 +1061,11 @@ fn shellitem_getdisplayname_is_not_classified_as_caller_owned_string_buffer() { .expect("codegen must succeed for IShellItem"); assert!( - out.js.contains(".addMethod('GetDisplayName', new DynComMethodSig().addIn(DynCom.i32Type()).addOut(DynCom.pointerType()))"), - "PWSTR* callee-allocated output must remain addOut(pointer), not caller-owned buffer:\n{}", + out.js.contains(".addOut(DynCom.coTaskMemPointerType())") + && out.js.contains( + "'GetDisplayName', new DynComMethodSig().addIn(DynCom.i32Type()).addOut(DynCom.coTaskMemPointerType())" + ), + "PWSTR* callee-allocated output must be registered as an owned CoTaskMem output, not the unclassified pointer type:\n{}", out.js ); assert!( @@ -927,6 +1090,7 @@ fn u16_input_param_uses_existing_u16_value_ctor_not_u16value() { let com_iface = com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") .expect("IShellLinkW must exist"); + let com_iface = without_method(com_iface, "GetPath"); let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) .expect("codegen must succeed for IShellLinkW"); @@ -1154,30 +1318,54 @@ fn unsigned_enum_values_preserve_their_value() { } #[test] -fn optional_string_buffer_placeholders_do_not_precede_required_parameters() { +fn shelllink_getpath_fails_closed_on_unsupported_find_data_struct() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + // `IShellLinkW::GetPath` takes a caller-writable `WIN32_FIND_DATAW* pfd` + // (an [in, out] multi-field struct with no NativeArrayInfo count and no + // recognized single-field pointer-alias/scalar shape). There is no safe + // layout/size projection for it, so generation must fail closed with an + // actionable diagnostic instead of silently treating it as an opaque + // caller-owned buffer (the removed `pfd`/`finddata` name heuristic). + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") + .expect("IShellLinkW must exist"); + let error = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect_err("GetPath's WIN32_FIND_DATAW* must fail closed, not fall back to a heuristic"); + assert!( + error.contains("GetPath") && error.contains("pfd") && error.contains("WIN32_FIND_DATAW"), + "diagnostic must name the interface, method, and offending parameter:\n{error}" + ); +} + +#[test] +fn shelllink_other_methods_still_generate_when_getpath_is_excluded() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } + // Everything else on IShellLinkW (including its OTHER string-buffer + // methods, e.g. GetIconLocation) is unaffected by GetPath's fail-closed + // struct-layout limitation; a consumer can still generate the interface + // by excluding the one unsupported method. let interface = com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") .expect("IShellLinkW must exist"); + let interface = without_method(interface, "GetPath"); let output = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect("IShellLinkW generation should succeed"); + .expect("IShellLinkW generation should succeed once GetPath is excluded"); assert!( output .dts - .contains("getPath(cch: number, pfd: bigint | Buffer, fFlags: number)"), - "a required parameter must not follow an optional pfd placeholder:\n{}", + .contains("getIconLocation(cch?: number): [string, number];"), + "other string-buffer methods must still project correctly:\n{}", output.dts ); - assert!( - !output.js.contains("getPath(cch = 260") && !output.js.contains("pfd = 0, fFlags"), - "JavaScript defaults must obey the same trailing-optional rule:\n{}", - output.js - ); } #[test] @@ -1476,6 +1664,7 @@ fn com_only_generation_emits_an_importable_package_shape() { } for name in [ "index.js", + "index.mjs", "index.d.ts", "package.json", "ITaskbarList3.js", @@ -1489,14 +1678,18 @@ fn com_only_generation_emits_an_importable_package_shape() { assert!(!output_dir.join("ITaskbarList3.js").exists()); let index = fs::read_to_string(output_dir.join("index.js")).unwrap(); assert!(index.contains("ITaskbarList3") && index.contains("TBPFLAG")); - assert!(index.contains("from './com/ITaskbarList3.js'")); + assert!(index.contains("__exportLazy('ITaskbarList3', './com/ITaskbarList3.js')")); let com_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); - assert!(com_index.contains("from './ITaskbarList3.js'")); + assert!(com_index.contains("__exportLazy('ITaskbarList3', './ITaskbarList3.js')")); + let com_esm_index = fs::read_to_string(output_dir.join("com").join("index.mjs")).unwrap(); + assert!(com_esm_index.contains("import * as __m")); let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); - assert!(package.contains("\"type\": \"module\"")); + assert!(package.contains("\"type\": \"commonjs\"")); assert!(package.contains("\"./ITaskbarList3\"")); assert!(package.contains("\"./com\"")); assert!(package.contains("\"./com/*\"")); + assert!(package.contains("\"import\": \"./com/index.mjs\"")); + assert!(package.contains("\"require\": \"./com/index.js\"")); let incremental = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) .args([ @@ -1506,7 +1699,15 @@ fn com_only_generation_emits_an_importable_package_shape() { "--namespace", "Windows.Win32.UI.Shell", "--class-name", - "IShellLinkW", + // `IShellLinkW` is deliberately NOT used here: its `GetPath` + // parameter `pfd` (`WIN32_FIND_DATAW*`) has no safe layout/size + // projection and now correctly fails closed (see the + // `shelllink_getpath_fails_closed_on_unsupported_find_data_struct` + // regression test), which would fail this whole interface's + // generation. `IShellItem` exercises the same incremental + // multi-interface + referenced-enum path (it references both + // `SIGDN` and `SFGAO_FLAGS`) without hitting that limitation. + "IShellItem", "--output", output_dir.to_str().unwrap(), ]) @@ -1520,15 +1721,15 @@ fn com_only_generation_emits_an_importable_package_shape() { let incremental_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); assert!( incremental_index.contains("ITaskbarList3") - && incremental_index.contains("IShellLinkW") + && incremental_index.contains("IShellItem") && incremental_index.contains("TBPFLAG") - && incremental_index.contains("SHOW_WINDOW_CMD"), + && incremental_index.contains("SIGDN"), "incremental generation must preserve earlier exports:\n{incremental_index}" ); let incremental_package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!( incremental_package.contains("\"./ITaskbarList3\"") - && incremental_package.contains("\"./IShellLinkW\""), + && incremental_package.contains("\"./IShellItem\""), "incremental generation must preserve earlier package subpaths:\n{incremental_package}" ); @@ -1593,7 +1794,7 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { &com_first, ); let com_only_package = fs::read_to_string(com_first.join("package.json")).unwrap(); - assert!(com_only_package.contains("\"type\": \"module\"")); + assert!(com_only_package.contains("\"type\": \"commonjs\"")); assert!( fs::read_to_string(com_first.join("index.d.ts")) .unwrap() @@ -1611,16 +1812,21 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { ); let com_dir = legacy_com_first.join("com"); let legacy_index = fs::read_to_string(com_dir.join("index.js")).unwrap(); + let legacy_dts = fs::read_to_string(com_dir.join("index.d.ts")).unwrap(); for entry in fs::read_dir(&com_dir).unwrap() { let entry = entry.unwrap(); let name = entry.file_name(); let name = name.to_string_lossy(); - if name != "index.js" && name != "index.d.ts" && name != "package.json" { + if name != "index.js" + && name != "index.mjs" + && name != "index.d.ts" + && name != "package.json" + { fs::copy(entry.path(), legacy_com_first.join(name.as_ref())).unwrap(); } } fs::write(legacy_com_first.join("index.js"), &legacy_index).unwrap(); - fs::write(legacy_com_first.join("index.d.ts"), legacy_index).unwrap(); + fs::write(legacy_com_first.join("index.d.ts"), legacy_dts).unwrap(); fs::remove_dir_all(com_dir).unwrap(); run_codegen_command( @@ -1637,3 +1843,64 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { fs::remove_dir_all(output_dir).expect("remove mixed package test directory"); } } + +/// Requirement 8: multi-interface COM generation must be atomic enough that +/// a later interface's projection failure doesn't leave an earlier, +/// successfully-projected interface's files (or the `com/` barrel) newly +/// written on disk. `ITaskbarList3` projects cleanly; `IShellLinkW` fails +/// closed (its `GetPath` parameter `pfd` is an unsupported +/// `WIN32_FIND_DATAW*`). Requesting both in one `--class-name` batch must +/// fail the whole command AND leave no `com/` output directory at all (since +/// this is a from-scratch generation into a directory that doesn't exist +/// yet). +#[test] +fn multi_interface_com_generation_does_not_leave_partial_output_on_projection_failure() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let output_dir = std::env::temp_dir().join(format!( + "dynwinrt-codegen-com-atomic-{}", + std::process::id() + )); + if output_dir.exists() { + fs::remove_dir_all(&output_dir).expect("remove stale atomic COM test directory"); + } + + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args([ + "generate", + "--winmd", + &win32_winmd(), + "--namespace", + "Windows.Win32.UI.Shell", + "--class-name", + "ITaskbarList3,IShellLinkW", + "--output", + output_dir.to_str().unwrap(), + ]) + .output() + .expect("spawn dynwinrt-codegen"); + + assert!( + !output.status.success(), + "generation must fail overall when any requested interface fails to project" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("IShellLinkW") && stderr.contains("pfd"), + "failure must name the offending interface/parameter:\n{stderr}" + ); + + // No partial `com/` output (nor any of ITaskbarList3's already-projected + // files) may have been written as a side effect of the failed batch. + assert!( + !output_dir.join("com").exists(), + "a failed multi-interface COM batch must not leave a partial com/ directory: {:?}", + output_dir.join("com") + ); + + if output_dir.exists() { + fs::remove_dir_all(&output_dir).expect("remove atomic COM test directory"); + } +} From 7931ff3fa1852a478df750f67c3155a4fe2429ad Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 6 Aug 2026 14:16:13 +0800 Subject: [PATCH 2/4] Expand safe Classic COM support Add fail-closed semantic ABI projection, exact ownership registries, generated JavaScript bindings, and an isolated explicit unsafe COM entrypoint. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6307886d-3c24-4596-8924-ba44b0e850a5 --- Cargo.lock | 3 + README.md | 8 +- bindings/js/Cargo.toml | 1 + bindings/js/README.md | 17 +- bindings/js/__test__/index.spec.ts | 445 +- bindings/js/package.json | 9 + bindings/js/scripts/generate-entrypoints.mjs | 41 +- bindings/js/src/com.rs | 4181 +++++++- bindings/js/src/lib.rs | 172 +- crates/dynwinrt/Cargo.toml | 4 + crates/dynwinrt/src/call.rs | 941 +- crates/dynwinrt/src/com.rs | 8687 ++++++++++++++++- crates/dynwinrt/src/com_automation.rs | 2828 ++++++ .../dynwinrt/src/metadata_table/value_data.rs | 4 +- crates/dynwinrt/src/native_call.rs | 1079 +- docs/classic-com-support.md | 933 +- docs/classic-com-usage.md | 691 ++ tests/e2e_test.ps1 | 15 +- tests/runners/com/dtm.mjs | 2 +- tests/runners/com/file-open-dialog.mjs | 2 +- tests/runners/com/file-operation.mjs | 2 +- tests/runners/com/hwnd.mjs | 2 +- tests/runners/com/module-commonjs.cjs | 2 +- tests/runners/com/persist-file.mjs | 2 +- tests/runners/com/pointer-reject-object.mjs | 2 +- .../runners/com/sequential-stream-buffer.mjs | 48 + tests/runners/com/shell-link-pod.mjs | 32 + tests/runners/com/smtc.mjs | 2 +- tests/runners/com/wic-imaging-factory.mjs | 2 +- tools/dynwinrt-codegen/Cargo.toml | 18 + tools/dynwinrt-codegen/src/codegen/com/ir.rs | 272 +- .../src/codegen/com/javascript/render.rs | 1521 ++- .../codegen/com/javascript/render_tests.rs | 889 +- .../src/codegen/com/javascript/types.rs | 524 +- tools/dynwinrt-codegen/src/codegen/com/mod.rs | 77 +- .../src/codegen/com/model/abi.rs | 668 ++ .../src/codegen/com/model/contract.rs | 245 + .../src/codegen/com/model/diagnostics.rs | 114 + .../src/codegen/com/model/ids.rs | 130 + .../src/codegen/com/model/layout.rs | 328 + .../src/codegen/com/model/metadata.rs | 3522 +++++++ .../src/codegen/com/model/method.rs | 1648 ++++ .../src/codegen/com/model/mod.rs | 390 + .../src/codegen/com/model/ownership.rs | 179 + .../codegen/com/project/legacy_diagnostics.rs | 937 ++ .../com/project/{types.rs => legacy_types.rs} | 23 +- .../src/codegen/com/project/mod.rs | 3508 +++++-- .../src/com_borrowed_handle_registry.rs | 408 + .../src/com_enumerator_registry.rs | 1368 +++ tools/dynwinrt-codegen/src/com_metadata.rs | 2417 ++++- .../src/com_safe_array_registry.rs | 3349 +++++++ tools/dynwinrt-codegen/src/lib.rs | 3 + tools/dynwinrt-codegen/src/main.rs | 117 + .../IDataTransferManagerInterop.d.ts | 5 +- .../IDataTransferManagerInterop.js | 4 +- .../snapshots/ishelllinkw/IShellLinkW.d.ts | 61 + .../snapshots/ishelllinkw/IShellLinkW.js | 154 + .../snapshots/itaskbarlist3/ITaskbarList.d.ts | 3 +- .../snapshots/itaskbarlist3/ITaskbarList.js | 2 +- .../itaskbarlist3/ITaskbarList2.d.ts | 3 +- .../snapshots/itaskbarlist3/ITaskbarList2.js | 2 +- .../itaskbarlist3/ITaskbarList3.d.ts | 19 +- .../snapshots/itaskbarlist3/ITaskbarList3.js | 27 +- .../itaskbarlist3/ITaskbarList4.d.ts | 19 +- .../snapshots/itaskbarlist3/ITaskbarList4.js | 27 +- .../snapshots/itaskbarlist3/TaskbarList.js | 2 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 4353 +++++++-- 67 files changed, 44710 insertions(+), 2783 deletions(-) create mode 100644 crates/dynwinrt/src/com_automation.rs create mode 100644 docs/classic-com-usage.md create mode 100644 tests/runners/com/sequential-stream-buffer.mjs create mode 100644 tests/runners/com/shell-link-pod.mjs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/abi.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/contract.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/diagnostics.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/ids.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/layout.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/method.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/mod.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs rename tools/dynwinrt-codegen/src/codegen/com/project/{types.rs => legacy_types.rs} (95%) create mode 100644 tools/dynwinrt-codegen/src/com_borrowed_handle_registry.rs create mode 100644 tools/dynwinrt-codegen/src/com_enumerator_registry.rs create mode 100644 tools/dynwinrt-codegen/src/com_safe_array_registry.rs create mode 100644 tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts create mode 100644 tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js diff --git a/Cargo.lock b/Cargo.lock index 2983e65a..6977ad1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -294,6 +294,7 @@ dependencies = [ "criterion", "futures", "libffi", + "libffi-sys", "paste", "tokio", "windows", @@ -311,6 +312,7 @@ dependencies = [ "clap", "regex", "roxmltree", + "windows", "windows-metadata", ] @@ -501,6 +503,7 @@ dependencies = [ "napi-build", "napi-derive", "pollster", + "serde_json", "windows", "windows-future", "windows-string", diff --git a/README.md b/README.md index 516ee180..d8accffc 100644 --- a/README.md +++ b/README.md @@ -51,10 +51,14 @@ console.log(uri.host); // "example.com" ``` Classic COM bindings import their runtime API from the separate -`@microsoft/dynwinrt/com` subpath. It is part of the same npm package; the -package root remains the WinRT-only API. See +`@microsoft/dynwinrt/com/unsafe` subpath internally. Applications use +`@microsoft/dynwinrt/com` for initialization and managed COM value types; +manual ABI declarations require an explicit `/com/unsafe` import. All are +part of the same npm package, while the package root remains WinRT-only. See [Classic COM support](docs/classic-com-support.md) for the supported ABI, common-interface test matrix, unsupported native types, and ownership rules. +See [Classic COM JavaScript usage](docs/classic-com-usage.md) for codegen, +GUID/IID/CLSID, lifecycle, Automation, and explicit unsafe ABI examples. Generated bindings project unambiguous public WinRT activation metadata as JavaScript constructors, including overloads such as `new Uri(base, relative)`. Existing diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index d48da037..9ce3af6a 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -18,6 +18,7 @@ dynwinrt = { path = "../../crates/dynwinrt" } windows-future = "0.3.2" windows-string = "0.0.0" pollster = "0.4.0" +serde_json = "1" [dependencies.windows] version = ">=0.59, <=0.62" diff --git a/bindings/js/README.md b/bindings/js/README.md index 59e22783..90defc53 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -45,15 +45,22 @@ Classic COM uses a separate subpath from the same package, keeping the WinRT root API unchanged: ```js -const { DynCom } = require('@microsoft/dynwinrt/com'); +const { initializeCom } = require('@microsoft/dynwinrt/com'); +initializeCom(1); // MTA ``` COM interface values returned by activation, `QueryInterface`, or typed interface out-parameters own one reference and release it when their -`DynWinRtValue` is released or collected. `adoptComPointer()` is only for a -native output that transfers an existing `+1` reference; numeric pointers and -typed-array pointers are borrowed and cannot be adopted. Win32 handles are not -COM references and require their own type-specific cleanup function. +`DynWinRtValue` is released or collected. Manual interface registration, +native signatures, and raw pointer ownership are isolated under +`@microsoft/dynwinrt/com/unsafe`. `adoptOwnedComPointer()` there consumes one +explicit caller-supplied `+1` reference; Buffer backing addresses are not +accepted. Win32 handles are not COM references and require their own +type-specific cleanup function. + +See the repository's +[Classic COM JavaScript usage guide](../../docs/classic-com-usage.md) for +codegen, GUID/IID/CLSID, lifetime, Automation, and `/com/unsafe` examples. Unambiguous public WinRT activation metadata is projected as JavaScript constructors. Parameterized and composable activations support idiomatic forms such as diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index fbb7a73f..ad705888 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -19,19 +19,42 @@ import { roInitialize, } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' -import { DynCom, DynComMethodSig } from '../dist/com.js' +import * as comRuntime from '../dist/com.js' +import { + DynCom, + DynComDispatchParams, + DynComMethodSig, + DynComPropVariant, + DynComSafeArray, + DynComUnsafe, + DynComVariant, +} from '../dist/com-unsafe.js' test('Classic COM is isolated from the WinRT root entrypoint', (t) => { t.false(Object.prototype.hasOwnProperty.call(winrtRuntime, 'DynCom')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynCom')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComUnsafe')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComMethodSig')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComInterface')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynComType')) + t.is(typeof comRuntime.initializeCom, 'function') t.truthy(DynCom) + t.truthy(DynComUnsafe) const assertion = "const assert = require('node:assert/strict');" + "const winrt = require('@microsoft/dynwinrt');" + "const com = require('@microsoft/dynwinrt/com');" + + "const unsafeCom = require('@microsoft/dynwinrt/com/unsafe');" + "assert.equal(Object.prototype.hasOwnProperty.call(winrt, 'DynCom'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComUnsafe'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComMethodSig'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComInterface'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComType'), false);" + "assert.equal(typeof winrt.DynWinRtType, 'function');" + - "assert.equal(typeof com.DynCom, 'function');" + + "assert.equal(typeof com.DynComVariant, 'function');" + + "assert.equal(typeof com.initializeCom, 'function');" + + "assert.equal(typeof unsafeCom.DynComUnsafe, 'function');" + "console.log('runtime-entrypoints-ok')" const cjs = spawnSync(process.execPath, ['--eval', assertion], { cwd: resolve(process.cwd()), @@ -45,19 +68,56 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { "import assert from 'node:assert/strict';" + "import * as winrt from '@microsoft/dynwinrt';" + "import * as com from '@microsoft/dynwinrt/com';" + + "import * as unsafeCom from '@microsoft/dynwinrt/com/unsafe';" + "assert.equal(Object.prototype.hasOwnProperty.call(winrt, 'DynCom'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComUnsafe'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComMethodSig'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComInterface'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'DynComType'), false);" + "assert.equal(typeof winrt.DynWinRtType, 'function');" + - "assert.equal(typeof com.DynCom, 'function');" + + "assert.equal(typeof com.DynComVariant, 'function');" + + "assert.equal(typeof com.initializeCom, 'function');" + + "assert.equal(typeof unsafeCom.DynComUnsafe, 'function');" + "console.log('runtime-entrypoints-ok')" const esm = spawnSync(process.execPath, ['--input-type=module', '--eval', esmAssertion], { cwd: resolve(process.cwd()), encoding: 'utf8', windowsHide: true, }) + t.is(esm.status, 0, esm.stderr) t.regex(esm.stdout, /runtime-entrypoints-ok/) }) +test('Classic COM raw ABI access requires the explicit unsafe entrypoint', (t) => { + const iid = WinGuid.parse('00000000-0000-0000-c000-000000000046') + const raw = DynComUnsafe.registerIUnknownInterface('Unsafe.IUnknown', iid).addMethodAt( + 3, + 'Raw', + new DynComMethodSig().addOut(DynComUnsafe.unclassifiedPointerType()), + ) + + t.truthy(raw.method(3)) + t.is( + typeof (raw as unknown as { addMethod?: unknown }).addMethod, + 'undefined', + ) + t.truthy(DynComUnsafe.ownedComOutputType()) + t.truthy(DynComUnsafe.coTaskMemOutputType()) + t.truthy(DynComUnsafe.bstrOutputType()) + t.truthy(DynComUnsafe.borrowedHandleOutputType()) + t.true(DynComUnsafe.adoptOwnedComPointer(0n, iid).isNull()) + t.true(DynComUnsafe.borrowComPointer(0n, iid).isNull()) + t.throws( + () => + (DynComUnsafe.adoptOwnedComPointer as unknown as (value: Buffer, iid: WinGuid) => unknown)( + Buffer.alloc(8), + iid, + ), + { message: /numeric pointer bits/ }, + ) +}) + test('DynCom rejects pointers after their TypedArray backing store is detached', (t) => { const bytes = new Uint8Array(16) const pointer = DynCom.pointer(bytes) @@ -69,6 +129,33 @@ test('DynCom rejects pointers after their TypedArray backing store is detached', t.regex(error.message, /backing ArrayBuffer is detached/) }) +test('DynCom rejects detached counted buffers and accepts typed backing widths', (t) => { + const detached = new Uint8Array(16) + structuredClone(detached.buffer, { transfer: [detached.buffer] }) + const error = t.throws(() => DynCom.buffer(detached)) + t.regex(error.message, /backing ArrayBuffer is detached/) + + for (const value of [ + Buffer.alloc(8), + new Uint8Array(8), + new Uint16Array(4), + new Uint32Array(2), + new Float32Array(2), + new Float64Array(1), + new BigInt64Array(1), + ]) { + t.truthy(DynCom.buffer(value)) + } +}) + +test('DynCom rejects SharedArrayBuffer-backed native storage', (t) => { + const shared = new Uint8Array(new SharedArrayBuffer(16)) + const bufferError = t.throws(() => DynCom.buffer(shared)) + t.regex(bufferError.message, /SharedArrayBuffer/) + const pointerError = t.throws(() => DynCom.pointer(shared)) + t.regex(pointerError.message, /SharedArrayBuffer/) +}) + test('DynCom does not adopt borrowed raw pointer bits as owned COM references', (t) => { const borrowed = DynCom.pointer(0n) const error = t.throws(() => DynCom.adoptComPointer(borrowed)) @@ -81,6 +168,353 @@ test('DynCom exposes HSTRING and semantic HRESULT primitives', (t) => { t.truthy(new DynComMethodSig().preserveHresult()) }) +test('DynCom BSTR values preserve exact strings and use dedicated signatures', (t) => { + const values = ['', 'embedded\u0000nul', 'supplementary \u{1f642}', 'x'.repeat(65537)] + for (const value of values) { + const original = value + const bstr = DynCom.bstr(value) + t.false(bstr.isNull()) + t.is(bstr.toString(), value) + t.is(value, original) + } + t.is(DynCom.nullBstr().toString(), '') + t.truthy(DynCom.bstrType()) + t.truthy(DynCom.nullableBstrType()) + t.truthy(new DynComMethodSig().addIn(DynCom.bstrType()).addInOut(DynCom.bstrType())) + t.throws(() => DynCom.bstr(1 as unknown as string), { message: /string/i }) +}) + +test('DynCom owning counted arrays use natural managed inputs', (t) => { + roInitialize() + const bstrs = DynCom.bstrArray(['embedded\u0000nul', '']) + const variants = DynCom.variantArray([ + DynComVariant.i32(17), + DynComVariant.bstr('embedded\u0000nul'), + ]) + const iid = WinGuid.parse('00000035-0000-0000-c000-000000000046') + const interfaces = DynCom.interfaceArray(iid, [ + DynWinRtValue.activationFactory('Windows.Foundation.Uri'), + ]) + + t.is(DynCom.bufferCount(bstrs), 2n) + t.is(DynCom.bufferCount(variants), 2n) + t.is(DynCom.bufferCount(interfaces), 1n) + t.false(bstrs.isNull()) + t.false(variants.isNull()) + t.false(interfaces.isNull()) + t.truthy(DynCom.callerOutputArray(DynCom.bstrType(), 2n)) + t.truthy(DynCom.enumeratorOutputArray(DynCom.variantType(), 2n)) + t.truthy(DynCom.coTaskMemWideStringType()) + const oneShot = DynCom.callerOutputArray(DynCom.bstrType(), 1n) + t.throws(() => DynCom.takeBstrArray(oneShot), { message: /does not contain owned string/ }) + t.throws(() => DynCom.takeBstrArray(oneShot), { message: /not an owned BSTR array/ }) + t.throws( + () => DynCom.interfaceArray(iid, [DynCom.pointer(0n) as unknown as DynWinRtValue]), + { message: /managed objects/ }, + ) +}) + +test('DynCom Automation wrappers preserve tags, values, bounds, and transfer', (t) => { + roInitialize() + const unionDescriptor = JSON.stringify({ + name: 'Tests.NativeUnion', + x86: { + size: 8, + alignment: 8, + fields: [ + { name: 'integer', count: 1, type: { kind: 'u64' } }, + { name: 'pointer', count: 1, type: { kind: 'pointer' } }, + ], + }, + x64: { + size: 8, + alignment: 8, + fields: [ + { name: 'integer', count: 1, type: { kind: 'u64' } }, + { name: 'pointer', count: 1, type: { kind: 'pointer' } }, + ], + }, + arm64: { + size: 8, + alignment: 8, + fields: [ + { name: 'integer', count: 1, type: { kind: 'u64' } }, + { name: 'pointer', count: 1, type: { kind: 'pointer' } }, + ], + }, + }) + const union = DynCom.createNativeUnion(unionDescriptor, 'integer') + t.is(union.activeField, 'integer') + t.deepEqual(union.bytes, Buffer.alloc(8)) + t.throws(() => DynCom.createNativeUnion(unionDescriptor, 'missing'), { + message: /no active field/, + }) + + const variants = [ + DynComVariant.empty(), + DynComVariant.null(), + DynComVariant.i8(-1), + DynComVariant.u8(1), + DynComVariant.i16(-2), + DynComVariant.u16(2), + DynComVariant.i32(-3), + DynComVariant.u32(3), + DynComVariant.int(-4), + DynComVariant.uint(4), + DynComVariant.i64(-5n), + DynComVariant.u64(5n), + DynComVariant.f32(1.5), + DynComVariant.f64(2.5), + DynComVariant.bool(true), + DynComVariant.bstr('automation'), + ] + t.deepEqual( + variants.map((value) => value.kind), + [ + 'empty', + 'null', + 'i8', + 'u8', + 'i16', + 'u16', + 'i32', + 'u32', + 'int', + 'uint', + 'i64', + 'u64', + 'f32', + 'f64', + 'bool', + 'bstr', + ], + ) + t.is(variants[14].toBool(), true) + t.is(variants[15].toStringValue(), 'automation') + t.throws(() => DynComVariant.i8(128), { message: /out of range/ }) + + const unknown = DynComVariant.unknown(DynWinRtValue.activationFactory('Windows.Foundation.Uri')) + t.is(unknown.kind, 'unknown') + t.truthy(unknown.toInterface()) + const dispatch = DynComVariant.dispatch() + t.is(dispatch.kind, 'dispatch') + t.is(dispatch.toInterface(), null) + + const bounds = [ + { lowerBound: -2, length: 2 }, + { lowerBound: 5, length: 2 }, + ] + const arrays = [ + DynComSafeArray.i8([-1]), + DynComSafeArray.u8([1]), + DynComSafeArray.i16([-2]), + DynComSafeArray.u16([2]), + DynComSafeArray.i32([1, 2, 3, 4], bounds), + DynComSafeArray.u32([3]), + DynComSafeArray.i64([-4n]), + DynComSafeArray.u64([4n]), + DynComSafeArray.f32([1.25]), + DynComSafeArray.f64([2.5]), + DynComSafeArray.bool([true, false]), + DynComSafeArray.bstr(['a', 'b']), + DynComSafeArray.unknown([]), + DynComSafeArray.dispatch([]), + DynComSafeArray.variant([DynComVariant.i32(7), DynComVariant.bstr('v')]), + ] + t.deepEqual( + arrays.map((value) => value.elementType), + [ + 'i8', + 'u8', + 'i16', + 'u16', + 'i32', + 'u32', + 'i64', + 'u64', + 'f32', + 'f64', + 'bool', + 'bstr', + 'unknown', + 'dispatch', + 'variant', + ], + ) + t.deepEqual(arrays[4].bounds, bounds) + t.deepEqual(arrays[4].toNumbers(), [1, 2, 3, 4]) + t.deepEqual(arrays[10].toBools(), [true, false]) + t.deepEqual(arrays[11].toStrings(), ['a', 'b']) + t.deepEqual(arrays[12].toInterfaces(), []) + t.deepEqual(arrays[13].toInterfaces(), []) + t.deepEqual( + arrays[14].toVariants().map((value) => value.kind), + ['i32', 'bstr'], + ) + t.throws(() => DynComSafeArray.i32([1], [{ lowerBound: 0, length: 2 }]), { + message: /require 2 element/, + }) + t.throws( + () => + DynComSafeArray.i32( + [1], + Array.from({ length: 9 }, () => ({ lowerBound: 0, length: 1 })), + ), + { message: /ranks must be between 1 and 8/ }, + ) + + const activationFactoryIid = WinGuid.parse('00000035-0000-0000-c000-000000000046') + const activationFactory = DynWinRtValue.activationFactory('Windows.Foundation.Uri') + const interfaceArray = DynComSafeArray.interface( + activationFactoryIid, + [activationFactory], + [{ lowerBound: -4, length: 1 }], + ) + t.is(interfaceArray.elementType, 'unknown') + t.is(interfaceArray.interfaceIid?.toString().toLowerCase(), activationFactoryIid.toString().toLowerCase()) + t.deepEqual(interfaceArray.bounds, [{ lowerBound: -4, length: 1 }]) + t.is(interfaceArray.toInterfaces().length, 1) + t.notThrows(() => DynCom.safeArrayType('unknown', activationFactoryIid)) + t.notThrows(() => DynCom.safeArrayType('unknown', activationFactoryIid, true)) + t.throws(() => DynCom.safeArrayType('i32', activationFactoryIid), { + message: /requires VT_UNKNOWN/, + }) + t.throws( + () => DynComSafeArray.interface(WinGuid.parse('ffffffff-ffff-ffff-ffff-ffffffffffff'), [activationFactory]), + { message: /interface is not supported|No such interface supported/i }, + ) + const nullSafeArray = DynWinRtValue.nullValue() + t.is(DynCom.takeNullableSafeArray(nullSafeArray), null) + const nullableSafeArray = DynCom.safeArray(interfaceArray) + const takenNullableSafeArray = DynCom.takeNullableSafeArray(nullableSafeArray) + t.is( + takenNullableSafeArray?.interfaceIid?.toString().toLowerCase(), + activationFactoryIid.toString().toLowerCase(), + ) + + const arrayVariant = DynComVariant.safeArray(arrays[4]) + t.deepEqual(arrayVariant.toSafeArray().toNumbers(), [1, 2, 3, 4]) + + const props = [ + DynComPropVariant.empty(), + DynComPropVariant.null(), + DynComPropVariant.i8(-1), + DynComPropVariant.u8(1), + DynComPropVariant.i16(-2), + DynComPropVariant.u16(2), + DynComPropVariant.i32(-3), + DynComPropVariant.u32(3), + DynComPropVariant.int(-4), + DynComPropVariant.uint(4), + DynComPropVariant.i64(-5n), + DynComPropVariant.u64(5n), + DynComPropVariant.f32(1.5), + DynComPropVariant.f64(2.5), + DynComPropVariant.bool(true), + DynComPropVariant.string('property'), + DynComPropVariant.guid(WinGuid.parse('00112233-4455-6677-8899-aabbccddeeff')), + DynComPropVariant.filetime(123n), + DynComPropVariant.blob(Buffer.from([1, 2, 3])), + ] + t.deepEqual( + props.slice(0, 19).map((value) => value.kind), + [ + 'empty', + 'null', + 'i8', + 'u8', + 'i16', + 'u16', + 'i32', + 'u32', + 'int', + 'uint', + 'i64', + 'u64', + 'f32', + 'f64', + 'bool', + 'string', + 'guid', + 'filetime', + 'blob', + ], + ) + t.is(props[15].toStringValue(), 'property') + t.is(props[17].toBigint(), 123n) + t.deepEqual(props[18].toBlob(), Buffer.from([1, 2, 3])) + for (const [value, expected] of [ + [DynComPropVariant.i8Vector([-1]), [-1]], + [DynComPropVariant.u8Vector([1]), [1]], + [DynComPropVariant.i16Vector([-2]), [-2]], + [DynComPropVariant.u16Vector([2]), [2]], + [DynComPropVariant.i32Vector([-3]), [-3]], + [DynComPropVariant.u32Vector([3]), [3]], + [DynComPropVariant.f32Vector([1.5]), [1.5]], + [DynComPropVariant.f64Vector([2.5]), [2.5]], + ] as const) { + t.deepEqual(value.toNumbers(), expected) + } + t.deepEqual(DynComPropVariant.i64Vector([-4n]).toBigints(), [-4n]) + t.deepEqual(DynComPropVariant.u64Vector([4n]).toBigints(), [4n]) + t.deepEqual(DynComPropVariant.boolVector([true, false]).toBools(), [true, false]) + t.deepEqual(DynComPropVariant.stringVector(['a', 'b']).toStrings(), ['a', 'b']) + t.is(DynComPropVariant.guidVector([WinGuid.parse('00112233-4455-6677-8899-aabbccddeeff')]).toGuidStrings().length, 1) + t.deepEqual(DynComPropVariant.filetimeVector([1n, 2n]).toBigints(), [1n, 2n]) + t.deepEqual(DynComPropVariant.boolVector([]).toBools(), []) + t.deepEqual(DynComPropVariant.stringVector([]).toStrings(), []) + t.deepEqual(DynComPropVariant.filetimeVector([]).toBigints(), []) + + const stored = DynCom.variant(DynComVariant.bstr('transfer')) + t.is(DynCom.takeVariant(stored).toStringValue(), 'transfer') + t.throws(() => DynCom.takeVariant(stored), { message: /not a COM VARIANT/ }) + + const released = DynComVariant.i32(1) + released.release() + t.throws(() => released.kind, { message: /released/ }) + + const dispatchParams = new DynComDispatchParams([DynComVariant.i32(10), DynComVariant.bstr('named')], [42]) + t.is(dispatchParams.argumentCount, 2) + t.deepEqual(dispatchParams.namedDispids, [42]) + const clonedDispatchParams = dispatchParams.clone() + dispatchParams.release() + t.throws(() => dispatchParams.argumentCount, { message: /released/ }) + t.is(clonedDispatchParams.argumentCount, 2) + t.throws(() => new DynComDispatchParams([DynComVariant.i32(1)], [1, 2]), { + message: /exceeds argument count/, + }) + t.throws(() => new DynComDispatchParams([DynComVariant.i32(1)], [1.5]), { + message: /integral number/, + }) + + const invokeSig = new DynComMethodSig() + .addIn(DynCom.i32Type()) + .addIn(DynCom.pointerType()) + .addIn(DynCom.u32Type()) + .addIn(DynCom.u16Type()) + .addIn(DynCom.dispatchParamsType()) + .addOptionalOut(DynCom.variantType()) + .addOptionalOut(DynCom.excepInfoType()) + .addOptionalOut(DynCom.u32Type()) + .captureDispatchInvokeHresult() + const dispatchIid = WinGuid.parse('00020400-0000-0000-c000-000000000046') + t.notThrows(() => + DynCom.registerIUnknownInterface('Windows.Win32.System.Com.IDispatch', dispatchIid).addMethodAt( + 6, + 'Invoke', + invokeSig, + ), + ) + t.throws( + () => + DynCom.registerIUnknownInterface( + 'Tests.INotDispatch', + WinGuid.parse('10000000-0000-0000-0000-000000000010'), + ).addMethodAt(6, 'Invoke', invokeSig), + { message: /restricted to the exact IDispatch::Invoke/ }, + ) +}) + test('DynCom distinguishes handle-value bytes from data-pointer storage', (t) => { const width = process.arch === 'ia32' ? 4 : 8 const expected = 0x12345678n @@ -415,10 +849,7 @@ test('create empty vectors for large struct element types', (t) => { DynWinRtType.i32(), ]) const vector = DynWinRtValue.createVector([], rectType) - const vectorIid = DynWinRtType.parameterized( - WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), - [rectType], - ).iid() + const vectorIid = DynWinRtType.parameterized(WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), [rectType]).iid() t.notThrows(() => vector.cast(vectorIid)) }) diff --git a/bindings/js/package.json b/bindings/js/package.json index 779bdace..b2eb1ea9 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -17,12 +17,21 @@ "require": "./dist/com.js", "default": "./dist/com.js" }, + "./com/unsafe": { + "types": "./dist/com-unsafe.d.ts", + "import": "./dist/com-unsafe.js", + "require": "./dist/com-unsafe.js", + "default": "./dist/com-unsafe.js" + }, "./package.json": "./package.json" }, "typesVersions": { "*": { "com": [ "dist/com.d.ts" + ], + "com/unsafe": [ + "dist/com-unsafe.d.ts" ] } }, diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index 2fa73d4a..b5e6785c 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -17,28 +17,53 @@ if (nativeExports.length === 0) { } const comExports = new Set([ + 'DynComDispatchParams', + 'DynComExcepInfo', + 'DynComNativeStruct', + 'DynComNativeStructArray', + 'DynComNativeUnion', + 'DynComPropVariant', + 'DynComSafeArray', + 'DynComVariant', + 'DynWinRtValue', + 'DynWinRTValue', + 'WinGuid', + 'WinGUID', + 'initializeCom', +]) +const comTypeExports = [...comExports, 'DynComSafeArrayBound'] +const comUnsafeExports = new Set([ + ...comExports, 'DynCom', + 'DynComDispatchInvokeResult', 'DynComInterface', 'DynComMethodHandle', 'DynComMethodSig', 'DynComType', - 'DynWinRtValue', - 'DynWinRTValue', - 'WinGuid', - 'WinGUID', + 'DynComUnsafe', + 'DynComUnsafeInterface', ]) +const comUnsafeTypeExports = [...comUnsafeExports, 'DynComSafeArrayBound'] writeFacade( 'winrt', - nativeExports.filter((name) => !name.startsWith('DynCom')), + nativeExports.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom'), ) writeFacade( 'com', nativeExports.filter((name) => comExports.has(name)), + comTypeExports, + comExports, +) +writeFacade( + 'com-unsafe', + nativeExports.filter((name) => comUnsafeExports.has(name)), + comUnsafeTypeExports, + comUnsafeExports, ) -function writeFacade(name, exports) { - const missing = name === 'com' ? [...comExports].filter((value) => !exports.includes(value)) : [] +function writeFacade(name, exports, typeExports = exports, requiredExports = []) { + const missing = [...requiredExports].filter((value) => !exports.includes(value)) if (missing.length > 0) { throw new Error(`Missing required ${name} exports: ${missing.join(', ')}`) } @@ -52,7 +77,7 @@ function writeFacade(name, exports) { ].join('\n') const dts = [ '// Generated by scripts/generate-entrypoints.mjs - do not edit', - `export { ${exports.join(', ')} } from './index.js'`, + `export { ${typeExports.join(', ')} } from './index.js'`, '', ].join('\n') diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index ce4f84e8..0f984682 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use napi::bindgen_prelude::{BigInt, FromNapiValue, ToNapiValue, Unknown}; +use napi::bindgen_prelude::{BigInt, Buffer, FromNapiValue, ToNapiValue, Unknown}; use napi::JsValue; use napi_derive::napi; use windows::core::{Interface as _, GUID}; @@ -16,12 +16,150 @@ pub(super) enum NativePointerOwner { pointer: usize, length: usize, }, + TypedBuffer { + env: napi::sys::napi_env, + reference: napi::sys::napi_ref, + pointer: usize, + byte_length: usize, + typed_array_type: i32, + }, CoTaskMem(*mut std::ffi::c_void), Guid(*mut GUID), WideString(Box<[u16]>), AnsiString(Box<[u8]>), } +enum AutomationValueKind { + Bstr(dynwinrt::com::BstrValue), + NativeUnion(dynwinrt::com::NativeUnionValue), + Variant(dynwinrt::com::VariantValue), + SafeArray(dynwinrt::com::SafeArrayValue), + PropVariant(dynwinrt::com::PropVariantValue), + DispatchParams(dynwinrt::com::DispatchParamsValue), + ExcepInfo(dynwinrt::com::ExcepInfoValue), +} + +pub(super) struct AutomationValue { + owner_thread: std::thread::ThreadId, + value: Option, +} + +impl AutomationValue { + pub(super) fn new(value: dynwinrt::com::Value) -> Self { + let value = match value { + dynwinrt::com::Value::Bstr(value) => AutomationValueKind::Bstr(value), + dynwinrt::com::Value::NativeUnion(value) => AutomationValueKind::NativeUnion(value), + dynwinrt::com::Value::Variant(value) => AutomationValueKind::Variant(value), + dynwinrt::com::Value::SafeArray(value) => AutomationValueKind::SafeArray(value), + dynwinrt::com::Value::PropVariant(value) => AutomationValueKind::PropVariant(value), + dynwinrt::com::Value::DispatchParams(value) => AutomationValueKind::DispatchParams(value), + dynwinrt::com::Value::ExcepInfo(value) => AutomationValueKind::ExcepInfo(value), + _ => unreachable!("AutomationValue requires an automation COM value"), + }; + Self { + owner_thread: std::thread::current().id(), + value: Some(value), + } + } + + fn ensure_owner_thread(&self) -> napi::Result<()> { + if matches!(self.value, Some(AutomationValueKind::Bstr(_))) + || std::thread::current().id() == self.owner_thread + { + Ok(()) + } else { + Err(napi::Error::from_reason( + "Apartment-bound COM Automation value used from a different thread", + )) + } + } + + pub(super) fn to_com_value(&self) -> napi::Result { + self.ensure_owner_thread()?; + let value = self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("COM Automation value has been consumed"))?; + Ok(match value { + AutomationValueKind::Bstr(value) => dynwinrt::com::Value::Bstr(value.clone()), + AutomationValueKind::NativeUnion(value) => dynwinrt::com::Value::NativeUnion(value.clone()), + AutomationValueKind::Variant(value) => dynwinrt::com::Value::Variant(value.clone()), + AutomationValueKind::SafeArray(value) => dynwinrt::com::Value::SafeArray(value.clone()), + AutomationValueKind::PropVariant(value) => dynwinrt::com::Value::PropVariant(value.clone()), + AutomationValueKind::DispatchParams(value) => { + dynwinrt::com::Value::DispatchParams(value.clone()) + } + AutomationValueKind::ExcepInfo(value) => dynwinrt::com::Value::ExcepInfo(value.clone()), + }) + } + + pub(super) fn take_variant(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::Variant(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not a COM VARIANT")) + } + } + } + + pub(super) fn take_safe_array(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::SafeArray(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not a COM SAFEARRAY")) + } + } + } + + pub(super) fn take_prop_variant(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::PropVariant(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not a COM PROPVARIANT")) + } + } + } + + pub(super) fn take_excep_info(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::ExcepInfo(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not COM EXCEPINFO")) + } + } + } + + pub(super) fn leak_for_shutdown(&mut self) { + if let Some(value) = self.value.take() { + std::mem::forget(value); + } + } +} + +impl Drop for AutomationValue { + fn drop(&mut self) { + if !matches!(self.value, Some(AutomationValueKind::Bstr(_))) + && (std::thread::current().id() != self.owner_thread || super::winui_dispatcher_loop_exited()) + { + self.leak_for_shutdown(); + } + } +} + +// Safety: access is rejected off the creating apartment. Wrong-thread and +// post-WinUI destruction drops leak the value instead of invoking native +// cleanup on an invalid apartment. +unsafe impl Send for AutomationValue {} +unsafe impl Sync for AutomationValue {} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum PointerProvenance { None, @@ -34,6 +172,30 @@ pub(super) enum PointerProvenance { impl NativePointerOwner { fn validate(&self) -> napi::Result<()> { + if let Self::TypedBuffer { + env, + reference, + pointer, + byte_length, + typed_array_type, + } = self + { + let mut raw = std::ptr::null_mut(); + napi::check_status!( + unsafe { napi::sys::napi_get_reference_value(*env, *reference, &mut raw) }, + "Failed to revalidate COM buffer owner" + )?; + let info = typed_buffer_info(*env, raw)?; + if info.pointer != *pointer + || info.byte_length != *byte_length + || info.typed_array_type != *typed_array_type + { + return Err(napi::Error::from_reason( + "Cannot use a COM buffer whose TypedArray backing storage changed", + )); + } + return Ok(()); + } let Self::Uint8Array { value, env, @@ -107,6 +269,12 @@ impl Drop for NativePointerOwner { *ptr = std::ptr::null_mut(); } } + Self::TypedBuffer { env, reference, .. } => { + if !reference.is_null() { + let _ = unsafe { napi::sys::napi_delete_reference(*env, *reference) }; + *reference = std::ptr::null_mut(); + } + } _ => {} } } @@ -168,6 +336,178 @@ struct Uint8ArrayInfo { length: usize, } +struct TypedBufferInfo { + pointer: usize, + byte_length: usize, + source_element_size: usize, + raw_bytes: bool, + typed_array_type: i32, +} + +fn reject_shared_array_buffer( + env: napi::sys::napi_env, + array_buffer: napi::sys::napi_value, +) -> napi::Result<()> { + let mut is_array_buffer = false; + napi::check_status!( + unsafe { napi::sys::napi_is_arraybuffer(env, array_buffer, &mut is_array_buffer) }, + "Failed to inspect TypedArray backing storage" + )?; + if !is_array_buffer { + return Err(napi::Error::from_reason( + "SharedArrayBuffer-backed views cannot be passed to native COM calls", + )); + } + Ok(()) +} + +fn typed_array_element_size(typed_array_type: i32) -> napi::Result { + use napi::sys::TypedarrayType; + match typed_array_type { + value + if value == TypedarrayType::int8_array as i32 + || value == TypedarrayType::uint8_array as i32 + || value == TypedarrayType::uint8_clamped_array as i32 => + { + Ok(1) + } + value + if value == TypedarrayType::int16_array as i32 + || value == TypedarrayType::uint16_array as i32 => + { + Ok(2) + } + value + if value == TypedarrayType::int32_array as i32 + || value == TypedarrayType::uint32_array as i32 + || value == TypedarrayType::float32_array as i32 => + { + Ok(4) + } + value + if value == TypedarrayType::float64_array as i32 + || value == TypedarrayType::bigint64_array as i32 + || value == TypedarrayType::biguint64_array as i32 => + { + Ok(8) + } + _ => Err(napi::Error::from_reason( + "Unsupported TypedArray element type for a COM buffer", + )), + } +} + +fn typed_buffer_info( + env: napi::sys::napi_env, + raw: napi::sys::napi_value, +) -> napi::Result { + let mut is_typed_array = false; + napi::check_status!( + unsafe { napi::sys::napi_is_typedarray(env, raw, &mut is_typed_array) }, + "Failed to inspect COM buffer value" + )?; + if !is_typed_array { + return Err(napi::Error::from_reason( + "DynCom.buffer(): expected Buffer or TypedArray", + )); + } + let mut typed_array_type = 0; + let mut length = 0usize; + let mut data = std::ptr::null_mut(); + let mut array_buffer = std::ptr::null_mut(); + let mut byte_offset = 0usize; + napi::check_status!( + unsafe { + napi::sys::napi_get_typedarray_info( + env, + raw, + &mut typed_array_type, + &mut length, + &mut data, + &mut array_buffer, + &mut byte_offset, + ) + }, + "Failed to inspect COM TypedArray backing storage" + )?; + reject_shared_array_buffer(env, array_buffer)?; + let mut detached = false; + napi::check_status!( + unsafe { napi::sys::napi_is_detached_arraybuffer(env, array_buffer, &mut detached) }, + "Failed to inspect COM TypedArray backing storage" + )?; + if detached { + return Err(napi::Error::from_reason( + "Cannot use a COM buffer whose backing ArrayBuffer is detached", + )); + } + let source_element_size = typed_array_element_size(typed_array_type)?; + let byte_length = length + .checked_mul(source_element_size) + .ok_or_else(|| napi::Error::from_reason("COM buffer byte length overflow"))?; + let mut is_buffer = false; + napi::check_status!( + unsafe { napi::sys::napi_is_buffer(env, raw, &mut is_buffer) }, + "Failed to identify Node Buffer storage" + )?; + Ok(TypedBufferInfo { + pointer: if byte_length == 0 { 0 } else { data as usize }, + byte_length, + source_element_size, + raw_bytes: is_buffer, + typed_array_type, + }) +} + +fn com_buffer(value: Unknown) -> napi::Result { + let env = value.value().env; + let raw = value.value().value; + let info = typed_buffer_info(env, raw)?; + let mut reference = std::ptr::null_mut(); + napi::check_status!( + unsafe { napi::sys::napi_create_reference(env, raw, 1, &mut reference) }, + "Failed to retain COM buffer backing storage" + )?; + let buffer = unsafe { + dynwinrt::com::ComBufferValue::borrowed( + info.pointer as *mut u8, + info.byte_length, + info.source_element_size, + info.raw_bytes, + true, + ) + } + .map_err(|error| napi::Error::from_reason(error.message()))?; + Ok(DynWinRTValue::with_com_buffer( + buffer, + NativePointerOwner::TypedBuffer { + env, + reference, + pointer: info.pointer, + byte_length: info.byte_length, + typed_array_type: info.typed_array_type, + }, + )) +} + +fn take_array_bytes(value: &mut DynWinRTValue, width: usize) -> napi::Result> { + let buffer = value + .4 + .as_ref() + .ok_or_else(|| napi::Error::from_reason("Value is not an owned COM array result"))?; + let bytes = buffer + .snapshot_bytes() + .map_err(com_error)? + .ok_or_else(|| napi::Error::from_reason("Borrowed COM arrays cannot be consumed"))?; + if width == 0 || bytes.len() % width != 0 { + return Err(napi::Error::from_reason( + "COM array result has an invalid scalar element width", + )); + } + value.4 = None; + Ok(bytes) +} + fn validate_wide_string_bytes(bytes: &[u8]) -> napi::Result<()> { if bytes.len() < 2 || bytes.len() % 2 != 0 { return Err(napi::Error::from_reason( @@ -223,6 +563,7 @@ fn uint8_array_info( }, "Failed to inspect TypedArray backing storage" )?; + reject_shared_array_buffer(env, array_buffer)?; if typed_array_type != napi::sys::TypedarrayType::uint8_array as i32 { return Ok(None); } @@ -453,6 +794,63 @@ fn adopt_com_pointer( } } +fn explicit_raw_com_pointer( + value: Unknown, + operation: &str, +) -> napi::Result<*mut std::ffi::c_void> { + let value = pointer(value)?; + if value.1.is_some() { + return Err(napi::Error::from_reason(format!( + "{operation}(): Buffer and Uint8Array backing addresses are not accepted; pass explicit numeric pointer bits", + ))); + } + match value.0 { + dynwinrt::WinRTValue::RawPtr(ptr) => Ok(ptr), + dynwinrt::WinRTValue::Null => Ok(std::ptr::null_mut()), + _ => Err(napi::Error::from_reason(format!( + "{operation}(): expected bigint, number, null, or undefined", + ))), + } +} + +fn unsafe_adopt_owned_com_pointer(value: Unknown, iid: &WinGUID) -> napi::Result { + let ptr = explicit_raw_com_pointer(value, "adoptOwnedComPointer")?; + adopt_owned_com_pointer_bits(ptr, iid) +} + +fn adopt_owned_com_pointer_bits( + ptr: *mut std::ffi::c_void, + iid: &WinGUID, +) -> napi::Result { + if ptr.is_null() { + return Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)); + } + unsafe { dynwinrt::com::adopt_com_pointer(ptr) } + .cast(&iid.0) + .map(DynWinRTValue::new) + .map_err(|error| napi::Error::from_reason(error.message())) +} + +fn unsafe_borrow_com_pointer(value: Unknown, iid: &WinGUID) -> napi::Result { + let ptr = explicit_raw_com_pointer(value, "borrowComPointer")?; + borrow_com_pointer_bits(ptr, iid) +} + +fn borrow_com_pointer_bits( + ptr: *mut std::ffi::c_void, + iid: &WinGUID, +) -> napi::Result { + if ptr.is_null() { + return Ok(DynWinRTValue::new(dynwinrt::WinRTValue::Null)); + } + let borrowed = unsafe { windows::core::IUnknown::from_raw_borrowed(&ptr) } + .ok_or_else(|| napi::Error::from_reason("borrowComPointer(): pointer must be non-null"))?; + dynwinrt::WinRTValue::Object(borrowed.clone()) + .cast(&iid.0) + .map(DynWinRTValue::new) + .map_err(|error| napi::Error::from_reason(error.message())) +} + fn adopt_co_task_mem_pointer(value: &mut DynWinRTValue) -> napi::Result { let ptr = take_native_output_pointer( value, @@ -537,7 +935,7 @@ fn take_native_output_pointer( } if value.2 != expected { return Err(napi::Error::from_reason(format!( - "Cannot consume {description} pointer with {:?} provenance; expected {:?}", + "only owned native outputs may be consumed: cannot consume {description} pointer with {:?} provenance; expected {:?}", value.2, expected ))); } @@ -571,6 +969,378 @@ fn iid_pointer(value: &WinGUID) -> DynWinRTValue { ) } +fn native_struct_layout( + descriptor: &str, +) -> napi::Result> { + let root: serde_json::Value = serde_json::from_str(descriptor).map_err(|error| { + napi::Error::from_reason(format!("Invalid native struct descriptor: {error}")) + })?; + let name = root + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native struct descriptor is missing `name`"))?; + #[cfg(target_arch = "x86")] + let architecture = "x86"; + #[cfg(target_arch = "x86_64")] + let architecture = "x64"; + #[cfg(target_arch = "aarch64")] + let architecture = "arm64"; + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))] + return Err(napi::Error::from_reason( + "Classic COM native structs support only x86, x64, and ARM64", + )); + let layout = root.get(architecture).ok_or_else(|| { + napi::Error::from_reason(format!( + "Native struct descriptor is missing `{architecture}`" + )) + })?; + parse_native_struct_variant(name, layout) +} + +fn native_union_layout( + descriptor: &str, +) -> napi::Result> { + let root: serde_json::Value = serde_json::from_str(descriptor).map_err(|error| { + napi::Error::from_reason(format!("Invalid native union descriptor: {error}")) + })?; + let name = root + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native union descriptor is missing `name`"))?; + #[cfg(target_arch = "x86")] + let architecture = "x86"; + #[cfg(target_arch = "x86_64")] + let architecture = "x64"; + #[cfg(target_arch = "aarch64")] + let architecture = "arm64"; + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))] + return Err(napi::Error::from_reason( + "Classic COM native unions support only x86, x64, and ARM64", + )); + let layout = root.get(architecture).ok_or_else(|| { + napi::Error::from_reason(format!( + "Native union descriptor is missing `{architecture}`" + )) + })?; + parse_native_union_variant(name, layout) +} + +fn parse_native_union_variant( + name: &str, + layout: &serde_json::Value, +) -> napi::Result> { + let size = json_usize(layout, "size")?; + let alignment = json_usize(layout, "alignment")?; + let fields = layout + .get("fields") + .and_then(serde_json::Value::as_array) + .ok_or_else(|| napi::Error::from_reason("Native union descriptor is missing `fields`"))? + .iter() + .map(|field| { + let field_name = field + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native union field is missing `name`"))?; + let count = u32::try_from(json_usize(field, "count")?) + .map_err(|_| napi::Error::from_reason("Native union field count exceeds u32"))?; + let typ = field + .get("type") + .ok_or_else(|| napi::Error::from_reason("Native union field is missing `type`"))?; + let kind = typ + .get("kind") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native union field type is missing `kind`"))?; + let typ = match kind { + "i8" => dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::I8), + "u8" => dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::U8), + "i16" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::I16) + } + "u16" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::U16) + } + "i32" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::I32) + } + "u32" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::U32) + } + "i64" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::I64) + } + "u64" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::U64) + } + "f32" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::F32) + } + "f64" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::F64) + } + "isize" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::ISize) + } + "usize" => { + dynwinrt::com::NativeUnionFieldType::Scalar(dynwinrt::com::NativeStructScalar::USize) + } + "guid" => dynwinrt::com::NativeUnionFieldType::Guid, + "pointer" => dynwinrt::com::NativeUnionFieldType::Pointer, + "struct" => { + let nested_name = typ + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Nested native struct is missing `name`"))?; + let nested_layout = typ + .get("layout") + .ok_or_else(|| napi::Error::from_reason("Nested native struct is missing `layout`"))?; + dynwinrt::com::NativeUnionFieldType::Struct(parse_native_struct_variant( + nested_name, + nested_layout, + )?) + } + _ => { + return Err(napi::Error::from_reason(format!( + "Unsupported native union field kind `{kind}`" + ))); + } + }; + dynwinrt::com::NativeUnionField::new(field_name, count, typ) + .map_err(|error| napi::Error::from_reason(error.message())) + }) + .collect::>>()?; + dynwinrt::com::NativeUnionLayout::new(name, size, alignment, fields) + .map(std::sync::Arc::new) + .map_err(|error| napi::Error::from_reason(error.message())) +} + +fn parse_native_struct_variant( + name: &str, + layout: &serde_json::Value, +) -> napi::Result> { + let size = json_usize(layout, "size")?; + let alignment = json_usize(layout, "alignment")?; + let fields = layout + .get("fields") + .and_then(serde_json::Value::as_array) + .ok_or_else(|| napi::Error::from_reason("Native struct descriptor is missing `fields`"))? + .iter() + .map(|field| { + let field_name = field + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native struct field is missing `name`"))?; + let offset = json_usize(field, "offset")?; + let count = u32::try_from(json_usize(field, "count")?) + .map_err(|_| napi::Error::from_reason("Native struct field count exceeds u32"))?; + let typ = field + .get("type") + .ok_or_else(|| napi::Error::from_reason("Native struct field is missing `type`"))?; + let kind = typ + .get("kind") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Native struct field type is missing `kind`"))?; + let typ = match kind { + "i8" => dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::I8), + "u8" => dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::U8), + "i16" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::I16) + } + "u16" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::U16) + } + "i32" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::I32) + } + "u32" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::U32) + } + "i64" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::I64) + } + "u64" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::U64) + } + "f32" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::F32) + } + "f64" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::F64) + } + "isize" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::ISize) + } + "usize" => { + dynwinrt::com::NativeStructFieldType::Scalar(dynwinrt::com::NativeStructScalar::USize) + } + "guid" => dynwinrt::com::NativeStructFieldType::Guid, + "pointer" => dynwinrt::com::NativeStructFieldType::Pointer, + "struct" => { + let nested_name = typ + .get("name") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| napi::Error::from_reason("Nested native struct is missing `name`"))?; + let nested_layout = typ + .get("layout") + .ok_or_else(|| napi::Error::from_reason("Nested native struct is missing `layout`"))?; + dynwinrt::com::NativeStructFieldType::Struct(parse_native_struct_variant( + nested_name, + nested_layout, + )?) + } + _ => { + return Err(napi::Error::from_reason(format!( + "Unsupported native struct field kind `{kind}`" + ))); + } + }; + dynwinrt::com::NativeStructField::new(field_name, offset, count, typ) + .map_err(|error| napi::Error::from_reason(error.message())) + }) + .collect::>>()?; + dynwinrt::com::NativeStructLayout::new(name, size, alignment, fields) + .map(std::sync::Arc::new) + .map_err(|error| napi::Error::from_reason(error.message())) +} + +fn json_usize(value: &serde_json::Value, name: &str) -> napi::Result { + value + .get(name) + .and_then(serde_json::Value::as_u64) + .and_then(|value| usize::try_from(value).ok()) + .ok_or_else(|| { + napi::Error::from_reason(format!("Native struct descriptor has invalid `{name}`")) + }) +} + +fn com_error(error: dynwinrt::Error) -> napi::Error { + napi::Error::from_reason(error.message()) +} + +fn bigint_i64(value: BigInt, name: &str) -> napi::Result { + let (value, lossless) = value.get_i64(); + if lossless { + Ok(value) + } else { + Err(napi::Error::from_reason(format!( + "{name} value must fit in a signed 64-bit integer" + ))) + } +} + +fn bigint_u64(value: BigInt, name: &str) -> napi::Result { + let (negative, value, lossless) = value.get_u64(); + if !negative && lossless { + Ok(value) + } else { + Err(napi::Error::from_reason(format!( + "{name} value must fit in an unsigned 64-bit integer" + ))) + } +} + +fn checked_signed_number(value: f64, min: i64, max: i64, name: &str) -> napi::Result { + if !value.is_finite() || value.fract() != 0.0 || value < min as f64 || value > max as f64 { + return Err(napi::Error::from_reason(format!( + "{name} value is out of range or not an integral number ({min}..={max})" + ))); + } + Ok(value as i64) +} + +fn checked_unsigned_number(value: f64, max: u64, name: &str) -> napi::Result { + if !value.is_finite() || value.fract() != 0.0 || value < 0.0 || value > max as f64 { + return Err(napi::Error::from_reason(format!( + "{name} value is out of range or not an integral number (0..={max})" + ))); + } + Ok(value as u64) +} + +fn optional_com_object( + value: Option<&DynWinRTValue>, + name: &str, +) -> napi::Result> { + value + .map(|value| { + value + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason(format!("{name} requires a COM object or null"))) + }) + .transpose() +} + +fn variant_kind(typ: dynwinrt::com::VariantType) -> &'static str { + match typ { + dynwinrt::com::VariantType::Empty => "empty", + dynwinrt::com::VariantType::Null => "null", + dynwinrt::com::VariantType::I8 => "i8", + dynwinrt::com::VariantType::U8 => "u8", + dynwinrt::com::VariantType::I16 => "i16", + dynwinrt::com::VariantType::U16 => "u16", + dynwinrt::com::VariantType::I32 => "i32", + dynwinrt::com::VariantType::U32 => "u32", + dynwinrt::com::VariantType::I64 => "i64", + dynwinrt::com::VariantType::U64 => "u64", + dynwinrt::com::VariantType::Int => "int", + dynwinrt::com::VariantType::UInt => "uint", + dynwinrt::com::VariantType::F32 => "f32", + dynwinrt::com::VariantType::F64 => "f64", + dynwinrt::com::VariantType::Bool => "bool", + dynwinrt::com::VariantType::Bstr => "bstr", + dynwinrt::com::VariantType::Unknown => "unknown", + dynwinrt::com::VariantType::Dispatch => "dispatch", + dynwinrt::com::VariantType::SafeArray(_) => "safeArray", + } +} + +fn safe_array_element_kind(typ: dynwinrt::com::SafeArrayElementType) -> &'static str { + match typ { + dynwinrt::com::SafeArrayElementType::I8 => "i8", + dynwinrt::com::SafeArrayElementType::U8 => "u8", + dynwinrt::com::SafeArrayElementType::I16 => "i16", + dynwinrt::com::SafeArrayElementType::U16 => "u16", + dynwinrt::com::SafeArrayElementType::I32 => "i32", + dynwinrt::com::SafeArrayElementType::U32 => "u32", + dynwinrt::com::SafeArrayElementType::I64 => "i64", + dynwinrt::com::SafeArrayElementType::U64 => "u64", + dynwinrt::com::SafeArrayElementType::F32 => "f32", + dynwinrt::com::SafeArrayElementType::F64 => "f64", + dynwinrt::com::SafeArrayElementType::Bool => "bool", + dynwinrt::com::SafeArrayElementType::Bstr => "bstr", + dynwinrt::com::SafeArrayElementType::Unknown => "unknown", + dynwinrt::com::SafeArrayElementType::Dispatch => "dispatch", + dynwinrt::com::SafeArrayElementType::Variant => "variant", + } +} + +fn safe_array_element_type_from_name( + name: &str, +) -> napi::Result { + Ok(match name { + "i8" => dynwinrt::com::SafeArrayElementType::I8, + "u8" => dynwinrt::com::SafeArrayElementType::U8, + "i16" => dynwinrt::com::SafeArrayElementType::I16, + "u16" => dynwinrt::com::SafeArrayElementType::U16, + "i32" => dynwinrt::com::SafeArrayElementType::I32, + "u32" => dynwinrt::com::SafeArrayElementType::U32, + "i64" => dynwinrt::com::SafeArrayElementType::I64, + "u64" => dynwinrt::com::SafeArrayElementType::U64, + "f32" => dynwinrt::com::SafeArrayElementType::F32, + "f64" => dynwinrt::com::SafeArrayElementType::F64, + "bool" => dynwinrt::com::SafeArrayElementType::Bool, + "bstr" => dynwinrt::com::SafeArrayElementType::Bstr, + "unknown" => dynwinrt::com::SafeArrayElementType::Unknown, + "dispatch" => dynwinrt::com::SafeArrayElementType::Dispatch, + "variant" => dynwinrt::com::SafeArrayElementType::Variant, + _ => { + return Err(napi::Error::from_reason(format!( + "Unsupported SAFEARRAY element type `{name}`" + ))); + } + }) +} + #[napi] pub struct DynComType(dynwinrt::com::Type); @@ -595,28 +1365,165 @@ impl DynComMethodSig { } #[napi] - pub fn add_in_out(&self, typ: &DynComType) -> Self { - Self(self.0.clone().add_in_out(typ.0.clone())) + pub fn add_optional_out(&self, typ: &DynComType) -> Self { + Self(self.0.clone().add_optional_out(typ.0.clone())) } #[napi] - pub fn add_out_fill(&self, typ: &DynComType) -> Self { - Self(self.0.clone().add_out_fill(typ.0.clone())) + pub fn capture_dispatch_invoke_hresult(&self) -> Self { + Self(self.0.clone().capture_dispatch_invoke_hresult()) } #[napi] - pub fn returns(&self, typ: &DynComType) -> Self { - Self(self.0.clone().returns(typ.0.clone())) + pub fn add_in_out(&self, typ: &DynComType) -> Self { + Self(self.0.clone().add_in_out(typ.0.clone())) } #[napi] - pub fn returns_void(&self) -> Self { - Self(self.0.clone().returns_void()) + pub fn add_out_fill(&self, typ: &DynComType) -> Self { + Self(self.0.clone().add_out_fill(typ.0.clone())) } #[napi] - pub fn preserve_hresult(&self) -> Self { - Self(self.0.clone().preserve_hresult()) + pub fn add_input_buffer( + &self, + element_type: &DynComType, + count_param_index: u32, + actual_length_param_index: Option, + count_in_bytes: bool, + ) -> napi::Result { + self + .0 + .clone() + .add_input_buffer( + element_type.0.clone(), + count_param_index as usize, + actual_length_param_index.map(|index| index as usize), + if count_in_bytes { + dynwinrt::com::BufferCountUnit::Bytes + } else { + dynwinrt::com::BufferCountUnit::Elements + }, + ) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn add_input_string_array(&self, wide: bool, count_param_index: u32) -> napi::Result { + self + .0 + .clone() + .add_input_string_array( + if wide { + dynwinrt::com::StringEncoding::Utf16 + } else { + dynwinrt::com::StringEncoding::Ansi + }, + count_param_index as usize, + ) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn add_caller_output_buffer( + &self, + element_type: &DynComType, + capacity_param_index: u32, + actual_length_param_index: Option, + count_in_bytes: bool, + two_call: bool, + ) -> napi::Result { + self + .0 + .clone() + .add_caller_output_buffer( + element_type.0.clone(), + capacity_param_index as usize, + actual_length_param_index.map(|index| index as usize), + if count_in_bytes { + dynwinrt::com::BufferCountUnit::Bytes + } else { + dynwinrt::com::BufferCountUnit::Elements + }, + two_call, + ) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn add_enumerator_next_buffer( + &self, + element_type: &DynComType, + capacity_param_index: u32, + fetched_param_index: u32, + ) -> napi::Result { + self + .0 + .clone() + .add_enumerator_next_buffer( + element_type.0.clone(), + capacity_param_index as usize, + fetched_param_index as usize, + ) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn add_co_task_mem_output_buffer( + &self, + element_type: &DynComType, + count_param_index: u32, + count_in_bytes: bool, + ) -> napi::Result { + self + .0 + .clone() + .add_callee_allocated_buffer( + element_type.0.clone(), + count_param_index as usize, + if count_in_bytes { + dynwinrt::com::BufferCountUnit::Bytes + } else { + dynwinrt::com::BufferCountUnit::Elements + }, + dynwinrt::com::BufferAllocator::CoTaskMem, + ) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn returns(&self, typ: &DynComType) -> Self { + Self(self.0.clone().returns(typ.0.clone())) + } + + #[napi] + pub fn returns_void(&self) -> Self { + Self(self.0.clone().returns_void()) + } + + #[napi] + pub fn preserve_hresult(&self) -> Self { + Self(self.0.clone().preserve_hresult()) + } + + #[napi] + pub fn preserve_enumerator_next_hresult(&self) -> Self { + Self(self.0.clone().preserve_enumerator_next_hresult()) + } + + #[napi] + pub fn preserve_enumerator_next_hresult_at(&self, vtable_index: u32) -> Self { + Self( + self + .0 + .clone() + .preserve_enumerator_next_hresult_at(vtable_index as usize), + ) } } @@ -657,9 +1564,78 @@ impl DynComInterface { } } +#[napi] +pub struct DynComUnsafeInterface(dynwinrt::com::Interface); + +#[napi] +impl DynComUnsafeInterface { + #[napi] + pub fn add_method_at( + &self, + vtable_index: u32, + name: String, + signature: &DynComMethodSig, + ) -> napi::Result { + self + .0 + .clone() + .add_method_at(vtable_index as usize, &name, signature.0.clone()) + .map(Self) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi] + pub fn method(&self, vtable_index: i32) -> napi::Result { + self + .0 + .method(vtable_index as usize) + .map(DynComMethodHandle) + .ok_or_else(|| { + napi::Error::from_reason(format!("No COM method at vtable index {vtable_index}")) + }) + } +} + #[napi] pub struct DynComMethodHandle(dynwinrt::com::MethodHandle); +#[napi] +pub struct DynComDispatchInvokeResult { + hresult: i32, + result: Option, + excep_info: Option, + arg_err: Option, + finalization_error: Option, +} + +#[napi] +impl DynComDispatchInvokeResult { + #[napi(getter)] + pub fn hresult(&self) -> i32 { + self.hresult + } + + #[napi(getter)] + pub fn arg_err(&self) -> Option { + self.arg_err + } + + #[napi(getter)] + pub fn finalization_error(&self) -> Option { + self.finalization_error.clone() + } + + #[napi] + pub fn take_result(&mut self) -> Option { + self.result.take() + } + + #[napi] + pub fn take_excep_info(&mut self) -> Option { + self.excep_info.take() + } +} + #[napi] impl DynComMethodHandle { #[napi] @@ -669,9 +1645,7 @@ impl DynComMethodHandle { .as_object() .ok_or_else(|| napi::Error::from_reason("getString() requires a COM object"))? .as_raw(); - self - .0 - .call_getter_hstring(raw) + unsafe { self.0.call_getter_hstring(raw) } .map(|value| value.to_string()) .map_err(|error| napi::Error::from_reason(error.message())) } @@ -682,6 +1656,11 @@ impl DynComMethodHandle { obj: &DynWinRTValue, args: Vec<&DynWinRTValue>, ) -> napi::Result { + if self.0.result_count() > 1 { + return Err(napi::Error::from_reason( + "invoke() cannot discard multiple COM results; use invokeAll()", + )); + } let raw = obj .0 .as_object() @@ -690,16 +1669,17 @@ impl DynComMethodHandle { for arg in &args { validate_pointer_owner(arg)?; } - let args = args.iter().map(|arg| arg.0.clone()).collect::>(); - let mut results = self - .0 - .invoke_with_output_kinds(raw, &args) + let args = args + .iter() + .map(|arg| arg.to_com_value()) + .collect::>>()?; + let mut results = unsafe { self.0.invoke_values_with_output_kinds(raw, &args) } .map_err(|error| napi::Error::from_reason(error.message()))?; let (value, kind) = results.drain(..).next().unwrap_or(( - dynwinrt::WinRTValue::I32(0), + dynwinrt::com::Value::WinRt(dynwinrt::WinRTValue::I32(0)), dynwinrt::com::PointerOutputKind::None, )); - Ok(DynWinRTValue::from_com_result(value, kind)) + Ok(DynWinRTValue::from_com_value(value, kind)) } #[napi] @@ -716,38 +1696,75 @@ impl DynComMethodHandle { for arg in &args { validate_pointer_owner(arg)?; } - let args = args.iter().map(|arg| arg.0.clone()).collect::>(); - self - .0 - .invoke_with_output_kinds(raw, &args) + let args = args + .iter() + .map(|arg| arg.to_com_value()) + .collect::>>()?; + unsafe { self.0.invoke_values_with_output_kinds(raw, &args) } .map(|results| { results .into_iter() - .map(|(value, kind)| DynWinRTValue::from_com_result(value, kind)) + .map(|(value, kind)| DynWinRTValue::from_com_value(value, kind)) .collect() }) .map_err(|error| napi::Error::from_reason(error.message())) } + + #[napi] + pub fn invoke_dispatch( + &self, + obj: &DynWinRTValue, + args: Vec<&DynWinRTValue>, + ) -> napi::Result { + let raw = obj + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("invokeDispatch() requires a COM object"))? + .as_raw(); + for arg in &args { + validate_pointer_owner(arg)?; + } + let args = args + .iter() + .map(|arg| arg.to_com_value()) + .collect::>>()?; + let result = unsafe { self.0.invoke_dispatch(raw, &args) }.map_err(com_error)?; + let (hresult, result, excep_info, arg_err, finalization_error) = result.into_parts(); + Ok(DynComDispatchInvokeResult { + hresult: hresult.0, + result: result.map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Variant(value), + dynwinrt::com::PointerOutputKind::None, + ) + }), + excep_info: excep_info.map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::ExcepInfo(value), + dynwinrt::com::PointerOutputKind::None, + ) + }), + arg_err, + finalization_error: finalization_error.map(|error| error.message()), + }) + } } #[napi] pub struct DynCom; +/// Explicit opt-in surface for manually declared native COM ABI contracts. +/// +/// Supplying an invalid pointer, IID, vtable slot, direction, count relation, +/// or ownership contract can crash the process or corrupt memory. #[napi] -impl DynCom { - #[napi] - pub fn initialize(apartment_type: Option) -> napi::Result<()> { - let apartment_type = match apartment_type.unwrap_or(1) { - 0 => dynwinrt::com::ApartmentType::SingleThreaded, - _ => dynwinrt::com::ApartmentType::MultiThreaded, - }; - dynwinrt::com::initialize_apartment(apartment_type) - .map_err(|error| napi::Error::from_reason(error.message())) - } +pub struct DynComUnsafe; +#[napi] +impl DynComUnsafe { #[napi(js_name = "registerIUnknownInterface")] - pub fn register_iunknown_interface(name: String, iid: &WinGUID) -> DynComInterface { - DynComInterface(dynwinrt::com::register_interface( + pub fn register_iunknown_interface(name: String, iid: &WinGUID) -> DynComUnsafeInterface { + DynComUnsafeInterface(dynwinrt::com::register_interface( &TABLE, &name, iid.0, @@ -756,8 +1773,8 @@ impl DynCom { } #[napi(js_name = "registerIInspectableInterface")] - pub fn register_iinspectable_interface(name: String, iid: &WinGUID) -> DynComInterface { - DynComInterface(dynwinrt::com::register_interface( + pub fn register_iinspectable_interface(name: String, iid: &WinGUID) -> DynComUnsafeInterface { + DynComUnsafeInterface(dynwinrt::com::register_interface( &TABLE, &name, iid.0, @@ -766,268 +1783,2572 @@ impl DynCom { } #[napi] - pub fn bool_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.bool_type())) + pub fn interface_type(iid: &WinGUID) -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) } #[napi] - pub fn i8_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.i8_type())) + pub fn unclassified_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::pointer()) } #[napi] - pub fn u8_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.u8_type())) + pub fn borrowed_handle_output_type() -> DynComType { + DynComType(dynwinrt::com::Type::borrowed_handle_output()) } #[napi] - pub fn i16_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.i16_type())) + pub fn owned_com_output_type() -> DynComType { + DynComType(dynwinrt::com::Type::owned_com_pointer()) } #[napi] - pub fn u16_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.u16_type())) + pub fn co_task_mem_output_type() -> DynComType { + DynComType(dynwinrt::com::Type::co_task_mem_pointer()) } #[napi] - pub fn i32_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.i32_type())) + pub fn bstr_output_type() -> DynComType { + DynComType(dynwinrt::com::Type::bstr_pointer()) } #[napi] - pub fn u32_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.u32_type())) + pub fn pointer( + #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::pointer(value) } #[napi] - pub fn i64_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.i64_type())) + pub fn wide_string_pointer( + #[napi(ts_arg_type = "string | bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::wide_string_pointer(value) } #[napi] - pub fn u64_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.u64_type())) + pub fn ansi_string_pointer( + #[napi(ts_arg_type = "string | bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::ansi_string_pointer(value) } #[napi] - pub fn isize_type() -> DynComType { - #[cfg(target_pointer_width = "64")] - { - DynComType(dynwinrt::com::Type::winrt(TABLE.i64_type())) - } - #[cfg(target_pointer_width = "32")] - { - DynComType(dynwinrt::com::Type::winrt(TABLE.i32_type())) - } + pub fn iid_pointer(value: &WinGUID) -> DynWinRTValue { + self::iid_pointer(value) } #[napi] - pub fn usize_type() -> DynComType { - #[cfg(target_pointer_width = "64")] - { - DynComType(dynwinrt::com::Type::winrt(TABLE.u64_type())) - } - #[cfg(target_pointer_width = "32")] - { - DynComType(dynwinrt::com::Type::winrt(TABLE.u32_type())) - } + pub fn handle_value( + #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array")] value: Unknown, + ) -> napi::Result { + self::handle_value(value) } #[napi] - pub fn f32_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.f32_type())) + pub fn co_create_instance(clsid: String, iid: &WinGUID) -> napi::Result { + self::co_create_instance(clsid, iid) } + /// Takes ownership of one caller-supplied +1 COM reference. #[napi] - pub fn f64_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.f64_type())) + pub fn adopt_owned_com_pointer( + #[napi(ts_arg_type = "bigint | number | null | undefined")] value: Unknown, + iid: &WinGUID, + ) -> napi::Result { + unsafe_adopt_owned_com_pointer(value, iid) } + /// Queries a caller-owned borrowed pointer and returns a new managed +1 reference. #[napi] - pub fn char16_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.char16_type())) + pub fn borrow_com_pointer( + #[napi(ts_arg_type = "bigint | number | null | undefined")] value: Unknown, + iid: &WinGUID, + ) -> napi::Result { + unsafe_borrow_com_pointer(value, iid) } +} - #[napi] - pub fn guid_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.guid_type())) - } +#[napi] +pub struct DynComNativeStruct { + descriptor: String, + bytes: Vec, +} - #[napi] - pub fn hstring_type() -> DynComType { - DynComType(dynwinrt::com::Type::winrt(TABLE.hstring())) - } +#[napi] +pub struct DynComNativeStructArray { + descriptor: String, + bytes: Vec, +} - #[napi] - pub fn hstring(value: String) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::HString(windows::core::HSTRING::from( - value, - ))) +#[napi] +impl DynComNativeStructArray { + #[napi(getter)] + pub fn length(&self) -> u32 { + self.bytes.len() as u32 } - #[napi] - pub fn pointer_type() -> DynComType { - DynComType(dynwinrt::com::Type::pointer()) + #[napi(getter)] + pub fn bytes(&self) -> Buffer { + Buffer::from(self.bytes.clone()) } +} - #[napi] - pub fn owned_com_pointer_type() -> DynComType { - DynComType(dynwinrt::com::Type::owned_com_pointer()) +#[napi] +pub struct DynComNativeUnion { + descriptor: String, + value: dynwinrt::com::NativeUnionValue, +} + +#[napi] +impl DynComNativeUnion { + #[napi(getter)] + pub fn active_field(&self) -> String { + self.value.active_field().into() } - #[napi] - pub fn co_task_mem_pointer_type() -> DynComType { - DynComType(dynwinrt::com::Type::co_task_mem_pointer()) + #[napi(getter)] + pub fn length(&self) -> u32 { + self.value.bytes().len() as u32 } - #[napi] - pub fn bstr_pointer_type() -> DynComType { - DynComType(dynwinrt::com::Type::bstr_pointer()) + #[napi(getter)] + pub fn bytes(&self) -> Buffer { + Buffer::from(self.value.bytes().to_vec()) } +} - #[napi] +#[napi] +pub struct DynComVariant { + value: Option, +} + +impl DynComVariant { + fn new(value: dynwinrt::com::VariantValue) -> Self { + Self { value: Some(value) } + } + + fn value(&self) -> napi::Result<&dynwinrt::com::VariantValue> { + self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("VARIANT has been released")) + } +} + +impl Drop for DynComVariant { + fn drop(&mut self) { + if super::winui_dispatcher_loop_exited() { + if let Some(value) = self.value.take() { + std::mem::forget(value); + } + } + } +} + +#[napi] +impl DynComVariant { + #[napi] + pub fn empty() -> Self { + Self::new(dynwinrt::com::VariantValue::empty()) + } + + #[napi(js_name = "null")] + pub fn null_value() -> Self { + Self::new(dynwinrt::com::VariantValue::null()) + } + + #[napi] + pub fn i8(value: f64) -> napi::Result { + checked_signed_number(value, i8::MIN as i64, i8::MAX as i64, "VARIANT VT_I1") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_i8(value as i8))) + } + + #[napi] + pub fn u8(value: f64) -> napi::Result { + checked_unsigned_number(value, u8::MAX as u64, "VARIANT VT_UI1") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_u8(value as u8))) + } + + #[napi] + pub fn i16(value: f64) -> napi::Result { + checked_signed_number(value, i16::MIN as i64, i16::MAX as i64, "VARIANT VT_I2") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_i16(value as i16))) + } + + #[napi] + pub fn u16(value: f64) -> napi::Result { + checked_unsigned_number(value, u16::MAX as u64, "VARIANT VT_UI2") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_u16(value as u16))) + } + + #[napi] + pub fn i32(value: f64) -> napi::Result { + checked_signed_number(value, i32::MIN as i64, i32::MAX as i64, "VARIANT VT_I4") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_i32(value as i32))) + } + + #[napi] + pub fn u32(value: f64) -> napi::Result { + checked_unsigned_number(value, u32::MAX as u64, "VARIANT VT_UI4") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_u32(value as u32))) + } + + #[napi] + pub fn int(value: f64) -> napi::Result { + checked_signed_number(value, i32::MIN as i64, i32::MAX as i64, "VARIANT VT_INT") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_int(value as i32))) + } + + #[napi] + pub fn uint(value: f64) -> napi::Result { + checked_unsigned_number(value, u32::MAX as u64, "VARIANT VT_UINT") + .map(|value| Self::new(dynwinrt::com::VariantValue::from_uint(value as u32))) + } + + #[napi] + pub fn i64(value: BigInt) -> napi::Result { + bigint_i64(value, "VARIANT VT_I8") + .map(dynwinrt::com::VariantValue::from_i64) + .map(Self::new) + } + + #[napi] + pub fn u64(value: BigInt) -> napi::Result { + bigint_u64(value, "VARIANT VT_UI8") + .map(dynwinrt::com::VariantValue::from_u64) + .map(Self::new) + } + + #[napi] + pub fn f32(value: f64) -> Self { + Self::new(dynwinrt::com::VariantValue::from_f32(value as f32)) + } + + #[napi] + pub fn f64(value: f64) -> Self { + Self::new(dynwinrt::com::VariantValue::from_f64(value)) + } + + #[napi] + pub fn bool(value: bool) -> Self { + Self::new(dynwinrt::com::VariantValue::from_bool(value)) + } + + #[napi] + pub fn bstr(value: String) -> napi::Result { + dynwinrt::com::VariantValue::from_bstr(&value) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn unknown(value: Option<&DynWinRTValue>) -> napi::Result { + let value = optional_com_object(value, "VARIANT VT_UNKNOWN")?; + Ok(Self::new(dynwinrt::com::VariantValue::from_unknown( + value.as_ref(), + ))) + } + + #[napi] + pub fn dispatch(value: Option<&DynWinRTValue>) -> napi::Result { + let value = optional_com_object(value, "VARIANT VT_DISPATCH")?; + dynwinrt::com::VariantValue::from_dispatch(value.as_ref()) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn safe_array(value: &DynComSafeArray) -> napi::Result { + dynwinrt::com::VariantValue::from_safe_array(value.value()?) + .map(Self::new) + .map_err(com_error) + } + + #[napi(getter)] + pub fn vartype(&self) -> napi::Result { + Ok(u32::from(self.value()?.vartype())) + } + + #[napi(getter)] + pub fn kind(&self) -> napi::Result { + Ok(variant_kind(self.value()?.variant_type().map_err(com_error)?).into()) + } + + #[napi] + pub fn to_number(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::I8(value) => Ok(f64::from(value)), + dynwinrt::com::VariantData::U8(value) => Ok(f64::from(value)), + dynwinrt::com::VariantData::I16(value) => Ok(f64::from(value)), + dynwinrt::com::VariantData::U16(value) => Ok(f64::from(value)), + dynwinrt::com::VariantData::I32(value) | dynwinrt::com::VariantData::Int(value) => { + Ok(f64::from(value)) + } + dynwinrt::com::VariantData::U32(value) | dynwinrt::com::VariantData::UInt(value) => { + Ok(f64::from(value)) + } + dynwinrt::com::VariantData::F32(value) => Ok(f64::from(value)), + dynwinrt::com::VariantData::F64(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "VARIANT does not contain a number-sized scalar", + )), + } + } + + #[napi] + pub fn to_bigint(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::I64(value) => Ok(BigInt::from(value)), + dynwinrt::com::VariantData::U64(value) => Ok(BigInt::from(value)), + _ => Err(napi::Error::from_reason( + "VARIANT does not contain a 64-bit integer", + )), + } + } + + #[napi] + pub fn to_bool(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::Bool(value) => Ok(value), + _ => Err(napi::Error::from_reason("VARIANT does not contain VT_BOOL")), + } + } + + #[napi(js_name = "toStringValue")] + pub fn to_string_value(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::Bstr(value) => Ok(value), + _ => Err(napi::Error::from_reason("VARIANT does not contain VT_BSTR")), + } + } + + #[napi] + pub fn to_interface(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::Unknown(value) | dynwinrt::com::VariantData::Dispatch(value) => { + Ok(value.map(|value| DynWinRTValue::new(dynwinrt::WinRTValue::Object(value)))) + } + _ => Err(napi::Error::from_reason( + "VARIANT does not contain VT_UNKNOWN or VT_DISPATCH", + )), + } + } + + #[napi] + pub fn to_safe_array(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::VariantData::SafeArray(value) => Ok(DynComSafeArray::new(value)), + _ => Err(napi::Error::from_reason( + "VARIANT does not contain a SAFEARRAY", + )), + } + } + + #[napi] + pub fn release(&mut self) { + self.value = None; + } +} + +#[napi] +pub struct DynComDispatchParams { + owner_thread: std::thread::ThreadId, + value: Option, +} + +impl DynComDispatchParams { + fn from_value(value: dynwinrt::com::DispatchParamsValue) -> Self { + Self { + owner_thread: std::thread::current().id(), + value: Some(value), + } + } + + fn value(&self) -> napi::Result<&dynwinrt::com::DispatchParamsValue> { + if std::thread::current().id() != self.owner_thread { + return Err(napi::Error::from_reason( + "Apartment-bound DISPPARAMS used from a different thread", + )); + } + self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("DISPPARAMS has been released")) + } +} + +impl Drop for DynComDispatchParams { + fn drop(&mut self) { + if std::thread::current().id() != self.owner_thread || super::winui_dispatcher_loop_exited() { + if let Some(value) = self.value.take() { + std::mem::forget(value); + } + } + } +} + +// Safety: every public operation rejects access away from the creating +// apartment, and wrong-thread/shutdown destruction deliberately leaks. +unsafe impl Send for DynComDispatchParams {} +unsafe impl Sync for DynComDispatchParams {} + +#[napi] +impl DynComDispatchParams { + #[napi(constructor)] + pub fn new( + arguments: Vec<&DynComVariant>, + named_dispids: Option>, + ) -> napi::Result { + let arguments = arguments + .into_iter() + .map(DynComVariant::value) + .collect::>>()?; + let named_dispids = named_dispids + .unwrap_or_default() + .into_iter() + .map(|value| { + checked_signed_number( + value, + i32::MIN as i64, + i32::MAX as i64, + "DISPPARAMS named DISPID", + ) + .map(|value| value as i32) + }) + .collect::>>()?; + dynwinrt::com::DispatchParamsValue::new( + &arguments.into_iter().cloned().collect::>(), + &named_dispids, + ) + .map(Self::from_value) + .map_err(com_error) + } + + #[napi(getter)] + pub fn argument_count(&self) -> napi::Result { + u32::try_from(self.value()?.argument_count()) + .map_err(|_| napi::Error::from_reason("DISPPARAMS argument count exceeds UINT")) + } + + #[napi(getter)] + pub fn named_dispids(&self) -> napi::Result> { + Ok(self.value()?.named_dispids()) + } + + #[napi(js_name = "clone")] + pub fn clone_value(&self) -> napi::Result { + Ok(Self::from_value(self.value()?.clone())) + } + + #[napi] + pub fn release(&mut self) -> napi::Result<()> { + if std::thread::current().id() != self.owner_thread { + return Err(napi::Error::from_reason( + "Apartment-bound DISPPARAMS used from a different thread", + )); + } + self.value = None; + Ok(()) + } +} + +#[napi] +pub struct DynComExcepInfo { + owner_thread: std::thread::ThreadId, + value: Option, +} + +impl DynComExcepInfo { + fn new(value: dynwinrt::com::ExcepInfoValue) -> Self { + Self { + owner_thread: std::thread::current().id(), + value: Some(value), + } + } + + fn value(&self) -> napi::Result<&dynwinrt::com::ExcepInfoValue> { + if std::thread::current().id() != self.owner_thread { + return Err(napi::Error::from_reason( + "Apartment-bound EXCEPINFO used from a different thread", + )); + } + self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("EXCEPINFO has been released")) + } +} + +impl Drop for DynComExcepInfo { + fn drop(&mut self) { + if std::thread::current().id() != self.owner_thread || super::winui_dispatcher_loop_exited() { + if let Some(value) = self.value.take() { + std::mem::forget(value); + } + } + } +} + +unsafe impl Send for DynComExcepInfo {} +unsafe impl Sync for DynComExcepInfo {} + +#[napi] +impl DynComExcepInfo { + #[napi(getter)] + pub fn code(&self) -> napi::Result { + Ok(u32::from(self.value()?.code())) + } + + #[napi(getter)] + pub fn source(&self) -> napi::Result> { + Ok(self.value()?.source().map(str::to_owned)) + } + + #[napi(getter)] + pub fn description(&self) -> napi::Result> { + Ok(self.value()?.description().map(str::to_owned)) + } + + #[napi(getter)] + pub fn help_file(&self) -> napi::Result> { + Ok(self.value()?.help_file().map(str::to_owned)) + } + + #[napi(getter)] + pub fn help_context(&self) -> napi::Result { + Ok(self.value()?.help_context()) + } + + #[napi(getter)] + pub fn scode(&self) -> napi::Result { + Ok(self.value()?.scode()) + } + + #[napi(js_name = "clone")] + pub fn clone_value(&self) -> napi::Result { + Ok(Self::new(self.value()?.clone())) + } + + #[napi] + pub fn release(&mut self) -> napi::Result<()> { + if std::thread::current().id() != self.owner_thread { + return Err(napi::Error::from_reason( + "Apartment-bound EXCEPINFO used from a different thread", + )); + } + self.value = None; + Ok(()) + } +} + +#[napi(object)] +pub struct DynComSafeArrayBound { + pub lower_bound: f64, + pub length: f64, +} + +#[napi] +pub struct DynComSafeArray { + value: Option, +} + +impl DynComSafeArray { + fn new(value: dynwinrt::com::SafeArrayValue) -> Self { + Self { value: Some(value) } + } + + fn value(&self) -> napi::Result<&dynwinrt::com::SafeArrayValue> { + self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("SAFEARRAY has been released")) + } + + fn create( + element_type: dynwinrt::com::SafeArrayElementType, + values: Vec, + bounds: Option>, + ) -> napi::Result { + let bounds = match bounds { + Some(bounds) => bounds + .into_iter() + .map(|bound| { + let lower_bound = checked_signed_number( + bound.lower_bound, + i32::MIN as i64, + i32::MAX as i64, + "SAFEARRAY lower bound", + )? as i32; + let length = + checked_unsigned_number(bound.length, u32::MAX as u64, "SAFEARRAY bound length")? + as u32; + dynwinrt::com::SafeArrayBound::new(lower_bound, length).map_err(com_error) + }) + .collect::>>()?, + None => vec![dynwinrt::com::SafeArrayBound::new( + 0, + u32::try_from(values.len()) + .map_err(|_| napi::Error::from_reason("SAFEARRAY length exceeds u32"))?, + ) + .map_err(com_error)?], + }; + dynwinrt::com::SafeArrayValue::new(element_type, bounds, values) + .map(Self::new) + .map_err(com_error) + } +} + +impl Drop for DynComSafeArray { + fn drop(&mut self) { + if super::winui_dispatcher_loop_exited() { + if let Some(value) = self.value.take() { + std::mem::forget(value); + } + } + } +} + +#[napi] +impl DynComSafeArray { + #[napi] + pub fn i8(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number(value, i8::MIN as i64, i8::MAX as i64, "SAFEARRAY VT_I1") + .map(|value| dynwinrt::com::SafeArrayElementValue::I8(value as i8)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::I8, values, bounds) + } + + #[napi] + pub fn u8(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u8::MAX as u64, "SAFEARRAY VT_UI1") + .map(|value| dynwinrt::com::SafeArrayElementValue::U8(value as u8)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::U8, values, bounds) + } + + #[napi] + pub fn i16(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number(value, i16::MIN as i64, i16::MAX as i64, "SAFEARRAY VT_I2") + .map(|value| dynwinrt::com::SafeArrayElementValue::I16(value as i16)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::I16, values, bounds) + } + + #[napi] + pub fn u16(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u16::MAX as u64, "SAFEARRAY VT_UI2") + .map(|value| dynwinrt::com::SafeArrayElementValue::U16(value as u16)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::U16, values, bounds) + } + + #[napi] + pub fn i32(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number(value, i32::MIN as i64, i32::MAX as i64, "SAFEARRAY VT_I4") + .map(|value| dynwinrt::com::SafeArrayElementValue::I32(value as i32)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::I32, values, bounds) + } + + #[napi] + pub fn u32(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u32::MAX as u64, "SAFEARRAY VT_UI4") + .map(|value| dynwinrt::com::SafeArrayElementValue::U32(value as u32)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::U32, values, bounds) + } + + #[napi] + pub fn i64(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + bigint_i64(value, "SAFEARRAY VT_I8").map(dynwinrt::com::SafeArrayElementValue::I64) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::I64, values, bounds) + } + + #[napi] + pub fn u64(values: Vec, bounds: Option>) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + bigint_u64(value, "SAFEARRAY VT_UI8").map(dynwinrt::com::SafeArrayElementValue::U64) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::U64, values, bounds) + } + + #[napi] + pub fn f32(values: Vec, bounds: Option>) -> napi::Result { + Self::create( + dynwinrt::com::SafeArrayElementType::F32, + values + .into_iter() + .map(|value| dynwinrt::com::SafeArrayElementValue::F32(value as f32)) + .collect(), + bounds, + ) + } + + #[napi] + pub fn f64(values: Vec, bounds: Option>) -> napi::Result { + Self::create( + dynwinrt::com::SafeArrayElementType::F64, + values + .into_iter() + .map(dynwinrt::com::SafeArrayElementValue::F64) + .collect(), + bounds, + ) + } + + #[napi] + pub fn bool(values: Vec, bounds: Option>) -> napi::Result { + Self::create( + dynwinrt::com::SafeArrayElementType::Bool, + values + .into_iter() + .map(dynwinrt::com::SafeArrayElementValue::Bool) + .collect(), + bounds, + ) + } + + #[napi] + pub fn bstr( + values: Vec, + bounds: Option>, + ) -> napi::Result { + Self::create( + dynwinrt::com::SafeArrayElementType::Bstr, + values + .into_iter() + .map(dynwinrt::com::SafeArrayElementValue::Bstr) + .collect(), + bounds, + ) + } + + #[napi] + pub fn unknown( + values: Vec<&DynWinRTValue>, + bounds: Option>, + ) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + optional_com_object(Some(value), "SAFEARRAY VT_UNKNOWN") + .map(|value| dynwinrt::com::SafeArrayElementValue::Unknown(value)) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::Unknown, values, bounds) + } + + #[napi] + pub fn interface( + iid: &WinGUID, + values: Vec<&DynWinRTValue>, + bounds: Option>, + ) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + optional_com_object(Some(value), "SAFEARRAY VT_UNKNOWN") + .map(dynwinrt::com::SafeArrayElementValue::Unknown) + }) + .collect::>>()?; + let bounds = match bounds { + Some(bounds) => bounds + .into_iter() + .map(|bound| { + let lower_bound = checked_signed_number( + bound.lower_bound, + i32::MIN as i64, + i32::MAX as i64, + "SAFEARRAY lower bound", + )? as i32; + let length = + checked_unsigned_number(bound.length, u32::MAX as u64, "SAFEARRAY bound length")? + as u32; + dynwinrt::com::SafeArrayBound::new(lower_bound, length).map_err(com_error) + }) + .collect::>>()?, + None => vec![dynwinrt::com::SafeArrayBound::new( + 0, + u32::try_from(values.len()) + .map_err(|_| napi::Error::from_reason("SAFEARRAY length exceeds u32"))?, + ) + .map_err(com_error)?], + }; + dynwinrt::com::SafeArrayValue::new_interface(iid.0, bounds, values) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn dispatch( + values: Vec<&DynWinRTValue>, + bounds: Option>, + ) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + optional_com_object(Some(value), "SAFEARRAY VT_DISPATCH").and_then(|value| { + let value = value + .map(|value| value.cast::()) + .transpose() + .map_err(|error| napi::Error::from_reason(error.message()))? + .map(|value| value.cast::()) + .transpose() + .map_err(|error| napi::Error::from_reason(error.message()))?; + Ok(dynwinrt::com::SafeArrayElementValue::Dispatch(value)) + }) + }) + .collect::>>()?; + Self::create( + dynwinrt::com::SafeArrayElementType::Dispatch, + values, + bounds, + ) + } + + #[napi] + pub fn variant( + values: Vec<&DynComVariant>, + bounds: Option>, + ) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + value + .value() + .cloned() + .map(dynwinrt::com::SafeArrayElementValue::Variant) + }) + .collect::>>()?; + Self::create(dynwinrt::com::SafeArrayElementType::Variant, values, bounds) + } + + #[napi(getter)] + pub fn element_type(&self) -> napi::Result { + Ok(safe_array_element_kind(self.value()?.element_type()).into()) + } + + #[napi(getter)] + pub fn interface_iid(&self) -> napi::Result> { + Ok(self.value()?.interface_iid().map(WinGUID)) + } + + #[napi(getter)] + pub fn length(&self) -> napi::Result { + Ok(BigInt::from(self.value()?.len() as u64)) + } + + #[napi(getter)] + pub fn bounds(&self) -> napi::Result> { + Ok( + self + .value()? + .bounds() + .iter() + .map(|bound| DynComSafeArrayBound { + lower_bound: f64::from(bound.lower_bound()), + length: f64::from(bound.length()), + }) + .collect(), + ) + } + + #[napi] + pub fn to_numbers(&self) -> napi::Result> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::I8(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::U8(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::I16(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::U16(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::I32(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::U32(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::F32(value) => Ok(f64::from(value)), + dynwinrt::com::SafeArrayElementValue::F64(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not number-sized", + )), + }) + .collect() + } + + #[napi] + pub fn to_bigints(&self) -> napi::Result> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::I64(value) => Ok(BigInt::from(value)), + dynwinrt::com::SafeArrayElementValue::U64(value) => Ok(BigInt::from(value)), + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not a 64-bit integer", + )), + }) + .collect() + } + + #[napi] + pub fn to_bools(&self) -> napi::Result> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::Bool(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not VT_BOOL", + )), + }) + .collect() + } + + #[napi] + pub fn to_strings(&self) -> napi::Result> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::Bstr(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not VT_BSTR", + )), + }) + .collect() + } + + #[napi] + pub fn to_interfaces(&self) -> napi::Result>> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::Unknown(value) + | dynwinrt::com::SafeArrayElementValue::Dispatch(value) => { + Ok(value.map(|value| DynWinRTValue::new(dynwinrt::WinRTValue::Object(value)))) + } + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not VT_UNKNOWN or VT_DISPATCH", + )), + }) + .collect() + } + + #[napi] + pub fn to_variants(&self) -> napi::Result> { + self + .value()? + .elements() + .map_err(com_error)? + .into_iter() + .map(|value| match value { + dynwinrt::com::SafeArrayElementValue::Variant(value) => Ok(DynComVariant::new(value)), + _ => Err(napi::Error::from_reason( + "SAFEARRAY element type is not VT_VARIANT", + )), + }) + .collect() + } + + #[napi] + pub fn release(&mut self) { + self.value = None; + } +} + +#[napi] +pub struct DynComPropVariant { + value: Option, +} + +impl DynComPropVariant { + fn new(value: dynwinrt::com::PropVariantValue) -> Self { + Self { value: Some(value) } + } + + fn value(&self) -> napi::Result<&dynwinrt::com::PropVariantValue> { + self + .value + .as_ref() + .ok_or_else(|| napi::Error::from_reason("PROPVARIANT has been released")) + } +} + +#[napi] +impl DynComPropVariant { + #[napi] + pub fn empty() -> Self { + Self::new(dynwinrt::com::PropVariantValue::empty()) + } + + #[napi(js_name = "null")] + pub fn null_value() -> Self { + Self::new(dynwinrt::com::PropVariantValue::null()) + } + + #[napi] + pub fn i8(value: f64) -> napi::Result { + checked_signed_number(value, i8::MIN as i64, i8::MAX as i64, "PROPVARIANT VT_I1") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_i8(value as i8))) + } + + #[napi] + pub fn u8(value: f64) -> napi::Result { + checked_unsigned_number(value, u8::MAX as u64, "PROPVARIANT VT_UI1") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_u8(value as u8))) + } + + #[napi] + pub fn i16(value: f64) -> napi::Result { + checked_signed_number(value, i16::MIN as i64, i16::MAX as i64, "PROPVARIANT VT_I2") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_i16(value as i16))) + } + + #[napi] + pub fn u16(value: f64) -> napi::Result { + checked_unsigned_number(value, u16::MAX as u64, "PROPVARIANT VT_UI2") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_u16(value as u16))) + } + + #[napi] + pub fn i32(value: f64) -> napi::Result { + checked_signed_number(value, i32::MIN as i64, i32::MAX as i64, "PROPVARIANT VT_I4") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_i32(value as i32))) + } + + #[napi] + pub fn u32(value: f64) -> napi::Result { + checked_unsigned_number(value, u32::MAX as u64, "PROPVARIANT VT_UI4") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_u32(value as u32))) + } + + #[napi] + pub fn int(value: f64) -> napi::Result { + checked_signed_number( + value, + i32::MIN as i64, + i32::MAX as i64, + "PROPVARIANT VT_INT", + ) + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_int(value as i32))) + } + + #[napi] + pub fn uint(value: f64) -> napi::Result { + checked_unsigned_number(value, u32::MAX as u64, "PROPVARIANT VT_UINT") + .map(|value| Self::new(dynwinrt::com::PropVariantValue::from_uint(value as u32))) + } + + #[napi] + pub fn i64(value: BigInt) -> napi::Result { + bigint_i64(value, "PROPVARIANT VT_I8") + .map(dynwinrt::com::PropVariantValue::from_i64) + .map(Self::new) + } + + #[napi] + pub fn u64(value: BigInt) -> napi::Result { + bigint_u64(value, "PROPVARIANT VT_UI8") + .map(dynwinrt::com::PropVariantValue::from_u64) + .map(Self::new) + } + + #[napi] + pub fn f32(value: f64) -> Self { + Self::new(dynwinrt::com::PropVariantValue::from_f32(value as f32)) + } + + #[napi] + pub fn f64(value: f64) -> Self { + Self::new(dynwinrt::com::PropVariantValue::from_f64(value)) + } + + #[napi] + pub fn bool(value: bool) -> Self { + Self::new(dynwinrt::com::PropVariantValue::from_bool(value)) + } + + #[napi] + pub fn string(value: String) -> napi::Result { + dynwinrt::com::PropVariantValue::from_string(&value) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn guid(value: &WinGUID) -> napi::Result { + dynwinrt::com::PropVariantValue::from_guid(value.0) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn filetime(value: BigInt) -> napi::Result { + bigint_u64(value, "PROPVARIANT VT_FILETIME") + .map(dynwinrt::com::PropVariantValue::from_filetime) + .map(Self::new) + } + + #[napi] + pub fn blob(value: Buffer) -> napi::Result { + dynwinrt::com::PropVariantValue::from_blob(&value) + .map(Self::new) + .map_err(com_error) + } + + #[napi] + pub fn i8_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number( + value, + i8::MIN as i64, + i8::MAX as i64, + "PROPVARIANT VT_VECTOR|VT_I1", + ) + .map(|value| value as i8) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::I8(values)) + } + + #[napi] + pub fn u8_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u8::MAX as u64, "PROPVARIANT VT_VECTOR|VT_UI1") + .map(|value| value as u8) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::U8(values)) + } + + #[napi] + pub fn i16_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number( + value, + i16::MIN as i64, + i16::MAX as i64, + "PROPVARIANT VT_VECTOR|VT_I2", + ) + .map(|value| value as i16) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::I16(values)) + } + + #[napi] + pub fn u16_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u16::MAX as u64, "PROPVARIANT VT_VECTOR|VT_UI2") + .map(|value| value as u16) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::U16(values)) + } + + #[napi] + pub fn i32_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_signed_number( + value, + i32::MIN as i64, + i32::MAX as i64, + "PROPVARIANT VT_VECTOR|VT_I4", + ) + .map(|value| value as i32) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::I32(values)) + } + + #[napi] + pub fn u32_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + checked_unsigned_number(value, u32::MAX as u64, "PROPVARIANT VT_VECTOR|VT_UI4") + .map(|value| value as u32) + }) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::U32(values)) + } + + #[napi] + pub fn i64_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| bigint_i64(value, "PROPVARIANT VT_VECTOR|VT_I8")) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::I64(values)) + } + + #[napi] + pub fn u64_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| bigint_u64(value, "PROPVARIANT VT_VECTOR|VT_UI8")) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::U64(values)) + } + + #[napi] + pub fn f32_vector(values: Vec) -> napi::Result { + propvariant_vector(dynwinrt::com::PropVariantVector::F32( + values.into_iter().map(|value| value as f32).collect(), + )) + } + + #[napi] + pub fn f64_vector(values: Vec) -> napi::Result { + propvariant_vector(dynwinrt::com::PropVariantVector::F64(values)) + } + + #[napi] + pub fn bool_vector(values: Vec) -> napi::Result { + propvariant_vector(dynwinrt::com::PropVariantVector::Bool(values)) + } + + #[napi] + pub fn string_vector(values: Vec) -> napi::Result { + propvariant_vector(dynwinrt::com::PropVariantVector::String(values)) + } + + #[napi] + pub fn guid_vector(values: Vec<&WinGUID>) -> napi::Result { + propvariant_vector(dynwinrt::com::PropVariantVector::Guid( + values.into_iter().map(|value| value.0).collect(), + )) + } + + #[napi] + pub fn filetime_vector(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| bigint_u64(value, "PROPVARIANT VT_VECTOR|VT_FILETIME")) + .collect::>>()?; + propvariant_vector(dynwinrt::com::PropVariantVector::FileTime(values)) + } + + #[napi(getter)] + pub fn vartype(&self) -> napi::Result { + Ok(u32::from(self.value()?.vartype())) + } + + #[napi(getter)] + pub fn kind(&self) -> napi::Result { + Ok(propvariant_kind(self.value()?.propvariant_type().map_err(com_error)?).into()) + } + + #[napi] + pub fn to_number(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::I8(value) => Ok(f64::from(value)), + dynwinrt::com::PropVariantData::U8(value) => Ok(f64::from(value)), + dynwinrt::com::PropVariantData::I16(value) => Ok(f64::from(value)), + dynwinrt::com::PropVariantData::U16(value) => Ok(f64::from(value)), + dynwinrt::com::PropVariantData::I32(value) | dynwinrt::com::PropVariantData::Int(value) => { + Ok(f64::from(value)) + } + dynwinrt::com::PropVariantData::U32(value) | dynwinrt::com::PropVariantData::UInt(value) => { + Ok(f64::from(value)) + } + dynwinrt::com::PropVariantData::F32(value) => Ok(f64::from(value)), + dynwinrt::com::PropVariantData::F64(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a number-sized scalar", + )), + } + } + + #[napi] + pub fn to_bigint(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::I64(value) => Ok(BigInt::from(value)), + dynwinrt::com::PropVariantData::U64(value) + | dynwinrt::com::PropVariantData::FileTime(value) => Ok(BigInt::from(value)), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a 64-bit integer or FILETIME", + )), + } + } + + #[napi] + pub fn to_bool(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Bool(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain VT_BOOL", + )), + } + } + + #[napi(js_name = "toStringValue")] + pub fn to_string_value(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::String(value) => Ok(value), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain VT_LPWSTR", + )), + } + } + + #[napi] + pub fn to_guid_string(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Guid(value) => Ok(format!("{value:?}")), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain VT_CLSID", + )), + } + } + + #[napi] + pub fn to_blob(&self) -> napi::Result { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Blob(value) => Ok(Buffer::from(value)), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain VT_BLOB", + )), + } + } + + #[napi] + pub fn to_numbers(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Vector(value) => propvariant_vector_numbers(value), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a numeric vector", + )), + } + } + + #[napi] + pub fn to_bigints(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::I64(values)) => { + Ok(values.into_iter().map(BigInt::from).collect()) + } + dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::U64(values)) + | dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::FileTime( + values, + )) => Ok(values.into_iter().map(BigInt::from).collect()), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a 64-bit integer or FILETIME vector", + )), + } + } + + #[napi] + pub fn to_bools(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::Bool(values)) => { + Ok(values) + } + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a VT_BOOL vector", + )), + } + } + + #[napi] + pub fn to_strings(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::String(values)) => { + Ok(values) + } + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a VT_LPWSTR vector", + )), + } + } + + #[napi] + pub fn to_guid_strings(&self) -> napi::Result> { + match self.value()?.data().map_err(com_error)? { + dynwinrt::com::PropVariantData::Vector(dynwinrt::com::PropVariantVector::Guid(values)) => Ok( + values + .into_iter() + .map(|value| format!("{value:?}")) + .collect(), + ), + _ => Err(napi::Error::from_reason( + "PROPVARIANT does not contain a VT_CLSID vector", + )), + } + } + + #[napi] + pub fn release(&mut self) { + self.value = None; + } +} + +fn propvariant_vector(value: dynwinrt::com::PropVariantVector) -> napi::Result { + dynwinrt::com::PropVariantValue::from_vector(value) + .map(DynComPropVariant::new) + .map_err(com_error) +} + +fn propvariant_vector_numbers(value: dynwinrt::com::PropVariantVector) -> napi::Result> { + Ok(match value { + dynwinrt::com::PropVariantVector::I8(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::U8(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::I16(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::U16(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::I32(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::U32(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::F32(values) => values.into_iter().map(f64::from).collect(), + dynwinrt::com::PropVariantVector::F64(values) => values, + _ => { + return Err(napi::Error::from_reason( + "PROPVARIANT vector element type is not number-sized", + )); + } + }) +} + +fn propvariant_kind(typ: dynwinrt::com::PropVariantType) -> &'static str { + match typ { + dynwinrt::com::PropVariantType::Empty => "empty", + dynwinrt::com::PropVariantType::Null => "null", + dynwinrt::com::PropVariantType::I8 => "i8", + dynwinrt::com::PropVariantType::U8 => "u8", + dynwinrt::com::PropVariantType::I16 => "i16", + dynwinrt::com::PropVariantType::U16 => "u16", + dynwinrt::com::PropVariantType::I32 => "i32", + dynwinrt::com::PropVariantType::U32 => "u32", + dynwinrt::com::PropVariantType::I64 => "i64", + dynwinrt::com::PropVariantType::U64 => "u64", + dynwinrt::com::PropVariantType::Int => "int", + dynwinrt::com::PropVariantType::UInt => "uint", + dynwinrt::com::PropVariantType::F32 => "f32", + dynwinrt::com::PropVariantType::F64 => "f64", + dynwinrt::com::PropVariantType::Bool => "bool", + dynwinrt::com::PropVariantType::String => "string", + dynwinrt::com::PropVariantType::Guid => "guid", + dynwinrt::com::PropVariantType::FileTime => "filetime", + dynwinrt::com::PropVariantType::Blob => "blob", + dynwinrt::com::PropVariantType::Vector(_) => "vector", + } +} + +#[napi] +pub fn initialize_com(apartment_type: Option) -> napi::Result<()> { + let apartment_type = match apartment_type.unwrap_or(1) { + 0 => dynwinrt::com::ApartmentType::SingleThreaded, + _ => dynwinrt::com::ApartmentType::MultiThreaded, + }; + dynwinrt::com::initialize_apartment(apartment_type) + .map_err(|error| napi::Error::from_reason(error.message())) +} + +#[napi] +impl DynComNativeStruct { + #[napi(getter)] + pub fn length(&self) -> u32 { + self.bytes.len() as u32 + } + + #[napi(getter)] + pub fn bytes(&self) -> Buffer { + Buffer::from(self.bytes.clone()) + } +} + +#[napi] +impl DynCom { + #[napi] + pub fn initialize(apartment_type: Option) -> napi::Result<()> { + initialize_com(apartment_type) + } + + #[napi(js_name = "registerIUnknownInterface")] + pub fn register_iunknown_interface(name: String, iid: &WinGUID) -> DynComInterface { + DynComInterface(dynwinrt::com::register_interface( + &TABLE, + &name, + iid.0, + dynwinrt::com::InterfaceBase::IUnknown, + )) + } + + #[napi(js_name = "registerIInspectableInterface")] + pub fn register_iinspectable_interface(name: String, iid: &WinGUID) -> DynComInterface { + DynComInterface(dynwinrt::com::register_interface( + &TABLE, + &name, + iid.0, + dynwinrt::com::InterfaceBase::IInspectable, + )) + } + + #[napi] + pub fn bool_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.bool_type())) + } + + #[napi] + pub fn i8_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.i8_type())) + } + + #[napi] + pub fn u8_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.u8_type())) + } + + #[napi] + pub fn i16_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.i16_type())) + } + + #[napi] + pub fn u16_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.u16_type())) + } + + #[napi] + pub fn i32_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.i32_type())) + } + + #[napi] + pub fn u32_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.u32_type())) + } + + #[napi] + pub fn i64_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.i64_type())) + } + + #[napi] + pub fn u64_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.u64_type())) + } + + #[napi] + pub fn isize_type() -> DynComType { + #[cfg(target_pointer_width = "64")] + { + DynComType(dynwinrt::com::Type::winrt(TABLE.i64_type())) + } + #[cfg(target_pointer_width = "32")] + { + DynComType(dynwinrt::com::Type::winrt(TABLE.i32_type())) + } + } + + #[napi] + pub fn usize_type() -> DynComType { + #[cfg(target_pointer_width = "64")] + { + DynComType(dynwinrt::com::Type::winrt(TABLE.u64_type())) + } + #[cfg(target_pointer_width = "32")] + { + DynComType(dynwinrt::com::Type::winrt(TABLE.u32_type())) + } + } + + #[napi] + pub fn f32_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.f32_type())) + } + + #[napi] + pub fn f64_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.f64_type())) + } + + #[napi] + pub fn char16_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.char16_type())) + } + + #[napi] + pub fn guid_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.guid_type())) + } + + #[napi] + pub fn hstring_type() -> DynComType { + DynComType(dynwinrt::com::Type::winrt(TABLE.hstring())) + } + + #[napi] + pub fn hstring(value: String) -> DynWinRTValue { + DynWinRTValue::new(dynwinrt::WinRTValue::HString(windows::core::HSTRING::from( + value, + ))) + } + + #[napi] + pub fn pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::pointer()) + } + + #[napi] + pub fn borrowed_handle_output_type() -> DynComType { + DynComType(dynwinrt::com::Type::borrowed_handle_output()) + } + + #[napi] + pub fn owned_com_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::owned_com_pointer()) + } + + #[napi] + pub fn co_task_mem_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::co_task_mem_pointer()) + } + + #[napi] + pub fn co_task_mem_wide_string_type() -> DynComType { + DynComType(dynwinrt::com::Type::co_task_mem_wide_string()) + } + + #[napi] + pub fn bstr_pointer_type() -> DynComType { + DynComType(dynwinrt::com::Type::bstr_pointer()) + } + + #[napi] + pub fn bstr_type() -> DynComType { + DynComType(dynwinrt::com::Type::bstr()) + } + + #[napi] + pub fn nullable_bstr_type() -> DynComType { + DynComType(dynwinrt::com::Type::nullable_bstr()) + } + + #[napi] + pub fn bstr(value: String) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Bstr(dynwinrt::com::BstrValue::new(value)), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn null_bstr() -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Bstr(dynwinrt::com::BstrValue::null()), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn native_struct_type(descriptor: String) -> napi::Result { + native_struct_layout(&descriptor) + .map(dynwinrt::com::Type::native_struct) + .map(DynComType) + } + + #[napi] + pub fn native_struct_pointer_type( + descriptor: String, + nullable: Option, + ) -> napi::Result { + native_struct_layout(&descriptor) + .map(|layout| { + if nullable.unwrap_or(false) { + dynwinrt::com::Type::nullable_native_struct_pointer(layout) + } else { + dynwinrt::com::Type::native_struct_pointer(layout) + } + }) + .map(DynComType) + } + + #[napi] + pub fn native_union_pointer_type(descriptor: String) -> napi::Result { + native_union_layout(&descriptor) + .map(dynwinrt::com::Type::native_union_pointer) + .map(DynComType) + } + + #[napi] + pub fn variant_type() -> DynComType { + DynComType(dynwinrt::com::Type::variant()) + } + + #[napi] + pub fn variant_by_value_type() -> DynComType { + DynComType(dynwinrt::com::Type::variant_by_value()) + } + + #[napi] + pub fn safe_array_type( + element_type: String, + interface_iid: Option<&WinGUID>, + nullable: Option, + ) -> napi::Result { + let element_type = safe_array_element_type_from_name(&element_type)?; + match (interface_iid, nullable.unwrap_or(false)) { + (Some(iid), false) if element_type == dynwinrt::com::SafeArrayElementType::Unknown => Ok( + DynComType(dynwinrt::com::Type::typed_interface_safe_array(iid.0)), + ), + (Some(iid), true) if element_type == dynwinrt::com::SafeArrayElementType::Unknown => { + Ok(DynComType( + dynwinrt::com::Type::nullable_typed_interface_safe_array(iid.0), + )) + } + (Some(_), _) => Err(napi::Error::from_reason( + "Exact SAFEARRAY interface IID requires VT_UNKNOWN elements", + )), + (None, false) => Ok(DynComType(dynwinrt::com::Type::typed_safe_array( + element_type, + ))), + (None, true) => Ok(DynComType(dynwinrt::com::Type::nullable_typed_safe_array( + element_type, + ))), + } + } + + #[napi] + pub fn prop_variant_type() -> DynComType { + DynComType(dynwinrt::com::Type::prop_variant()) + } + + #[napi] + pub fn dispatch_params_type() -> DynComType { + DynComType(dynwinrt::com::Type::dispatch_params()) + } + + #[napi] + pub fn excep_info_type() -> DynComType { + DynComType(dynwinrt::com::Type::excep_info()) + } + + #[napi] pub fn interface_type(iid: &WinGUID) -> DynComType { DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) } #[napi] - pub fn bool_value(value: bool) -> DynWinRTValue { - DynWinRTValue::bool_value(value) + pub fn bool_value(value: bool) -> DynWinRTValue { + DynWinRTValue::bool_value(value) + } + + #[napi] + pub fn i8_value(value: i32) -> DynWinRTValue { + DynWinRTValue::i8_value(value) + } + + #[napi] + pub fn u8_value(value: u32) -> DynWinRTValue { + DynWinRTValue::u8_value(value) + } + + #[napi] + pub fn i16(value: i32) -> DynWinRTValue { + DynWinRTValue::i16(value) + } + + #[napi] + pub fn u16(value: u32) -> DynWinRTValue { + DynWinRTValue::u16(value) + } + + #[napi] + pub fn i32(value: i32) -> DynWinRTValue { + DynWinRTValue::i32(value) + } + + #[napi] + pub fn u32(value: u32) -> DynWinRTValue { + DynWinRTValue::u32(value) + } + + #[napi] + pub fn i64(value: BigInt) -> napi::Result { + let (value, lossless) = value.get_i64(); + if !lossless { + return Err(napi::Error::from_reason( + "DynCom.i64(): value must fit in a signed 64-bit integer", + )); + } + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I64(value))) + } + + #[napi] + pub fn u64(value: BigInt) -> napi::Result { + let (negative, value, lossless) = value.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "DynCom.u64(): value must fit in an unsigned 64-bit integer", + )); + } + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U64(value))) + } + + #[napi] + pub fn isize(value: BigInt) -> napi::Result { + let (value, lossless) = value.get_i64(); + if !lossless { + return Err(napi::Error::from_reason( + "DynCom.isize(): value must fit in a pointer-sized signed integer", + )); + } + #[cfg(target_pointer_width = "64")] + { + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I64(value))) + } + #[cfg(target_pointer_width = "32")] + { + let value = i32::try_from(value).map_err(|_| { + napi::Error::from_reason("DynCom.isize(): value must fit in a pointer-sized signed integer") + })?; + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I32(value))) + } + } + + #[napi] + pub fn usize(value: BigInt) -> napi::Result { + let (negative, value, lossless) = value.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "DynCom.usize(): value must fit in a pointer-sized unsigned integer", + )); + } + #[cfg(target_pointer_width = "64")] + { + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U64(value))) + } + #[cfg(target_pointer_width = "32")] + { + let value = u32::try_from(value).map_err(|_| { + napi::Error::from_reason( + "DynCom.usize(): value must fit in a pointer-sized unsigned integer", + ) + })?; + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U32(value))) + } + } + + #[napi] + pub fn f32(value: f64) -> DynWinRTValue { + DynWinRTValue::f32(value) + } + + #[napi] + pub fn f64(value: f64) -> DynWinRTValue { + DynWinRTValue::f64(value) + } + + #[napi] + pub fn char16(value: u32) -> DynWinRTValue { + DynWinRTValue::new(dynwinrt::WinRTValue::U16(value as u16)) + } + + #[napi] + pub fn guid(value: &WinGUID) -> DynWinRTValue { + DynWinRTValue::guid(value) + } + + #[napi] + pub fn co_create_instance(clsid: String, iid: &WinGUID) -> napi::Result { + self::co_create_instance(clsid, iid) + } + + #[napi] + pub fn try_cast(value: &DynWinRTValue, iid: &WinGUID) -> napi::Result> { + self::try_cast(value, iid) + } + + #[napi] + pub fn pointer( + #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array | null | undefined")] + value: Unknown, + ) -> napi::Result { + self::pointer(value) + } + + #[napi] + pub fn null_buffer() -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(dynwinrt::com::ComBufferValue::null()), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn null_native_struct_pointer() -> DynWinRTValue { + DynWinRTValue::new(dynwinrt::WinRTValue::Null) + } + + #[napi] + pub fn is_null_native_struct_pointer(value: &DynWinRTValue) -> bool { + value.3.is_none() && value.0.is_null_object() + } + + #[napi] + pub fn null_com_value() -> DynWinRTValue { + DynWinRTValue::new(dynwinrt::WinRTValue::Null) + } + + #[napi] + pub fn buffer( + #[napi(ts_arg_type = "Buffer | ArrayBufferView")] value: Unknown, + ) -> napi::Result { + self::com_buffer(value) + } + + #[napi] + pub fn wide_string_array(values: Vec) -> napi::Result { + dynwinrt::com::ComBufferValue::string_array(values, dynwinrt::com::StringEncoding::Utf16) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn ansi_string_array(values: Vec) -> napi::Result { + dynwinrt::com::ComBufferValue::string_array(values, dynwinrt::com::StringEncoding::Ansi) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn interface_array( + iid: &WinGUID, + values: Vec<&DynWinRTValue>, + ) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + value + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("COM interface arrays require managed objects")) + }) + .collect::>>()?; + dynwinrt::com::ComBufferValue::interface_array(iid.0, values) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn bstr_array(values: Vec) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(dynwinrt::com::ComBufferValue::bstr_array(values)), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn variant_array(values: Vec<&DynComVariant>) -> napi::Result { + let values = values + .into_iter() + .map(|value| value.value().cloned()) + .collect::>>()?; + dynwinrt::com::ComBufferValue::variant_array(values) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn caller_output_array( + element_type: &DynComType, + count: BigInt, + ) -> napi::Result { + let (negative, count, lossless) = count.get_u64(); + if negative || !lossless || count as usize as u64 != count { + return Err(napi::Error::from_reason( + "callerOutputArray(): count must fit in an unsigned pointer-sized integer", + )); + } + dynwinrt::com::ComBufferValue::caller_output(&element_type.0, count as usize) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn enumerator_output_array( + element_type: &DynComType, + count: BigInt, + ) -> napi::Result { + let (negative, count, lossless) = count.get_u64(); + if negative || !lossless || count as usize as u64 != count { + return Err(napi::Error::from_reason( + "enumeratorOutputArray(): count must fit in an unsigned pointer-sized integer", + )); + } + dynwinrt::com::ComBufferValue::enumerator_output(&element_type.0, count as usize) + .map(|value| { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(value), + dynwinrt::com::PointerOutputKind::None, + ) + }) + .map_err(com_error) + } + + #[napi] + pub fn take_buffer(value: &mut DynWinRTValue) -> napi::Result { + let buffer = value + .4 + .take() + .ok_or_else(|| napi::Error::from_reason("Value is not an owned COM buffer result"))?; + let bytes = buffer + .snapshot_bytes() + .map_err(com_error)? + .ok_or_else(|| napi::Error::from_reason("Borrowed COM buffers cannot be consumed"))?; + Ok(Buffer::from(bytes)) + } + + #[napi] + pub fn take_i8_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 1)? + .into_iter() + .map(|value| value as i8) + .collect(), + ) + } + + #[napi] + pub fn take_u8_array(value: &mut DynWinRTValue) -> napi::Result> { + take_array_bytes(value, 1) + } + + #[napi] + pub fn take_i16_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 2)? + .chunks_exact(2) + .map(|bytes| i16::from_ne_bytes(bytes.try_into().unwrap())) + .collect(), + ) + } + + #[napi] + pub fn take_u16_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 2)? + .chunks_exact(2) + .map(|bytes| u16::from_ne_bytes(bytes.try_into().unwrap())) + .collect(), + ) + } + + #[napi] + pub fn take_i32_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 4)? + .chunks_exact(4) + .map(|bytes| i32::from_ne_bytes(bytes.try_into().unwrap())) + .collect(), + ) + } + + #[napi] + pub fn take_u32_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 4)? + .chunks_exact(4) + .map(|bytes| u32::from_ne_bytes(bytes.try_into().unwrap())) + .collect(), + ) + } + + #[napi] + pub fn take_i64_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 8)? + .chunks_exact(8) + .map(|bytes| BigInt::from(i64::from_ne_bytes(bytes.try_into().unwrap()))) + .collect(), + ) + } + + #[napi] + pub fn take_u64_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 8)? + .chunks_exact(8) + .map(|bytes| BigInt::from(u64::from_ne_bytes(bytes.try_into().unwrap()))) + .collect(), + ) + } + + #[napi] + pub fn take_f32_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 4)? + .chunks_exact(4) + .map(|bytes| f32::from_ne_bytes(bytes.try_into().unwrap()) as f64) + .collect(), + ) + } + + #[napi] + pub fn take_f64_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 8)? + .chunks_exact(8) + .map(|bytes| f64::from_ne_bytes(bytes.try_into().unwrap())) + .collect(), + ) + } + + #[napi] + pub fn take_bool_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 1)? + .into_iter() + .map(|value| value != 0) + .collect(), + ) + } + + #[napi] + pub fn take_guid_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, std::mem::size_of::())? + .chunks_exact(std::mem::size_of::()) + .map(|bytes| { + let guid = + unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast::()) }; + format!("{guid:?}") + }) + .collect(), + ) + } + + #[napi] + pub fn take_native_struct_array( + value: &mut DynWinRTValue, + descriptor: String, + ) -> napi::Result> { + let layout = native_struct_layout(&descriptor)?; + Ok( + take_array_bytes(value, layout.size())? + .chunks_exact(layout.size()) + .map(|bytes| DynComNativeStruct { + descriptor: descriptor.clone(), + bytes: bytes.to_vec(), + }) + .collect(), + ) + } + + #[napi] + pub fn take_com_array(value: &mut DynWinRTValue) -> napi::Result> { + value + .4 + .take() + .ok_or_else(|| napi::Error::from_reason("Value is not a managed COM array result"))? + .into_com_values() + .map(|values| values.into_iter().map(DynWinRTValue::new).collect()) + .map_err(com_error) + } + + #[napi] + pub fn take_bstr_array(value: &mut DynWinRTValue) -> napi::Result> { + value + .4 + .take() + .ok_or_else(|| napi::Error::from_reason("Value is not an owned BSTR array result"))? + .into_strings() + .map_err(com_error) + } + + #[napi] + pub fn take_co_task_mem_wide_string_array( + value: &mut DynWinRTValue, + ) -> napi::Result> { + Self::take_bstr_array(value) + } + + #[napi] + pub fn take_variant_array(value: &mut DynWinRTValue) -> napi::Result> { + value + .4 + .take() + .ok_or_else(|| napi::Error::from_reason("Value is not an owned VARIANT array result"))? + .into_variants() + .map(|values| values.into_iter().map(DynComVariant::new).collect()) + .map_err(com_error) + } + + #[napi] + pub fn take_win32_bool_array(value: &mut DynWinRTValue) -> napi::Result> { + Ok( + take_array_bytes(value, 4)? + .chunks_exact(4) + .map(|bytes| i32::from_ne_bytes(bytes.try_into().unwrap()) != 0) + .collect(), + ) + } + + #[napi] + pub fn take_isize_array(value: &mut DynWinRTValue) -> napi::Result> { + #[cfg(target_pointer_width = "64")] + { + Self::take_i64_array(value) + } + #[cfg(target_pointer_width = "32")] + { + Ok( + Self::take_i32_array(value)? + .into_iter() + .map(|value| BigInt::from(i64::from(value))) + .collect(), + ) + } + } + + #[napi] + pub fn take_usize_array(value: &mut DynWinRTValue) -> napi::Result> { + #[cfg(target_pointer_width = "64")] + { + Self::take_u64_array(value) + } + #[cfg(target_pointer_width = "32")] + { + Ok( + Self::take_u32_array(value)? + .into_iter() + .map(|value| BigInt::from(u64::from(value))) + .collect(), + ) + } + } + + #[napi] + pub fn buffer_count(value: &DynWinRTValue) -> napi::Result { + value + .4 + .as_ref() + .map(|buffer| BigInt::from(buffer.count() as u64)) + .ok_or_else(|| napi::Error::from_reason("Value is not a COM buffer result")) + } + + #[napi] + pub fn buffer_element_count( + value: &DynWinRTValue, + element_type: &DynComType, + ) -> napi::Result { + value + .4 + .as_ref() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM buffer")) + .and_then(|buffer| { + buffer + .element_count(&element_type.0) + .map(|count| BigInt::from(count as u64)) + .map_err(com_error) + }) } #[napi] - pub fn i8_value(value: i32) -> DynWinRTValue { - DynWinRTValue::i8_value(value) + pub fn buffer_allocation_length(value: BigInt) -> napi::Result { + let (negative, value, lossless) = value.get_u64(); + if negative || !lossless || value > i32::MAX as u64 { + return Err(napi::Error::from_reason( + "COM buffer size exceeds the supported projected Buffer size", + )); + } + Ok(value as u32) } #[napi] - pub fn u8_value(value: u32) -> DynWinRTValue { - DynWinRTValue::u8_value(value) + pub fn native_struct( + descriptor: String, + value: &DynComNativeStruct, + ) -> napi::Result { + let layout = native_struct_layout(&descriptor)?; + if value.descriptor != descriptor { + return Err(napi::Error::from_reason(format!( + "Native struct type mismatch: expected `{}`, received a differently branded native struct", + layout.name() + ))); + } + let value = dynwinrt::com::NativeStructValue::new(layout, value.bytes.clone()) + .map_err(|error| napi::Error::from_reason(error.message()))?; + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::NativeStruct(value), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn i16(value: i32) -> DynWinRTValue { - DynWinRTValue::i16(value) + pub fn create_native_struct( + descriptor: String, + bytes: Option, + ) -> napi::Result { + let layout = native_struct_layout(&descriptor)?; + let bytes = bytes + .map(|bytes| bytes.to_vec()) + .unwrap_or_else(|| vec![0; layout.size()]); + if bytes.len() != layout.size() { + return Err(napi::Error::from_reason(format!( + "Native struct `{}` requires exactly {} bytes, received {}", + layout.name(), + layout.size(), + bytes.len() + ))); + } + Ok(DynComNativeStruct { descriptor, bytes }) } #[napi] - pub fn u16(value: u32) -> DynWinRTValue { - DynWinRTValue::u16(value) + pub fn create_native_struct_array( + descriptor: String, + bytes: Buffer, + ) -> napi::Result { + let layout = native_struct_layout(&descriptor)?; + dynwinrt::com::ComBufferValue::native_struct_input(bytes.to_vec(), &layout) + .map_err(com_error)?; + Ok(DynComNativeStructArray { + descriptor, + bytes: bytes.to_vec(), + }) } #[napi] - pub fn i32(value: i32) -> DynWinRTValue { - DynWinRTValue::i32(value) + pub fn native_struct_buffer( + descriptor: String, + value: &DynComNativeStructArray, + ) -> napi::Result { + let layout = native_struct_layout(&descriptor)?; + if value.descriptor != descriptor { + return Err(napi::Error::from_reason(format!( + "Native struct array type mismatch: expected `{}`", + layout.name() + ))); + } + let buffer = dynwinrt::com::ComBufferValue::native_struct_input(value.bytes.clone(), &layout) + .map_err(com_error)?; + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::Buffer(buffer), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn u32(value: u32) -> DynWinRTValue { - DynWinRTValue::u32(value) + pub fn native_struct_bytes( + descriptor: String, + value: &DynWinRTValue, + ) -> napi::Result { + let expected = native_struct_layout(&descriptor)?; + let value = value + .3 + .as_ref() + .ok_or_else(|| napi::Error::from_reason("Value is not a native COM struct"))?; + if value.layout() != &expected { + return Err(napi::Error::from_reason(format!( + "Native struct type mismatch: expected `{}`, received `{}`", + expected.name(), + value.layout().name() + ))); + } + Ok(DynComNativeStruct { + descriptor, + bytes: value.bytes().to_vec(), + }) } #[napi] - pub fn i64(value: BigInt) -> napi::Result { - let (value, lossless) = value.get_i64(); - if !lossless { - return Err(napi::Error::from_reason( - "DynCom.i64(): value must fit in a signed 64-bit integer", - )); + pub fn create_native_union( + descriptor: String, + active_field: String, + bytes: Option, + ) -> napi::Result { + let layout = native_union_layout(&descriptor)?; + let value = match bytes { + Some(bytes) => dynwinrt::com::NativeUnionValue::new(layout, active_field, bytes.to_vec()), + None => dynwinrt::com::NativeUnionValue::zeroed(layout, active_field), } - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I64(value))) + .map_err(com_error)?; + Ok(DynComNativeUnion { descriptor, value }) } #[napi] - pub fn u64(value: BigInt) -> napi::Result { - let (negative, value, lossless) = value.get_u64(); - if negative || !lossless { - return Err(napi::Error::from_reason( - "DynCom.u64(): value must fit in an unsigned 64-bit integer", - )); + pub fn native_union( + descriptor: String, + value: &DynComNativeUnion, + ) -> napi::Result { + let layout = native_union_layout(&descriptor)?; + if value.descriptor != descriptor || value.value.layout() != &layout { + return Err(napi::Error::from_reason(format!( + "Native union type mismatch: expected `{}`", + layout.name() + ))); } - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U64(value))) + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::NativeUnion(value.value.clone()), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn isize(value: BigInt) -> napi::Result { - let (value, lossless) = value.get_i64(); - if !lossless { - return Err(napi::Error::from_reason( - "DynCom.isize(): value must fit in a pointer-sized signed integer", - )); - } - #[cfg(target_pointer_width = "64")] - { - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I64(value))) - } - #[cfg(target_pointer_width = "32")] - { - let value = i32::try_from(value).map_err(|_| { - napi::Error::from_reason("DynCom.isize(): value must fit in a pointer-sized signed integer") - })?; - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::I32(value))) - } + pub fn variant(value: &DynComVariant) -> napi::Result { + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::Variant(value.value()?.clone()), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn usize(value: BigInt) -> napi::Result { - let (negative, value, lossless) = value.get_u64(); - if negative || !lossless { - return Err(napi::Error::from_reason( - "DynCom.usize(): value must fit in a pointer-sized unsigned integer", - )); - } - #[cfg(target_pointer_width = "64")] - { - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U64(value))) - } - #[cfg(target_pointer_width = "32")] - { - let value = u32::try_from(value).map_err(|_| { - napi::Error::from_reason( - "DynCom.usize(): value must fit in a pointer-sized unsigned integer", - ) - })?; - Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U32(value))) - } + pub fn safe_array(value: &DynComSafeArray) -> napi::Result { + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::SafeArray(value.value()?.clone()), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn f32(value: f64) -> DynWinRTValue { - DynWinRTValue::f32(value) + pub fn prop_variant(value: &DynComPropVariant) -> napi::Result { + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::PropVariant(value.value()?.clone()), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn f64(value: f64) -> DynWinRTValue { - DynWinRTValue::f64(value) + pub fn dispatch_params(value: &DynComDispatchParams) -> napi::Result { + Ok(DynWinRTValue::from_com_value( + dynwinrt::com::Value::DispatchParams(value.value()?.clone()), + dynwinrt::com::PointerOutputKind::None, + )) } #[napi] - pub fn char16(value: u32) -> DynWinRTValue { - DynWinRTValue::new(dynwinrt::WinRTValue::U16(value as u16)) + pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM VARIANT"))? + .take_variant()?; + value.5 = None; + Ok(DynComVariant::new(result)) } #[napi] - pub fn guid(value: &WinGUID) -> DynWinRTValue { - DynWinRTValue::guid(value) + pub fn take_safe_array(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM SAFEARRAY"))? + .take_safe_array()?; + value.5 = None; + Ok(DynComSafeArray::new(result)) } #[napi] - pub fn co_create_instance(clsid: String, iid: &WinGUID) -> napi::Result { - self::co_create_instance(clsid, iid) + pub fn take_nullable_safe_array( + value: &mut DynWinRTValue, + ) -> napi::Result> { + if value.5.is_none() && value.0.is_null_object() { + return Ok(None); + } + Self::take_safe_array(value).map(Some) } #[napi] - pub fn try_cast(value: &DynWinRTValue, iid: &WinGUID) -> napi::Result> { - self::try_cast(value, iid) + pub fn take_prop_variant(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM PROPVARIANT"))? + .take_prop_variant()?; + value.5 = None; + Ok(DynComPropVariant::new(result)) } #[napi] - pub fn pointer( - #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array | null | undefined")] - value: Unknown, - ) -> napi::Result { - self::pointer(value) + pub fn take_excep_info(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not COM EXCEPINFO"))? + .take_excep_info()?; + value.5 = None; + Ok(DynComExcepInfo::new(result)) } #[napi] @@ -1174,6 +4495,359 @@ impl DynCom { #[cfg(test)] mod tests { use super::*; + use std::ffi::c_void; + + const TEST_POD_DESCRIPTOR: &str = r#"{"name":"Test.Pod","x86":{"size":8,"alignment":4,"fields":[{"name":"first","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"second","offset":4,"count":2,"type":{"kind":"u16"}}]},"x64":{"size":8,"alignment":4,"fields":[{"name":"first","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"second","offset":4,"count":2,"type":{"kind":"u16"}}]},"arm64":{"size":8,"alignment":4,"fields":[{"name":"first","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"second","offset":4,"count":2,"type":{"kind":"u16"}}]}}"#; + const TEST_UNION_DESCRIPTOR: &str = r#"{"name":"Test.Union","x86":{"size":8,"alignment":8,"fields":[{"name":"integer","count":1,"type":{"kind":"u64"}},{"name":"pointer","count":1,"type":{"kind":"pointer"}}]},"x64":{"size":8,"alignment":8,"fields":[{"name":"integer","count":1,"type":{"kind":"u64"}},{"name":"pointer","count":1,"type":{"kind":"pointer"}}]},"arm64":{"size":8,"alignment":8,"fields":[{"name":"integer","count":1,"type":{"kind":"u64"}},{"name":"pointer","count":1,"type":{"kind":"pointer"}}]}}"#; + + #[repr(C)] + struct FakeComObject { + vtable: *const *mut c_void, + } + + #[test] + fn bstr_values_are_not_apartment_bound() { + let text = "embedded\0nul \u{1f642}"; + let value = AutomationValue::new(dynwinrt::com::Value::Bstr(dynwinrt::com::BstrValue::new( + text, + ))); + let result = std::thread::spawn(move || { + let dynwinrt::com::Value::Bstr(value) = value.to_com_value().unwrap() else { + panic!("expected BSTR") + }; + value.as_deref().unwrap().to_string() + }) + .join() + .unwrap(); + assert_eq!(result, text); + + let apartment_bound = AutomationValue::new(dynwinrt::com::Value::Variant( + dynwinrt::com::VariantValue::from_i32(1), + )); + assert!( + std::thread::spawn(move || apartment_bound.to_com_value().is_err()) + .join() + .unwrap() + ); + } + + unsafe extern "system" fn fill_excep_info( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows::core::HRESULT { + unsafe { + (*info).wCode = 7; + (*info).bstrSource = std::mem::ManuallyDrop::new(windows::core::BSTR::from("js source")); + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows::core::BSTR::from("js description")); + (*info).bstrHelpFile = std::mem::ManuallyDrop::new(windows::core::BSTR::from("js help")); + (*info).dwHelpContext = 19; + (*info).scode = 0x80020009u32 as i32; + } + windows::core::HRESULT(0) + } + + #[link(name = "oleaut32")] + unsafe extern "system" { + #[link_name = "SafeArrayCopy"] + fn safe_array_copy_for_test( + input: *mut windows::Win32::System::Com::SAFEARRAY, + output: *mut *mut windows::Win32::System::Com::SAFEARRAY, + ) -> windows::core::HRESULT; + } + + unsafe extern "system" fn copy_safe_array_for_test( + _this: *mut c_void, + input: *mut windows::Win32::System::Com::SAFEARRAY, + output: *mut *mut windows::Win32::System::Com::SAFEARRAY, + ) -> windows::core::HRESULT { + unsafe { safe_array_copy_for_test(input, output) } + } + + #[test] + fn automation_wrappers_are_tagged_typed_and_transfer_once() { + let union = + DynCom::create_native_union(TEST_UNION_DESCRIPTOR.into(), "integer".into(), None).unwrap(); + assert_eq!(union.active_field(), "integer"); + assert_eq!(union.bytes().as_ref(), &[0; 8]); + assert!( + DynCom::create_native_union(TEST_UNION_DESCRIPTOR.into(), "missing".into(), None).is_err() + ); + + let variant = DynComVariant::bstr("automation".into()).unwrap(); + assert_eq!(variant.kind().unwrap(), "bstr"); + assert_eq!(variant.to_string_value().unwrap(), "automation"); + assert!(variant.to_bool().is_err()); + assert!(DynComVariant::i8(128.0).is_err()); + assert!(DynComVariant::i8(4_294_967_297.0).is_err()); + assert!(DynComVariant::i32(4_294_967_296.0).is_err()); + assert!(DynComVariant::u32(-1.0).is_err()); + assert!(DynComVariant::bool(true).to_bool().unwrap()); + + let array = DynComSafeArray::i32( + vec![1.0, 2.0, 3.0, 4.0], + Some(vec![ + DynComSafeArrayBound { + lower_bound: -2.0, + length: 2.0, + }, + DynComSafeArrayBound { + lower_bound: 5.0, + length: 2.0, + }, + ]), + ) + .unwrap(); + assert_eq!(array.element_type().unwrap(), "i32"); + assert_eq!(array.to_numbers().unwrap(), [1.0, 2.0, 3.0, 4.0]); + assert_eq!(array.bounds().unwrap()[0].lower_bound, -2.0); + assert!(array.to_strings().is_err()); + assert!(DynComSafeArray::i32(vec![4_294_967_296.0], None).is_err()); + assert!(DynComSafeArray::i32( + vec![], + Some(vec![DynComSafeArrayBound { + lower_bound: 4_294_967_296.0, + length: 0.0, + }]), + ) + .is_err()); + + let array_variant = DynComVariant::safe_array(&array).unwrap(); + assert_eq!( + array_variant.to_safe_array().unwrap().to_numbers().unwrap(), + [1.0, 2.0, 3.0, 4.0] + ); + + let prop = DynComPropVariant::string_vector(vec!["a".into(), "b".into()]).unwrap(); + assert_eq!(prop.kind().unwrap(), "vector"); + assert_eq!(prop.to_strings().unwrap(), ["a", "b"]); + assert!(prop.to_numbers().is_err()); + assert!(DynComPropVariant::i8_vector(vec![4_294_967_297.0]).is_err()); + assert!(DynComPropVariant::string("bad\0value".into()).is_err()); + assert_eq!( + DynComPropVariant::blob(Buffer::from(vec![1, 2, 3])) + .unwrap() + .to_blob() + .unwrap() + .as_ref(), + &[1, 2, 3] + ); + + let mut stored = DynCom::variant(&variant).unwrap(); + let taken = DynCom::take_variant(&mut stored).unwrap(); + assert_eq!(taken.to_string_value().unwrap(), "automation"); + assert!(DynCom::take_variant(&mut stored).is_err()); + } + + #[test] + fn typed_interface_safearray_outputs_accept_valid_generic_descriptors() { + use windows::core::Interface as _; + use windows::Win32::System::WinRT::{RoInitialize, RO_INIT_MULTITHREADED}; + + let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + let expected_iid = windows::core::GUID::from_u128(0x00000035_0000_0000_c000_000000000046); + let interface = dynwinrt::com::register_interface( + &TABLE, + "Tests.ISafeArrayCopy", + windows::core::GUID::from_u128(0x10000000_0000_0000_0000_000000000002), + dynwinrt::com::InterfaceBase::IUnknown, + ) + .add_method( + "Copy", + dynwinrt::com::MethodSignature::new(&TABLE) + .add_in(dynwinrt::com::Type::typed_safe_array( + dynwinrt::com::SafeArrayElementType::Unknown, + )) + .add_out(dynwinrt::com::Type::typed_interface_safe_array( + expected_iid, + )), + ); + let method = interface.method(3).unwrap(); + let vtable = [ + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + copy_safe_array_for_test as *mut c_void, + ]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let factory = DynWinRTValue::activation_factory("Windows.Foundation.Uri".into()).unwrap(); + + for descriptor_iid in [None, Some(windows::core::IUnknown::IID)] { + let array = if let Some(iid) = descriptor_iid { + DynComSafeArray::interface( + &WinGUID(iid), + vec![&factory], + Some(vec![DynComSafeArrayBound { + lower_bound: -2.0, + length: 1.0, + }]), + ) + .unwrap() + } else { + DynComSafeArray::unknown( + vec![&factory], + Some(vec![DynComSafeArrayBound { + lower_bound: -2.0, + length: 1.0, + }]), + ) + .unwrap() + }; + let mut output = unsafe { + method.invoke_values_with_output_kinds( + (&mut object as *mut FakeComObject).cast(), + &[dynwinrt::com::Value::SafeArray( + array.value().unwrap().clone(), + )], + ) + } + .unwrap(); + let (value, kind) = output.pop().unwrap(); + let mut stored = DynWinRTValue::from_com_value(value, kind); + let projected = DynCom::take_safe_array(&mut stored).unwrap(); + assert_eq!(projected.interface_iid().unwrap().unwrap().0, expected_iid); + assert_eq!(projected.bounds().unwrap()[0].lower_bound, -2.0); + assert_eq!(projected.to_interfaces().unwrap().len(), 1); + } + } + + #[test] + fn dispatch_params_validate_ranges_clone_and_apartment_ownership() { + let first = DynComVariant::i32(10.0).unwrap(); + let second = DynComVariant::bstr("second".into()).unwrap(); + let mut params = DynComDispatchParams::new(vec![&first, &second], Some(vec![42.0])).unwrap(); + assert_eq!(params.argument_count().unwrap(), 2); + assert_eq!(params.named_dispids().unwrap(), [42]); + + let clone = params.clone_value().unwrap(); + params.release().unwrap(); + assert!(params.argument_count().is_err()); + assert_eq!(clone.argument_count().unwrap(), 2); + + assert!(DynComDispatchParams::new(vec![&first], Some(vec![1.0, 2.0])).is_err()); + assert!(DynComDispatchParams::new(vec![&first], Some(vec![1.5])).is_err()); + assert!(DynComDispatchParams::new(vec![&first], Some(vec![i32::MAX as f64 + 1.0])).is_err()); + + let cross_thread = clone.clone_value().unwrap(); + let error = std::thread::spawn(move || cross_thread.argument_count().unwrap_err()) + .join() + .unwrap(); + assert!(error.reason.contains("different thread")); + } + + #[test] + fn excep_info_output_transfers_to_the_js_wrapper_once() { + let interface = dynwinrt::com::register_interface( + &TABLE, + "Tests.IExcepInfo", + windows::core::GUID::from_u128(0x10000000_0000_0000_0000_000000000001), + dynwinrt::com::InterfaceBase::IUnknown, + ) + .add_method( + "GetInfo", + dynwinrt::com::MethodSignature::new(&TABLE).add_out(dynwinrt::com::Type::excep_info()), + ); + let method = interface.method(3).unwrap(); + let vtable = [ + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + fill_excep_info as *mut c_void, + ]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let mut output = unsafe { + method.invoke_values_with_output_kinds((&mut object as *mut FakeComObject).cast(), &[]) + } + .unwrap(); + let (value, kind) = output.pop().unwrap(); + let mut stored = DynWinRTValue::from_com_value(value, kind); + let mut info = DynCom::take_excep_info(&mut stored).unwrap(); + assert_eq!(info.code().unwrap(), 7); + assert_eq!(info.source().unwrap().as_deref(), Some("js source")); + assert_eq!( + info.description().unwrap().as_deref(), + Some("js description") + ); + assert_eq!(info.help_file().unwrap().as_deref(), Some("js help")); + assert_eq!(info.help_context().unwrap(), 19); + assert_eq!(info.scode().unwrap(), 0x80020009u32 as i32); + assert!(DynCom::take_excep_info(&mut stored).is_err()); + info.release().unwrap(); + assert!(info.description().is_err()); + } + + #[test] + fn native_struct_helpers_validate_identity_size_and_zero_initialization() { + let layout = native_struct_layout(TEST_POD_DESCRIPTOR).unwrap(); + assert_eq!(layout.name(), "Test.Pod"); + assert_eq!(layout.size(), 8); + + let zeroed = DynCom::create_native_struct(TEST_POD_DESCRIPTOR.into(), None).unwrap(); + assert_eq!(zeroed.bytes.as_slice(), &[0; 8]); + let array = + DynCom::create_native_struct_array(TEST_POD_DESCRIPTOR.into(), Buffer::from(vec![0; 16])) + .unwrap(); + assert_eq!(array.length(), 16); + assert!(DynCom::native_struct_buffer(TEST_POD_DESCRIPTOR.into(), &array).is_ok()); + assert!(DynCom::create_native_struct_array( + TEST_POD_DESCRIPTOR.into(), + Buffer::from(vec![0; 9]), + ) + .is_err()); + let initialized = DynCom::create_native_struct( + TEST_POD_DESCRIPTOR.into(), + Some(Buffer::from(vec![1, 2, 3, 4, 5, 6, 7, 8])), + ) + .unwrap(); + assert_eq!(initialized.bytes.as_slice(), &[1, 2, 3, 4, 5, 6, 7, 8]); + assert!(DynCom::create_native_struct( + TEST_POD_DESCRIPTOR.into(), + Some(Buffer::from(vec![0; 7])) + ) + .is_err()); + + let branded = DynComNativeStruct { + descriptor: TEST_POD_DESCRIPTOR.into(), + bytes: vec![1, 2, 3, 4, 5, 6, 7, 8], + }; + let mut value = DynCom::native_struct(TEST_POD_DESCRIPTOR.into(), &branded).unwrap(); + assert!(!DynCom::is_null_native_struct_pointer(&value)); + assert!(DynCom::is_null_native_struct_pointer( + &DynCom::null_native_struct_pointer() + )); + assert_eq!( + DynCom::native_struct_bytes(TEST_POD_DESCRIPTOR.into(), &value) + .unwrap() + .bytes + .as_slice(), + &[1, 2, 3, 4, 5, 6, 7, 8] + ); + value.release(); + assert!(DynCom::native_struct_bytes(TEST_POD_DESCRIPTOR.into(), &value).is_err()); + let wrong_type = DynComNativeStruct { + descriptor: TEST_POD_DESCRIPTOR.replace("Test.Pod", "Test.Other"), + bytes: vec![0; 8], + }; + assert!(DynCom::native_struct(TEST_POD_DESCRIPTOR.into(), &wrong_type).is_err()); + let wrong_size = DynComNativeStruct { + descriptor: TEST_POD_DESCRIPTOR.into(), + bytes: vec![0; 7], + }; + assert!(DynCom::native_struct(TEST_POD_DESCRIPTOR.into(), &wrong_size).is_err()); + } + + #[test] + fn projected_buffer_allocation_length_is_bounded() { + assert_eq!( + DynCom::buffer_allocation_length(BigInt::from(1024u64)).unwrap(), + 1024 + ); + assert!(DynCom::buffer_allocation_length(BigInt::from(i32::MAX as u64 + 1)).is_err()); + } #[test] fn string_pointer_buffers_require_matching_nul_terminators() { @@ -1184,6 +4858,73 @@ mod tests { assert!(validate_ansi_string_bytes(b"text").is_err()); } + #[test] + fn string_arrays_and_scalar_output_arrays_use_owned_runtime_storage() { + let wide = DynCom::wide_string_array(vec!["First".into(), "Second".into()]).unwrap(); + assert_eq!( + DynCom::buffer_count(&wide).unwrap().get_u64(), + (false, 2, true) + ); + assert!(DynCom::wide_string_array(vec!["embedded\0nul".into()]).is_err()); + assert!(DynCom::ansi_string_array(vec!["caf\u{e9}".into()]).is_err()); + + let mut output = DynCom::caller_output_array(&DynCom::i32_type(), BigInt::from(2u64)).unwrap(); + assert_eq!(DynCom::take_i32_array(&mut output).unwrap(), [0, 0]); + assert!(DynCom::take_i32_array(&mut output).is_err()); + } + + #[test] + fn enumerator_array_helpers_preserve_typed_zeroed_storage() { + let mut guids = + DynCom::enumerator_output_array(&DynCom::guid_type(), BigInt::from(2u64)).unwrap(); + assert_eq!( + DynCom::buffer_count(&guids).unwrap().get_u64(), + (false, 2, true) + ); + assert!(DynCom::take_guid_array(&mut guids) + .unwrap() + .iter() + .all(|value| value.eq_ignore_ascii_case("00000000-0000-0000-0000-000000000000"))); + assert!(DynCom::take_guid_array(&mut guids).is_err()); + let variants = + DynCom::enumerator_output_array(&DynCom::variant_type(), BigInt::from(1u64)).unwrap(); + assert_eq!( + DynCom::buffer_count(&variants).unwrap().get_u64(), + (false, 1, true) + ); + } + + #[test] + fn com_typed_buffer_widths_are_exact() { + use napi::sys::TypedarrayType; + + for typ in [ + TypedarrayType::int8_array, + TypedarrayType::uint8_array, + TypedarrayType::uint8_clamped_array, + ] { + assert_eq!(typed_array_element_size(typ as i32).unwrap(), 1); + } + for typ in [TypedarrayType::int16_array, TypedarrayType::uint16_array] { + assert_eq!(typed_array_element_size(typ as i32).unwrap(), 2); + } + for typ in [ + TypedarrayType::int32_array, + TypedarrayType::uint32_array, + TypedarrayType::float32_array, + ] { + assert_eq!(typed_array_element_size(typ as i32).unwrap(), 4); + } + for typ in [ + TypedarrayType::float64_array, + TypedarrayType::bigint64_array, + TypedarrayType::biguint64_array, + ] { + assert_eq!(typed_array_element_size(typ as i32).unwrap(), 8); + } + assert!(typed_array_element_size(i32::MAX).is_err()); + } + #[test] fn takes_and_clears_cotaskmem_wide_string() { let text = "dynwinrt"; @@ -1231,6 +4972,64 @@ mod tests { assert!(matches!(value.0, dynwinrt::WinRTValue::RawPtr(raw) if raw == ptr)); } + #[test] + fn unsafe_raw_com_ownership_is_explicit_and_preserves_the_caller_reference() { + let _ = dynwinrt::com::initialize_apartment(dynwinrt::com::ApartmentType::MultiThreaded); + let iid = WinGUID(windows::core::IUnknown::IID); + let original = co_create_instance("00021401-0000-0000-c000-000000000046".into(), &iid) + .expect("ShellLink activation"); + let object = original.0.as_object().unwrap(); + + let borrowed = borrow_com_pointer_bits(object.as_raw(), &iid).unwrap(); + drop(borrowed); + assert!(dynwinrt::WinRTValue::Object(object.clone()) + .cast(&iid.0) + .is_ok()); + + let transferred = std::mem::ManuallyDrop::new(object.clone()); + let adopted = adopt_owned_com_pointer_bits(transferred.as_raw(), &iid).unwrap(); + drop(adopted); + assert!(dynwinrt::WinRTValue::Object(object.clone()) + .cast(&iid.0) + .is_ok()); + + let transferred = std::mem::ManuallyDrop::new(object.clone()); + let unsupported = WinGUID(windows::core::GUID::from_u128( + 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, + )); + assert!(adopt_owned_com_pointer_bits(transferred.as_raw(), &unsupported).is_err()); + assert!(dynwinrt::WinRTValue::Object(object.clone()) + .cast(&iid.0) + .is_ok()); + } + + #[test] + fn borrowed_handle_outputs_convert_null_and_pointer_bits_without_adoption() { + let null = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(std::ptr::null_mut()), + dynwinrt::com::PointerOutputKind::None, + ); + assert_eq!( + as_pointer_bigint(&null).unwrap().get_u64(), + (false, 0, true) + ); + + let ptr = 0x1234usize as *mut std::ffi::c_void; + let mut value = DynWinRTValue::from_com_result( + dynwinrt::WinRTValue::RawPtr(ptr), + dynwinrt::com::PointerOutputKind::None, + ); + assert_eq!( + as_pointer_bigint(&value).unwrap().get_u64(), + (false, 0x1234, true) + ); + let error = + take_native_output_pointer(&mut value, PointerProvenance::ComOutput, "COM interface") + .unwrap_err(); + assert!(error.reason.contains("UnclassifiedOutput")); + assert!(matches!(value.0, dynwinrt::WinRTValue::RawPtr(raw) if raw == ptr)); + } + #[test] fn pointer_output_requires_the_exact_allocator_provenance() { let ptr = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(1) }; diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 0ab45e88..28a4ae81 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -18,7 +18,12 @@ use napi_derive::napi; use windows::core::{IUnknown, Interface, HSTRING}; mod com; -pub use com::{DynCom, DynComInterface, DynComMethodHandle, DynComMethodSig, DynComType}; +pub use com::{ + initialize_com, DynCom, DynComDispatchInvokeResult, DynComDispatchParams, DynComExcepInfo, + DynComInterface, DynComMethodHandle, DynComMethodSig, DynComNativeStruct, + DynComNativeStructArray, DynComNativeUnion, DynComPropVariant, DynComSafeArray, + DynComSafeArrayBound, DynComType, DynComUnsafe, DynComUnsafeInterface, DynComVariant, +}; mod async_promise; mod scheduled_start; @@ -579,21 +584,52 @@ pub struct DynWinRTValue( dynwinrt::WinRTValue, Option, com::PointerProvenance, + Option, + Option, + Option, ); unsafe impl Send for DynWinRTValue {} unsafe impl Sync for DynWinRTValue {} impl DynWinRTValue { fn new(value: dynwinrt::WinRTValue) -> Self { - Self(value, None, com::PointerProvenance::None) + Self(value, None, com::PointerProvenance::None, None, None, None) } fn with_pointer_owner(value: dynwinrt::WinRTValue, owner: com::NativePointerOwner) -> Self { - Self(value, Some(owner), com::PointerProvenance::Borrowed) + Self( + value, + Some(owner), + com::PointerProvenance::Borrowed, + None, + None, + None, + ) } fn with_borrowed_pointer(value: dynwinrt::WinRTValue) -> Self { - Self(value, None, com::PointerProvenance::Borrowed) + Self( + value, + None, + com::PointerProvenance::Borrowed, + None, + None, + None, + ) + } + + fn with_com_buffer( + buffer: dynwinrt::com::ComBufferValue, + owner: com::NativePointerOwner, + ) -> Self { + Self( + dynwinrt::WinRTValue::Null, + Some(owner), + com::PointerProvenance::Borrowed, + None, + Some(buffer), + None, + ) } fn from_com_result( @@ -612,7 +648,112 @@ impl DynWinRTValue { } else { com::PointerProvenance::None }; - Self(value, None, provenance) + Self(value, None, provenance, None, None, None) + } + + fn from_com_value( + value: dynwinrt::com::Value, + output_kind: dynwinrt::com::PointerOutputKind, + ) -> Self { + match value { + dynwinrt::com::Value::WinRt(value) => Self::from_com_result(value, output_kind), + dynwinrt::com::Value::Bstr(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new(dynwinrt::com::Value::Bstr(value))), + ), + dynwinrt::com::Value::NativeStruct(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + Some(value), + None, + None, + ), + dynwinrt::com::Value::NativeUnion(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new( + dynwinrt::com::Value::NativeUnion(value), + )), + ), + dynwinrt::com::Value::Variant(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new(dynwinrt::com::Value::Variant( + value, + ))), + ), + dynwinrt::com::Value::SafeArray(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new(dynwinrt::com::Value::SafeArray( + value, + ))), + ), + dynwinrt::com::Value::PropVariant(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new( + dynwinrt::com::Value::PropVariant(value), + )), + ), + dynwinrt::com::Value::DispatchParams(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new( + dynwinrt::com::Value::DispatchParams(value), + )), + ), + dynwinrt::com::Value::ExcepInfo(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new(dynwinrt::com::Value::ExcepInfo( + value, + ))), + ), + dynwinrt::com::Value::Buffer(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + Some(value), + None, + ), + } + } + + fn to_com_value(&self) -> napi::Result { + if let Some(value) = &self.5 { + value.to_com_value() + } else if let Some(value) = &self.4 { + Ok(dynwinrt::com::Value::Buffer(value.clone())) + } else if let Some(value) = &self.3 { + Ok(dynwinrt::com::Value::NativeStruct(value.clone())) + } else { + Ok(dynwinrt::com::Value::WinRt(self.0.clone())) + } } fn release_native_pointer_output(&mut self) { @@ -645,15 +786,22 @@ impl DynWinRTValue { impl Drop for DynWinRTValue { fn drop(&mut self) { - self.release_native_pointer_output(); - // After Application.Start returns, XAML has already torn down its thread // state. Leaking late projected COM references is safer than releasing // them into a destroyed DXamlCore; normal application teardown must call // release()/releaseProjected() before this process-exit fallback is needed. if winui_dispatcher_loop_exited() { + self.2 = com::PointerProvenance::None; let value = mem::replace(&mut self.0, dynwinrt::WinRTValue::Null); mem::forget(value); + if let Some(value) = self.4.take() { + mem::forget(value); + } + if let Some(value) = &mut self.5 { + value.leak_for_shutdown(); + } + } else { + self.release_native_pointer_output(); } } } @@ -666,6 +814,9 @@ impl DynWinRTValue { self.0 = dynwinrt::WinRTValue::Null; self.1 = None; self.2 = com::PointerProvenance::None; + self.3 = None; + self.4 = None; + self.5 = None; } #[napi] @@ -898,6 +1049,11 @@ impl DynWinRTValue { #[napi] pub fn to_string(&self) -> String { + if let Some(automation) = &self.5 { + if let Ok(dynwinrt::com::Value::Bstr(value)) = automation.to_com_value() { + return value.as_deref().unwrap_or_default().to_string(); + } + } match &self.0 { dynwinrt::WinRTValue::HString(s) => s.to_string(), dynwinrt::WinRTValue::I32(i) => i.to_string(), @@ -988,7 +1144,7 @@ impl DynWinRTValue { #[napi] pub fn is_null(&self) -> bool { - self.0.is_null_object() + self.3.is_none() && self.4.is_none() && self.5.is_none() && self.0.is_null_object() } #[napi] diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index 7a352f36..ad0b6623 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -9,6 +9,7 @@ authors = ["Microsoft"] [dependencies] libffi = "5.1.0" +libffi-sys = "4.1.0" paste = "1" windows-collections = "0.3.2" windows-core = "0.62.2" @@ -29,8 +30,11 @@ features = [ "System_Threading", "Web_Http", "Win32_System_Com", + "Win32_System_Com_StructuredStorage", "Win32_System_LibraryLoader", + "Win32_System_Ole", "Win32_System_Threading", + "Win32_System_Variant", "Win32_System_WinRT", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index 0717ecfb..16bd9b0b 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -7,12 +7,213 @@ use windows_core::{HRESULT, Interface}; use crate::{ abi::{AbiType, AbiValue}, - native_call::{MethodReturn, Parameter}, + native_call::{MethodReturn, NativeCallValue, Parameter}, value::WinRTValue, }; +struct NativeStructStorage { + ptr: std::ptr::NonNull, + allocation: std::alloc::Layout, +} + +struct NativeUnionStorage { + ptr: std::ptr::NonNull, + allocation: std::alloc::Layout, +} + +struct BstrCallValue { + raw: *const u16, +} + +impl BstrCallValue { + fn new(value: Option<&str>) -> windows_core::Result { + let Some(value) = value else { + return Ok(Self { + raw: std::ptr::null_mut(), + }); + }; + let utf16 = value.encode_utf16().collect::>(); + let value = + unsafe { windows::Win32::Foundation::SysAllocStringLen(Some(utf16.as_slice())) }; + let raw = value.into_raw(); + if raw.is_null() { + return Err(windows_core::Error::from_hresult(windows_core::HRESULT( + 0x8007000Eu32 as i32, + ))); + } + #[cfg(test)] + if !raw.is_null() { + BSTR_TEST_ALLOCS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + Ok(Self { raw }) + } + + fn as_raw(&self) -> *const u16 { + self.raw + } + + fn as_mut_ptr(&mut self) -> *mut *const u16 { + &mut self.raw + } + + fn take(&mut self) -> *const u16 { + std::mem::replace(&mut self.raw, std::ptr::null()) + } +} + +impl Drop for BstrCallValue { + fn drop(&mut self) { + if self.raw.is_null() { + return; + } + #[cfg(test)] + BSTR_TEST_FREES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + drop(unsafe { windows_core::BSTR::from_raw(self.take()) }); + } +} + +#[cfg(test)] +static BSTR_TEST_ALLOCS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(test)] +static BSTR_TEST_FREES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +#[cfg(test)] +pub(crate) fn reset_bstr_test_counts() { + BSTR_TEST_ALLOCS.store(0, std::sync::atomic::Ordering::Relaxed); + BSTR_TEST_FREES.store(0, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +pub(crate) fn bstr_test_counts() -> (usize, usize) { + ( + BSTR_TEST_ALLOCS.load(std::sync::atomic::Ordering::Relaxed), + BSTR_TEST_FREES.load(std::sync::atomic::Ordering::Relaxed), + ) +} + +impl NativeUnionStorage { + fn from_value(value: &crate::com::NativeUnionValue) -> windows_core::Result { + let layout = value.layout(); + let allocation = std::alloc::Layout::from_size_align(layout.size(), layout.alignment()) + .map_err(|_| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "invalid native union allocation layout", + ) + })?; + let ptr = unsafe { std::alloc::alloc_zeroed(allocation) }; + let ptr = std::ptr::NonNull::new(ptr).ok_or_else(|| { + windows_core::Error::new( + windows_core::HRESULT(0x8007000Eu32 as i32), + "native union allocation failed", + ) + })?; + unsafe { + std::ptr::copy_nonoverlapping( + value.bytes().as_ptr(), + ptr.as_ptr(), + value.bytes().len(), + ); + } + Ok(Self { ptr, allocation }) + } + + fn as_ptr(&self) -> *const u8 { + self.ptr.as_ptr() + } +} + +impl Drop for NativeUnionStorage { + fn drop(&mut self) { + unsafe { std::alloc::dealloc(self.ptr.as_ptr(), self.allocation) }; + } +} + +impl NativeStructStorage { + fn zeroed(layout: &crate::com::NativeStructLayout) -> windows_core::Result { + let allocation = std::alloc::Layout::from_size_align(layout.size(), layout.alignment()) + .map_err(|_| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "invalid native struct allocation layout", + ) + })?; + let ptr = unsafe { std::alloc::alloc_zeroed(allocation) }; + let ptr = std::ptr::NonNull::new(ptr).ok_or_else(|| { + windows_core::Error::new( + windows_core::HRESULT(0x8007000Eu32 as i32), + "native struct allocation failed", + ) + })?; + Ok(Self { ptr, allocation }) + } + + fn from_bytes( + layout: &crate::com::NativeStructLayout, + bytes: &[u8], + ) -> windows_core::Result { + if bytes.len() != layout.size() { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "native struct byte length does not match its layout", + )); + } + let storage = Self::zeroed(layout)?; + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), storage.ptr.as_ptr(), bytes.len()); + } + Ok(storage) + } + + fn as_ptr(&self) -> *const u8 { + self.ptr.as_ptr() + } + + fn as_mut_ptr(&mut self) -> *mut u8 { + self.ptr.as_ptr() + } + + fn to_vec(&self) -> Vec { + unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.allocation.size()).to_vec() } + } +} + +impl Drop for NativeStructStorage { + fn drop(&mut self) { + unsafe { std::alloc::dealloc(self.ptr.as_ptr(), self.allocation) }; + } +} + pub(crate) trait ArgumentList { fn get_value(&self, index: usize) -> &WinRTValue; + + fn get_bstr(&self, _index: usize) -> Option<&crate::com::BstrValue> { + None + } + + fn get_native_struct(&self, _index: usize) -> Option<&crate::com::NativeStructValue> { + None + } + + fn get_native_union(&self, _index: usize) -> Option<&crate::com::NativeUnionValue> { + None + } + + fn get_variant(&self, _index: usize) -> Option<&crate::com::VariantValue> { + None + } + + fn get_safe_array(&self, _index: usize) -> Option<&crate::com::SafeArrayValue> { + None + } + + fn get_prop_variant(&self, _index: usize) -> Option<&crate::com::PropVariantValue> { + None + } + + fn get_dispatch_params(&self, _index: usize) -> Option<&crate::com::DispatchParamsValue> { + None + } } impl ArgumentList for [WinRTValue] { @@ -221,6 +422,17 @@ fn cleanup_failed_outputs(parameters: &[Parameter], out_values: &mut [AbiValue]) } } +pub(crate) struct CapturedHResultCall { + pub(crate) hresult: HRESULT, + pub(crate) outputs: Vec>, + pub(crate) finalization_error: Option, +} + +enum DynamicCallOutcome { + Values(Vec), + Captured(CapturedHResultCall), +} + pub fn call_method_dynamic( vtable_index: usize, obj: *mut c_void, @@ -229,7 +441,59 @@ pub fn call_method_dynamic( out_count: usize, return_kind: &MethodReturn, cif: &libffi::middle::Cif, -) -> windows_core::Result> { +) -> windows_core::Result> { + match call_method_dynamic_impl( + vtable_index, + obj, + parameters, + args, + out_count, + return_kind, + cif, + )? { + DynamicCallOutcome::Values(values) => Ok(values), + DynamicCallOutcome::Captured(_) => Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "captured HRESULT calls require the dedicated COM invocation path", + )), + } +} + +pub(crate) fn call_method_dynamic_captured( + vtable_index: usize, + obj: *mut c_void, + parameters: &[Parameter], + args: &A, + out_count: usize, + return_kind: &MethodReturn, + cif: &libffi::middle::Cif, +) -> windows_core::Result { + match call_method_dynamic_impl( + vtable_index, + obj, + parameters, + args, + out_count, + return_kind, + cif, + )? { + DynamicCallOutcome::Captured(call) => Ok(call), + DynamicCallOutcome::Values(_) => Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "method does not use the captured HRESULT convention", + )), + } +} + +fn call_method_dynamic_impl( + vtable_index: usize, + obj: *mut c_void, + parameters: &[Parameter], + args: &A, + out_count: usize, + return_kind: &MethodReturn, + cif: &libffi::middle::Cif, +) -> windows_core::Result { use crate::metadata_table::ValueTypeData; use libffi::middle::CodePtr; @@ -239,6 +503,20 @@ pub fn call_method_dynamic( let mut out_ptrs: Vec<*const std::ffi::c_void> = Vec::with_capacity(out_count); let mut struct_out_values: Vec> = Vec::with_capacity(out_count); let mut guid_out_values: Vec>> = Vec::with_capacity(out_count); + let mut native_struct_out_values: Vec> = + Vec::with_capacity(out_count); + let mut bstr_out_values = std::collections::BTreeMap::>::new(); + let mut variant_out_values: Vec> = + Vec::with_capacity(out_count); + let mut safe_array_out_values: Vec>> = + Vec::with_capacity(out_count); + let mut prop_variant_out_values: Vec> = + Vec::with_capacity(out_count); + let mut excep_info_out_values = + std::collections::BTreeMap::>::new(); + let mut excep_info_values = + std::collections::BTreeMap::::new(); + let mut optional_out_requests: Vec> = Vec::with_capacity(out_count); // Array storage: Box'd for pointer stability (addresses don't change after creation) let mut array_out_slots: Vec> = Vec::new(); @@ -250,6 +528,10 @@ pub fn call_method_dynamic( // Array in-param storage: pre-compute all before building ffi_args let mut array_in_slots: Vec> = Vec::new(); + let mut native_struct_in_slots: Vec> = Vec::new(); + let mut bstr_in_slots: Vec = Vec::new(); + let mut native_union_in_slots: Vec = Vec::new(); + let mut variant_by_value_in_slots: Vec = Vec::new(); // FillArray storage: caller-allocated buffers let mut fill_array_slots: Vec> = Vec::new(); @@ -259,6 +541,33 @@ pub fn call_method_dynamic( // Phase 1a: Pre-allocate all out parameters for p in parameters { if p.is_out() { + let requested = if p.is_optional_out() { + match args.get_value(p.input_index.expect("optional output request index")) { + WinRTValue::Bool(requested) => *requested, + _ => { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "optional COM output request must be Boolean", + )); + } + } + } else { + true + }; + optional_out_requests.push(p.is_optional_out().then_some(requested)); + if !requested { + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + out_ptrs.push(std::ptr::null()); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + continue; + } if p.is_fill_array() { // FillArray: caller allocates buffer. Use the capacity from args. let array_data = args @@ -286,6 +595,10 @@ pub fn call_method_dynamic( out_ptrs.push(std::ptr::null()); struct_out_values.push(None); guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); array_out_map.push(None); } else if p.typ.is_array() { let slot = Box::new(ArrayOutSlot { @@ -303,6 +616,31 @@ pub fn call_method_dynamic( out_ptrs.push(std::ptr::null()); struct_out_values.push(None); guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + fill_array_map.push(None); + } else if p.typ.is_bstr() { + let mut value = Box::new(BstrCallValue::new( + p.is_in_out() + .then(|| { + args.get_bstr(p.input_index.expect("BSTR in/out input index")) + .expect("validated BSTR in/out value") + .as_deref() + }) + .flatten(), + )?); + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + bstr_out_values.insert(p.value_index, value); + array_out_map.push(None); fill_array_map.push(None); } else if p.typ.is_guid() { let value = Box::new(windows_core::GUID::zeroed()); @@ -310,6 +648,121 @@ pub fn call_method_dynamic( out_values.push(AbiValue::Pointer(std::ptr::null_mut())); struct_out_values.push(None); guid_out_values.push(Some(value)); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_native_struct_pointer() { + if !p.is_in_out() { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "native struct pointer outputs require an in/out contract", + )); + } + let layout = p + .typ + .native_struct_layout() + .expect("native struct pointer parameter has a layout"); + let mut value = match args + .get_native_struct(p.input_index.expect("in/out input index")) + { + Some(value) => Some(NativeStructStorage::from_bytes(layout, value.bytes())?), + None if p.typ.is_nullable_native_struct_pointer() => None, + None => { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "expected native struct value for in/out parameter", + )); + } + }; + out_ptrs.push( + value + .as_mut() + .map_or(std::ptr::null(), |value| value.as_mut_ptr().cast()), + ); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(value); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_native_struct() { + let layout = p + .typ + .native_struct_layout() + .expect("native struct parameter has a layout"); + let mut value = if p.is_in_out() { + NativeStructStorage::from_bytes( + layout, + args.get_native_struct(p.input_index.expect("in/out input index")) + .expect("validated native struct in/out value") + .bytes(), + )? + } else { + NativeStructStorage::zeroed(layout)? + }; + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(Some(value)); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_variant() { + let value = crate::com::VariantValue::empty(); + out_ptrs.push(value.raw_mut().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(Some(value)); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_safe_array() { + let mut value = Box::new(crate::com::automation::SafeArrayOutput::new()); + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(Some(value)); + prop_variant_out_values.push(None); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_prop_variant() { + let value = crate::com::PropVariantValue::empty(); + out_ptrs.push(value.raw_mut().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(Some(value)); + array_out_map.push(None); + fill_array_map.push(None); + } else if p.typ.is_excep_info() { + let mut value = Box::new(crate::com::automation::ExcepInfoOutput::new()); + out_ptrs.push(value.as_mut_ptr().cast()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + excep_info_out_values.insert(p.value_index, value); array_out_map.push(None); fill_array_map.push(None); } else if p.typ.is_struct() { @@ -330,6 +783,10 @@ pub fn call_method_dynamic( out_values.push(AbiValue::Pointer(std::ptr::null_mut())); struct_out_values.push(Some(val)); guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); array_out_map.push(None); fill_array_map.push(None); } else { @@ -342,6 +799,10 @@ pub fn call_method_dynamic( out_ptrs.push(out_values.last().unwrap().as_out_ptr()); struct_out_values.push(None); guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); array_out_map.push(None); fill_array_map.push(None); } @@ -362,12 +823,144 @@ pub fn call_method_dynamic( data_ptr, _buffer: buffer, })); + } else if p.is_input() + && !p.is_out() + && (p.typ.is_native_struct() || p.typ.is_native_struct_pointer()) + { + let layout = p + .typ + .native_struct_layout() + .expect("native struct input has a layout"); + let input_index = p.input_index.expect("native struct input index"); + let slot = match args.get_native_struct(input_index) { + Some(value) => Some(NativeStructStorage::from_bytes(layout, value.bytes())?), + None if p.typ.is_nullable_native_struct_pointer() => None, + None => panic!("validated native struct input"), + }; + native_struct_in_slots.push(slot); + } else if p.is_input() && !p.is_out() && p.typ.is_bstr() { + bstr_in_slots.push(BstrCallValue::new( + args.get_bstr(p.input_index.expect("BSTR input index")) + .expect("validated BSTR input") + .as_deref(), + )?); + } else if p.is_input() && !p.is_out() && p.typ.native_union_layout().is_some() { + native_union_in_slots.push(NativeUnionStorage::from_value( + args.get_native_union(p.input_index.expect("native union input index")) + .expect("validated native union input"), + )?); + } else if p.is_input() && !p.is_out() && p.typ.is_variant_by_value() { + variant_by_value_in_slots.push( + crate::com::automation::VariantCopyValue::new( + args.get_variant(p.input_index.expect("by-value VARIANT input index")) + .expect("validated by-value VARIANT input"), + ) + .map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?, + ); } } + let native_struct_in_ptrs = native_struct_in_slots + .iter() + .map(|slot| { + slot.as_ref() + .map_or(std::ptr::null(), NativeStructStorage::as_ptr) + }) + .collect::>(); + let native_union_in_ptrs = native_union_in_slots + .iter() + .map(NativeUnionStorage::as_ptr) + .collect::>(); + let bstr_in_ptrs = bstr_in_slots + .iter() + .map(BstrCallValue::as_raw) + .collect::>(); + let variant_in_ptrs = parameters + .iter() + .filter(|parameter| { + parameter.is_input() && !parameter.is_out() && parameter.typ.is_variant() + }) + .map(|parameter| { + args.get_variant(parameter.input_index.expect("VARIANT input index")) + .expect("validated VARIANT input") + .raw() + .cast::() + }) + .collect::>(); + let safe_array_inputs = parameters + .iter() + .filter(|parameter| { + parameter.is_input() && !parameter.is_out() && parameter.typ.is_safe_array() + }) + .map(|parameter| { + args.get_safe_array(parameter.input_index.expect("SAFEARRAY input index")) + .expect("validated SAFEARRAY input") + }) + .collect::>(); + let unique_safe_arrays = safe_array_inputs + .iter() + .map(|value| (value.identity(), *value)) + .collect::>(); + let safe_array_in_guards = unique_safe_arrays + .values() + .map(|value| { + value.lock_native().map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + }) + }) + .collect::>>()?; + let safe_array_raw_by_identity = unique_safe_arrays + .keys() + .copied() + .zip(safe_array_in_guards.iter().map(|guard| guard.as_raw())) + .collect::>(); + let safe_array_in_ptrs = safe_array_inputs + .iter() + .map(|value| safe_array_raw_by_identity[&value.identity()].cast::()) + .collect::>(); + let prop_variant_in_ptrs = parameters + .iter() + .filter(|parameter| { + parameter.is_input() && !parameter.is_out() && parameter.typ.is_prop_variant() + }) + .map(|parameter| { + args.get_prop_variant(parameter.input_index.expect("PROPVARIANT input index")) + .expect("validated PROPVARIANT input") + .raw() + .cast::() + }) + .collect::>(); + let dispatch_params_in_ptrs = parameters + .iter() + .filter(|parameter| { + parameter.is_input() && !parameter.is_out() && parameter.typ.is_dispatch_params() + }) + .map(|parameter| { + args.get_dispatch_params(parameter.input_index.expect("DISPPARAMS input index")) + .expect("validated DISPPARAMS input") + .raw_mut() + .cast::() + }) + .collect::>(); // Phase 2: Build ffi_args let mut array_in_idx = 0usize; let mut array_out_idx = 0usize; + let mut native_struct_in_idx = 0usize; + let mut native_union_in_idx = 0usize; + let mut bstr_in_idx = 0usize; + let mut variant_by_value_in_idx = 0usize; + let mut variant_in_idx = 0usize; + let mut safe_array_in_idx = 0usize; + let mut prop_variant_in_idx = 0usize; + let mut dispatch_params_in_idx = 0usize; for p in parameters { if p.is_out() { if let Some(slot_idx) = fill_array_map[p.value_index] { @@ -389,35 +982,71 @@ pub fn call_method_dynamic( ffi_args.push(arg(&slot.length)); ffi_args.push(arg(&slot.data_ptr)); array_in_idx += 1; + } else if p.typ.is_native_struct() { + let slot = native_struct_in_slots[native_struct_in_idx] + .as_ref() + .expect("by-value native struct cannot be null"); + ffi_args.push(Arg::new(unsafe { &*slot.as_ptr() })); + native_struct_in_idx += 1; + } else if p.typ.is_native_struct_pointer() { + ffi_args.push(arg(&native_struct_in_ptrs[native_struct_in_idx])); + native_struct_in_idx += 1; + } else if p.typ.native_union_layout().is_some() { + ffi_args.push(arg(&native_union_in_ptrs[native_union_in_idx])); + native_union_in_idx += 1; + } else if p.typ.is_bstr() { + ffi_args.push(arg(&bstr_in_ptrs[bstr_in_idx])); + bstr_in_idx += 1; + } else if p.typ.is_variant_by_value() { + ffi_args.push(arg( + variant_by_value_in_slots[variant_by_value_in_idx].as_ref() + )); + variant_by_value_in_idx += 1; + } else if p.typ.is_variant() { + ffi_args.push(arg(&variant_in_ptrs[variant_in_idx])); + variant_in_idx += 1; + } else if p.typ.is_safe_array() { + ffi_args.push(arg(&safe_array_in_ptrs[safe_array_in_idx])); + safe_array_in_idx += 1; + } else if p.typ.is_prop_variant() { + ffi_args.push(arg(&prop_variant_in_ptrs[prop_variant_in_idx])); + prop_variant_in_idx += 1; + } else if p.typ.is_dispatch_params() { + ffi_args.push(arg(&dispatch_params_in_ptrs[dispatch_params_in_idx])); + dispatch_params_in_idx += 1; } else { ffi_args.push(args.get_value(p.value_index).libffi_arg()); } } // Phase 3: Call - let return_value = unsafe { + let (return_value, native_hresult) = unsafe { match return_kind { MethodReturn::HResult => { let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); - if hr.is_err() { - cleanup_failed_outputs(parameters, &mut out_values); - hr.ok()?; - } - None + (None, Some(hr)) } MethodReturn::SemanticHResult => { let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); - if hr.is_err() { - cleanup_failed_outputs(parameters, &mut out_values); - hr.ok()?; - } - Some(WinRTValue::HResult(hr)) + ( + hr.is_ok() + .then_some(NativeCallValue::WinRt(WinRTValue::HResult(hr))), + Some(hr), + ) + } + MethodReturn::PreservedHResult => { + let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); + (Some(NativeCallValue::WinRt(WinRTValue::HResult(hr))), None) + } + MethodReturn::CapturedHResult(_) => { + let hr: windows_core::HRESULT = cif.call(CodePtr(fptr), &ffi_args); + (None, Some(hr)) } MethodReturn::Void => { cif.call::<()>(CodePtr(fptr), &ffi_args); - None + (None, None) } - MethodReturn::Value(typ) => { + MethodReturn::Value { typ, .. } => { let value = match typ.abi_type() { AbiType::Bool => AbiValue::Bool(cif.call(CodePtr(fptr), &ffi_args)), AbiType::I8 => AbiValue::I8(cif.call(CodePtr(fptr), &ffi_args)), @@ -433,15 +1062,108 @@ pub fn call_method_dynamic( AbiType::Guid => AbiValue::Guid(cif.call(CodePtr(fptr), &ffi_args)), AbiType::Ptr => AbiValue::Pointer(cif.call(CodePtr(fptr), &ffi_args)), }; - Some(typ.from_out_value(&value).map_err(|error| { + ( + Some(NativeCallValue::WinRt(typ.from_out_value(&value).map_err( + |error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + }, + )?)), + None, + ) + } + } + }; + + if let MethodReturn::CapturedHResult(plan) = return_kind { + const DISP_E_PARAMNOTFOUND: HRESULT = HRESULT(0x80020004u32 as i32); + const DISP_E_TYPEMISMATCH: HRESULT = HRESULT(0x80020005u32 as i32); + let hresult = native_hresult.expect("captured HRESULT call has a native HRESULT"); + let mut outputs = std::iter::repeat_with(|| None) + .take(out_count) + .collect::>(); + let mut finalization_error = None; + + if hresult.is_ok() { + if optional_out_requests[plan.result_output_index] == Some(true) { + let value = variant_out_values[plan.result_output_index] + .take() + .expect("captured result output uses VARIANT storage"); + value.validate_supported().map_err(|error| { windows_core::Error::new( windows_core::HRESULT(0x80070057u32 as i32), &error.message(), ) - })?) + })?; + outputs[plan.result_output_index] = Some(NativeCallValue::Variant(value)); } + } else { + if optional_out_requests[plan.excep_info_output_index] == Some(true) { + let output = excep_info_out_values + .remove(&plan.excep_info_output_index) + .expect("captured exception output uses EXCEPINFO storage"); + match (*output).into_value() { + Ok(value) if value.is_meaningful() => { + outputs[plan.excep_info_output_index] = + Some(NativeCallValue::ExcepInfo(value)); + } + Ok(_) => {} + Err(error) => { + finalization_error = Some(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + )); + } + } + } + if matches!(hresult, DISP_E_PARAMNOTFOUND | DISP_E_TYPEMISMATCH) + && optional_out_requests[plan.arg_err_output_index] == Some(true) + { + let AbiValue::U32(arg_err) = out_values[plan.arg_err_output_index] else { + unreachable!("captured argument error output uses UINT storage"); + }; + outputs[plan.arg_err_output_index] = + Some(NativeCallValue::WinRt(WinRTValue::U32(arg_err))); + } + cleanup_failed_outputs(parameters, &mut out_values); } - }; + + return Ok(DynamicCallOutcome::Captured(CapturedHResultCall { + hresult, + outputs, + finalization_error, + })); + } + + let mut excep_info_error = None; + for (index, output) in std::mem::take(&mut excep_info_out_values) { + match (*output).into_value() { + Ok(value) => { + excep_info_values.insert(index, value); + } + Err(error) => { + if excep_info_error.is_none() { + excep_info_error = Some(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + )); + } + } + } + } + if let Some(hr) = native_hresult.filter(|hr| hr.is_err()) { + cleanup_failed_outputs(parameters, &mut out_values); + return Err(excep_info_error.unwrap_or_else(|| { + hr.ok() + .expect_err("a failing HRESULT must produce a windows-core error") + })); + } + if let Some(error) = excep_info_error { + cleanup_failed_outputs(parameters, &mut out_values); + return Err(error); + } // Counted FillArray methods (for example GetMany) carry the actual count // as their UInt32 retval. Other FillArray methods write the full capacity. @@ -460,61 +1182,144 @@ pub fn call_method_dynamic( }; // Phase 4: Extract results - let mut result_values: Vec = + let mut result_values: Vec = Vec::with_capacity(out_count + usize::from(return_value.is_some())); - if let Some(value) = return_value { - result_values.push(value); - } - for p in parameters { - if p.is_out() { - if let Some(slot_idx) = fill_array_map[p.value_index] { - // FillArray: transfer CoTaskMem buffer ownership to ArrayData - let slot = &mut fill_array_slots[slot_idx]; - let length = fill_array_actual_count - .map(|count| count.min(slot.capacity)) - .unwrap_or(slot.capacity) as usize; - let ptr = slot.buffer_ptr as *mut c_void; - slot.buffer_ptr = std::ptr::null_mut(); // prevent FillArraySlot::drop from freeing - result_values.push(WinRTValue::Array(crate::array::ArrayData::from_cotaskmem( - slot.element_type.clone(), - ptr, - length, - ))); - } else if let Some(slot_idx) = array_out_map[p.value_index] { - // ReceiveArray: wrap callee-allocated CoTaskMem buffer directly. - // ArrayData takes ownership and will CoTaskMemFree + release elements on drop. - let slot = &mut array_out_slots[slot_idx]; - let length = slot.length as usize; - let data_ptr = slot.data_ptr; - // Null out data_ptr so ArrayOutSlot::drop won't double-free. - slot.data_ptr = std::ptr::null_mut(); - let array_value = if data_ptr.is_null() || length == 0 { - if !data_ptr.is_null() { - // Free empty but non-null buffer - unsafe { - windows::Win32::System::Com::CoTaskMemFree(Some(data_ptr)); + let extraction_result = (|| -> windows_core::Result<()> { + for p in parameters { + if p.is_out() { + if optional_out_requests[p.value_index] == Some(false) { + result_values.push(NativeCallValue::WinRt(WinRTValue::Null)); + continue; + } + if let Some(slot_idx) = fill_array_map[p.value_index] { + // FillArray: transfer CoTaskMem buffer ownership to ArrayData + let slot = &mut fill_array_slots[slot_idx]; + let length = fill_array_actual_count + .map(|count| count.min(slot.capacity)) + .unwrap_or(slot.capacity) as usize; + let ptr = slot.buffer_ptr as *mut c_void; + slot.buffer_ptr = std::ptr::null_mut(); // prevent FillArraySlot::drop from freeing + result_values.push(NativeCallValue::WinRt(WinRTValue::Array( + crate::array::ArrayData::from_cotaskmem( + slot.element_type.clone(), + ptr, + length, + ), + ))); + } else if let Some(slot_idx) = array_out_map[p.value_index] { + // ReceiveArray: wrap callee-allocated CoTaskMem buffer directly. + // ArrayData takes ownership and will CoTaskMemFree + release elements on drop. + let slot = &mut array_out_slots[slot_idx]; + let length = slot.length as usize; + let data_ptr = slot.data_ptr; + // Null out data_ptr so ArrayOutSlot::drop won't double-free. + slot.data_ptr = std::ptr::null_mut(); + let array_value = if data_ptr.is_null() || length == 0 { + if !data_ptr.is_null() { + // Free empty but non-null buffer + unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(data_ptr)); + } } + crate::array::ArrayData::empty(slot.element_type.clone()) + } else { + crate::array::ArrayData::from_cotaskmem( + slot.element_type.clone(), + data_ptr, + length, + ) + }; + result_values.push(NativeCallValue::WinRt(WinRTValue::Array(array_value))); + } else if let Some(mut value) = bstr_out_values.remove(&p.value_index) { + let ptr = value.take().cast_mut().cast(); + out_values[p.value_index] = AbiValue::Pointer(ptr); + result_values.push(NativeCallValue::WinRt(WinRTValue::RawPtr(ptr))); + } else if let Some(guid) = guid_out_values[p.value_index].take() { + result_values.push(NativeCallValue::WinRt(WinRTValue::Guid(*guid))); + } else if let Some(bytes) = native_struct_out_values[p.value_index].take() { + let layout = p + .typ + .native_struct_layout() + .expect("native struct output has a layout") + .clone(); + result_values.push(NativeCallValue::NativeStruct( + crate::com::NativeStructValue::new(layout, bytes.to_vec()).map_err( + |error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + }, + )?, + )); + } else if p.typ.is_nullable_native_struct_pointer() && p.is_in_out() { + result_values.push(NativeCallValue::WinRt(WinRTValue::Null)); + } else if let Some(value) = variant_out_values[p.value_index].take() { + value.validate_supported().map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?; + result_values.push(NativeCallValue::Variant(value)); + } else if let Some(value) = safe_array_out_values[p.value_index].take() { + if value.is_null() && p.typ.is_nullable_safe_array() { + result_values.push(NativeCallValue::WinRt(WinRTValue::Null)); + } else { + result_values.push(NativeCallValue::SafeArray( + (*value) + .into_value( + p.typ.safe_array_element(), + p.typ.safe_array_interface_iid(), + ) + .map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?, + )); } - crate::array::ArrayData::empty(slot.element_type.clone()) + } else if let Some(value) = prop_variant_out_values[p.value_index].take() { + value.validate_supported().map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })?; + result_values.push(NativeCallValue::PropVariant(value)); + } else if let Some(value) = excep_info_values.remove(&p.value_index) { + result_values.push(NativeCallValue::ExcepInfo(value)); + } else if let Some(struct_val) = struct_out_values[p.value_index].take() { + result_values.push(NativeCallValue::WinRt(WinRTValue::Struct(struct_val))); } else { - crate::array::ArrayData::from_cotaskmem( - slot.element_type.clone(), - data_ptr, - length, - ) - }; - result_values.push(WinRTValue::Array(array_value)); - } else if let Some(guid) = guid_out_values[p.value_index].take() { - result_values.push(WinRTValue::Guid(*guid)); - } else if let Some(struct_val) = struct_out_values[p.value_index].take() { - result_values.push(WinRTValue::Struct(struct_val)); - } else { - let mut out_value = p.typ.from_out_value(&out_values[p.value_index]).unwrap(); - // Safety: null IUnknown crashes on clone/drop. Replace with Null variant. - out_value.sanitize_null_object(); - result_values.push(out_value); + let mut out_value = p.typ.from_out_value(&out_values[p.value_index]).unwrap(); + // Safety: null IUnknown crashes on clone/drop. Replace with Null variant. + out_value.sanitize_null_object(); + let conversion_owns_native_value = !matches!(out_value, WinRTValue::RawPtr(_)); + result_values.push(NativeCallValue::WinRt(out_value)); + if conversion_owns_native_value + && let AbiValue::Pointer(ptr) = &mut out_values[p.value_index] + { + *ptr = std::ptr::null_mut(); + } + } } } + Ok(()) + })(); + if let Err(error) = extraction_result { + cleanup_failed_outputs(parameters, &mut out_values); + if let MethodReturn::Value { cleanup, .. } = return_kind + && *cleanup != crate::native_call::OutputCleanup::None + && let Some(NativeCallValue::WinRt(WinRTValue::RawPtr(ptr))) = &return_value + { + unsafe { cleanup.cleanup(*ptr) }; + } + return Err(error); + } + if let Some(value) = return_value { + result_values.insert(0, value); } - Ok(result_values) + Ok(DynamicCallOutcome::Values(result_values)) } diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index c0585eee..ac51fb89 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -3,9 +3,10 @@ use core::ffi::c_void; use std::{ - cell::RefCell, - collections::BTreeMap, - sync::{Arc, RwLock}, + cell::{RefCell, UnsafeCell}, + collections::{BTreeMap, BTreeSet}, + mem::{align_of, size_of}, + sync::{Arc, Mutex, MutexGuard, RwLock, TryLockError}, }; use windows::Win32::System::Com::{ @@ -15,11 +16,22 @@ use windows::Win32::System::Com::{ use windows_core::{GUID, IUnknown, Interface as WindowsInterface}; use crate::{ - MetadataTable, TypeHandle, WinRTValue, - native_call::{AbiMethodSignature, Method as NativeMethod, OutputCleanup, ParameterType}, + MetadataTable, TypeHandle, TypeKind, WinRTValue, + native_call::{ + CapturedHResultPlan, Method as NativeMethod, MethodReturn, OutputCleanup, ParamKind, + ParameterType, lower_completed_method, + }, result, }; +#[path = "com_automation.rs"] +pub(crate) mod automation; +pub use automation::{ + DispatchParamsValue, ExcepInfoValue, PropVariantData, PropVariantType, PropVariantValue, + PropVariantVector, PropVariantVectorType, SafeArrayBound, SafeArrayElementType, + SafeArrayElementValue, SafeArrayValue, VariantData, VariantType, VariantValue, +}; + const RPC_E_CHANGED_MODE: windows_core::HRESULT = windows_core::HRESULT(0x80010106u32 as i32); #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -46,553 +58,8126 @@ pub enum PointerOutputKind { Bstr, } -#[derive(Debug, Clone)] -pub struct Type { - abi: ParameterType, - pointer_output: PointerOutputKind, +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NativeStructScalar { + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + ISize, + USize, } -impl Type { - pub fn winrt(typ: TypeHandle) -> Self { - Self { - abi: ParameterType::winrt(typ), - pointer_output: PointerOutputKind::None, - } - } - - pub fn pointer() -> Self { - Self::pointer_with_output(PointerOutputKind::Unclassified) - } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NativeStructFieldType { + Scalar(NativeStructScalar), + Guid, + Pointer, + Struct(Arc), +} - pub fn owned_com_pointer() -> Self { - Self::pointer_with_output(PointerOutputKind::Com) +impl NativeStructFieldType { + fn size_alignment(&self) -> (usize, usize) { + match self { + Self::Scalar(scalar) => match scalar { + NativeStructScalar::I8 | NativeStructScalar::U8 => (1, 1), + NativeStructScalar::I16 | NativeStructScalar::U16 => (2, 2), + NativeStructScalar::I32 | NativeStructScalar::U32 | NativeStructScalar::F32 => { + (4, 4) + } + NativeStructScalar::I64 | NativeStructScalar::U64 | NativeStructScalar::F64 => { + (8, 8) + } + NativeStructScalar::ISize | NativeStructScalar::USize => { + (size_of::(), align_of::()) + } + }, + Self::Guid => (16, 4), + Self::Pointer => (size_of::(), align_of::()), + Self::Struct(layout) => (layout.size, layout.alignment), + } } - pub fn co_task_mem_pointer() -> Self { - Self::pointer_with_output(PointerOutputKind::CoTaskMem) + fn libffi_type(&self) -> libffi::middle::Type { + use libffi::middle::Type; + match self { + Self::Scalar(scalar) => match scalar { + NativeStructScalar::I8 => Type::i8(), + NativeStructScalar::U8 => Type::u8(), + NativeStructScalar::I16 => Type::i16(), + NativeStructScalar::U16 => Type::u16(), + NativeStructScalar::I32 => Type::i32(), + NativeStructScalar::U32 => Type::u32(), + NativeStructScalar::I64 => Type::i64(), + NativeStructScalar::U64 => Type::u64(), + NativeStructScalar::F32 => Type::f32(), + NativeStructScalar::F64 => Type::f64(), + NativeStructScalar::ISize => { + if size_of::() == 8 { + Type::i64() + } else { + Type::i32() + } + } + NativeStructScalar::USize => { + if size_of::() == 8 { + Type::u64() + } else { + Type::u32() + } + } + }, + Self::Guid => { + let mut fields = vec![Type::u32(), Type::u16(), Type::u16()]; + fields.extend(std::iter::repeat_with(Type::u8).take(8)); + Type::structure(fields) + } + Self::Pointer => Type::pointer(), + Self::Struct(layout) => layout.libffi_type(), + } } +} - pub fn bstr_pointer() -> Self { - Self::pointer_with_output(PointerOutputKind::Bstr) - } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeStructField { + name: String, + offset: usize, + count: u32, + typ: NativeStructFieldType, +} - fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { - Self { - abi: ParameterType::pointer(), - pointer_output, +impl NativeStructField { + pub fn new( + name: impl Into, + offset: usize, + count: u32, + typ: NativeStructFieldType, + ) -> result::Result { + let name = name.into(); + if name.trim().is_empty() || count == 0 { + return Err(invalid_argument( + "native struct fields require a name and non-zero count", + )); } + Ok(Self { + name, + offset, + count, + typ, + }) } } -#[derive(Debug, Clone)] -pub struct MethodSignature { - abi: AbiMethodSignature, - output_kinds: Vec, - return_kind: Option, +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeStructLayout { + name: String, + size: usize, + alignment: usize, + fields: Vec, } -impl MethodSignature { - pub fn new(table: &std::sync::Arc) -> Self { - Self { - abi: AbiMethodSignature::new(table), - output_kinds: Vec::new(), - return_kind: None, +impl NativeStructLayout { + pub fn new( + name: impl Into, + size: usize, + alignment: usize, + fields: Vec, + ) -> result::Result { + let name = name.into(); + if name.trim().is_empty() || size == 0 { + return Err(invalid_argument( + "native struct layout requires a name and non-zero size", + )); + } + if alignment == 0 || !alignment.is_power_of_two() || size % alignment != 0 { + return Err(invalid_argument( + "native struct alignment must be a power of two and divide its size", + )); + } + if fields.is_empty() { + return Err(invalid_argument( + "native struct layout requires at least one field", + )); + } + let mut names = std::collections::HashSet::new(); + let mut intervals = Vec::with_capacity(fields.len()); + let mut maximum_alignment = 1usize; + for field in &fields { + if !names.insert(field.name.as_str()) { + return Err(invalid_argument(format!( + "native struct `{name}` has duplicate field `{}`", + field.name + ))); + } + let (element_size, field_alignment) = field.typ.size_alignment(); + maximum_alignment = maximum_alignment.max(field_alignment); + if field.offset % field_alignment != 0 { + return Err(invalid_argument(format!( + "native struct `{name}` field `{}` offset {} violates alignment {field_alignment}", + field.name, field.offset + ))); + } + let field_size = element_size + .checked_mul(field.count as usize) + .ok_or_else(|| invalid_argument("native struct field size overflow"))?; + let end = field + .offset + .checked_add(field_size) + .ok_or_else(|| invalid_argument("native struct field end overflow"))?; + if end > size { + return Err(invalid_argument(format!( + "native struct `{name}` field `{}` extends past {size} bytes", + field.name + ))); + } + if intervals + .iter() + .any(|(start, existing_end)| field.offset < *existing_end && *start < end) + { + return Err(invalid_argument(format!( + "native struct `{name}` has overlapping field `{}`", + field.name + ))); + } + intervals.push((field.offset, end)); + } + if maximum_alignment != alignment { + return Err(invalid_argument(format!( + "native struct `{name}` declares alignment {alignment}, computed {maximum_alignment}" + ))); } + Ok(Self { + name, + size, + alignment, + fields, + }) } - pub fn add_in(mut self, typ: Type) -> Self { - self.abi = self.abi.add_in_type(typ.abi); - self + pub const fn size(&self) -> usize { + self.size } - pub fn add_out(mut self, typ: Type) -> Self { - self.output_kinds.push(typ.pointer_output); - self.abi = match typ.pointer_output { - PointerOutputKind::Com => self - .abi - .add_out_type_with_cleanup(typ.abi, OutputCleanup::ComRelease), - PointerOutputKind::CoTaskMem => self - .abi - .add_out_type_with_cleanup(typ.abi, OutputCleanup::CoTaskMemFree), - PointerOutputKind::Bstr => self - .abi - .add_out_type_with_cleanup(typ.abi, OutputCleanup::BstrFree), - PointerOutputKind::None | PointerOutputKind::Unclassified => { - self.abi.add_out_type(typ.abi) - } - }; - self + pub const fn alignment(&self) -> usize { + self.alignment } - pub fn add_in_out(mut self, typ: Type) -> Self { - self.output_kinds.push(PointerOutputKind::Unclassified); - self.abi = self.abi.add_in_out_type(typ.abi); - self + pub fn name(&self) -> &str { + &self.name } - pub fn add_out_fill(mut self, typ: Type) -> Self { - self.output_kinds.push(PointerOutputKind::None); - self.abi = self.abi.add_out_fill_type(typ.abi); - self + pub(crate) fn libffi_type(&self) -> libffi::middle::Type { + let mut fields = self.fields.iter().collect::>(); + fields.sort_by_key(|field| field.offset); + let mut elements = Vec::new(); + let mut cursor = 0usize; + for field in fields { + elements.extend( + std::iter::repeat_with(libffi::middle::Type::u8).take( + field + .offset + .checked_sub(cursor) + .expect("validated native struct fields do not overlap"), + ), + ); + for _ in 0..field.count { + elements.push(field.typ.libffi_type()); + } + cursor = field.offset + field.typ.size_alignment().0 * field.count as usize; + } + elements.extend(std::iter::repeat_with(libffi::middle::Type::u8).take(self.size - cursor)); + libffi::middle::Type::structure(elements) } +} - pub fn returns(mut self, typ: Type) -> Self { - self.return_kind = Some(typ.pointer_output); - self.abi = self.abi.returns_type(typ.abi); - self +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeStructValue { + layout: Arc, + bytes: Vec, +} + +impl NativeStructValue { + pub fn new(layout: Arc, bytes: Vec) -> result::Result { + if bytes.len() != layout.size { + return Err(invalid_argument(format!( + "native struct `{}` requires {} bytes, received {}", + layout.name, + layout.size, + bytes.len() + ))); + } + Ok(Self { layout, bytes }) } - pub fn returns_void(mut self) -> Self { - self.return_kind = None; - self.abi = self.abi.returns_void(); - self + pub fn zeroed(layout: Arc) -> Self { + Self { + bytes: vec![0; layout.size], + layout, + } } - pub fn preserve_hresult(mut self) -> Self { - self.return_kind = Some(PointerOutputKind::None); - self.abi = self.abi.preserve_hresult(); - self + pub fn layout(&self) -> &Arc { + &self.layout } - fn build(self, vtable_index: usize) -> RegisteredMethod { - let mut result_kinds = - Vec::with_capacity(self.output_kinds.len() + usize::from(self.return_kind.is_some())); - if let Some(kind) = self.return_kind { - result_kinds.push(kind); - } - result_kinds.extend(self.output_kinds); - RegisteredMethod { - native: self.abi.build(vtable_index), - result_kinds, - } + pub fn bytes(&self) -> &[u8] { + &self.bytes } } -#[derive(Debug)] -struct RegisteredMethod { - native: NativeMethod, - result_kinds: Vec, +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NativeUnionFieldType { + Scalar(NativeStructScalar), + Guid, + Pointer, + Struct(Arc), } -// Safety: a RegisteredMethod is fully built before publication and remains -// immutable. NativeMethod invokes libffi's CIF only through shared references; -// ffi_call treats the prepared CIF and its type graph as read-only. -unsafe impl Send for RegisteredMethod {} -unsafe impl Sync for RegisteredMethod {} +impl NativeUnionFieldType { + fn size_alignment(&self) -> (usize, usize) { + match self { + Self::Scalar(value) => NativeStructFieldType::Scalar(*value).size_alignment(), + Self::Guid => NativeStructFieldType::Guid.size_alignment(), + Self::Pointer => NativeStructFieldType::Pointer.size_alignment(), + Self::Struct(layout) => NativeStructFieldType::Struct(layout.clone()).size_alignment(), + } + } +} -#[derive(Debug, Clone)] -pub struct Interface { +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeUnionField { name: String, - iid: GUID, - base_slot: usize, - methods: Arc)>>>, + count: u32, + typ: NativeUnionFieldType, } -impl Interface { +impl NativeUnionField { + pub fn new( + name: impl Into, + count: u32, + typ: NativeUnionFieldType, + ) -> result::Result { + let name = name.into(); + if name.trim().is_empty() || count == 0 { + return Err(invalid_argument( + "native union fields require a name and non-zero count", + )); + } + Ok(Self { name, count, typ }) + } + pub fn name(&self) -> &str { &self.name } +} - pub fn iid(&self) -> GUID { - self.iid +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeUnionLayout { + name: String, + size: usize, + alignment: usize, + fields: Vec, +} + +impl NativeUnionLayout { + pub fn new( + name: impl Into, + size: usize, + alignment: usize, + fields: Vec, + ) -> result::Result { + let name = name.into(); + if name.trim().is_empty() || size == 0 { + return Err(invalid_argument( + "native union layout requires a name and non-zero size", + )); + } + if alignment == 0 || !alignment.is_power_of_two() || size % alignment != 0 { + return Err(invalid_argument( + "native union alignment must be a power of two and divide its size", + )); + } + if fields.is_empty() { + return Err(invalid_argument( + "native union layout requires at least one field", + )); + } + let mut names = std::collections::HashSet::new(); + let mut maximum_alignment = 1usize; + for field in &fields { + if !names.insert(field.name.as_str()) { + return Err(invalid_argument(format!( + "native union `{name}` has duplicate field `{}`", + field.name + ))); + } + let (element_size, field_alignment) = field.typ.size_alignment(); + maximum_alignment = maximum_alignment.max(field_alignment); + let field_size = element_size + .checked_mul(field.count as usize) + .ok_or_else(|| invalid_argument("native union field size overflow"))?; + if field_size > size { + return Err(invalid_argument(format!( + "native union `{name}` field `{}` requires {field_size} bytes but the union has {size}", + field.name + ))); + } + } + if maximum_alignment != alignment { + return Err(invalid_argument(format!( + "native union `{name}` declares alignment {alignment}, computed {maximum_alignment}" + ))); + } + Ok(Self { + name, + size, + alignment, + fields, + }) } - pub fn add_method(self, name: &str, signature: MethodSignature) -> Self { - let vtable_index = self - .methods - .read() - .unwrap() - .last_key_value() - .map_or(self.base_slot, |(slot, _)| slot + 1); - self.add_method_at(vtable_index, name, signature) - .expect("sequential COM method registration must use a free vtable slot") + pub const fn size(&self) -> usize { + self.size } - pub fn add_method_at( - self, - vtable_index: usize, - name: &str, - signature: MethodSignature, + pub const fn alignment(&self) -> usize { + self.alignment + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn has_field(&self, name: &str) -> bool { + self.fields.iter().any(|field| field.name == name) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeUnionValue { + layout: Arc, + active_field: String, + bytes: Vec, +} + +impl NativeUnionValue { + pub fn new( + layout: Arc, + active_field: impl Into, + bytes: Vec, ) -> result::Result { - if vtable_index < self.base_slot { + let active_field = active_field.into(); + if !layout.has_field(&active_field) { return Err(invalid_argument(format!( - "COM method '{name}' uses vtable slot {vtable_index}, before the interface base slot {}", - self.base_slot + "native union `{}` has no active field `{active_field}`", + layout.name ))); } - - let mut methods = self.methods.write().unwrap(); - if methods.contains_key(&vtable_index) { + if bytes.len() != layout.size { return Err(invalid_argument(format!( - "COM vtable slot {vtable_index} is already registered on '{}'", - self.name + "native union `{}` requires {} bytes, received {}", + layout.name, + layout.size, + bytes.len() ))); } - methods.insert( - vtable_index, - (name.to_string(), Arc::new(signature.build(vtable_index))), - ); - drop(methods); - Ok(self) + Ok(Self { + layout, + active_field, + bytes, + }) } - pub fn method(&self, vtable_index: usize) -> Option { - self.methods - .read() - .unwrap() - .get(&vtable_index) - .map(|(_, method)| MethodHandle(Arc::clone(method))) + pub fn zeroed( + layout: Arc, + active_field: impl Into, + ) -> result::Result { + let bytes = vec![0; layout.size]; + Self::new(layout, active_field, bytes) } -} -#[derive(Clone)] -pub struct MethodHandle(Arc); + pub fn layout(&self) -> &Arc { + &self.layout + } -impl std::fmt::Debug for MethodHandle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("MethodHandle").finish_non_exhaustive() + pub fn active_field(&self) -> &str { + &self.active_field } -} -impl MethodHandle { - pub fn invoke(&self, obj: *mut c_void, args: &[WinRTValue]) -> result::Result> { - self.0 - .native - .call_dynamic(obj, args) - .map_err(result::Error::WindowsError) + pub fn bytes(&self) -> &[u8] { + &self.bytes } +} - pub fn invoke_with_output_kinds( - &self, - obj: *mut c_void, - args: &[WinRTValue], - ) -> result::Result> { - let values = self.invoke(obj, args)?; - if values.len() != self.0.result_kinds.len() { - return Err(invalid_argument(format!( - "COM result plan mismatch: native call returned {} value(s), signature describes {}", - values.len(), - self.0.result_kinds.len() - ))); - } - Ok(values - .into_iter() - .zip(self.0.result_kinds.iter().copied()) - .collect()) +#[derive(Debug, Clone)] +pub struct BstrValue(Option); + +impl BstrValue { + pub fn new(value: impl Into) -> Self { + Self(Some(value.into())) } - pub fn call_getter_hstring(&self, obj: *mut c_void) -> result::Result { - self.0 - .native - .call_getter_hstring(obj) - .map_err(result::Error::WindowsError) + pub fn null() -> Self { + Self(None) } -} -pub fn register_interface( - _table: &std::sync::Arc, - name: &str, - iid: GUID, - base: InterfaceBase, -) -> Interface { - Interface { - name: name.to_string(), - iid, - base_slot: base.first_method_slot(), - methods: Arc::new(RwLock::new(BTreeMap::new())), + pub fn as_deref(&self) -> Option<&str> { + self.0.as_deref() } } -fn invalid_argument(message: String) -> result::Error { - result::Error::WindowsError(windows_core::Error::new( - windows_core::HRESULT(0x80070057u32 as i32), - &message, - )) +#[derive(Debug, Clone)] +pub enum Value { + WinRt(WinRTValue), + Bstr(BstrValue), + NativeStruct(NativeStructValue), + NativeUnion(NativeUnionValue), + Variant(VariantValue), + SafeArray(SafeArrayValue), + PropVariant(PropVariantValue), + DispatchParams(DispatchParamsValue), + ExcepInfo(ExcepInfoValue), + Buffer(ComBufferValue), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ApartmentType { - SingleThreaded, - MultiThreaded, -} - -impl ApartmentType { - fn as_flag(self) -> windows::Win32::System::Com::COINIT { - match self { - Self::SingleThreaded => COINIT_APARTMENTTHREADED, - Self::MultiThreaded => COINIT_MULTITHREADED, - } - } +pub enum StringEncoding { + Utf16, + Ansi, } -struct ComApartment { - apartment_type: ApartmentType, +#[derive(Debug, Clone)] +enum EncodedString { + Utf16(Box<[u16]>), + Ansi(Box<[u8]>), } -impl Drop for ComApartment { - fn drop(&mut self) { - unsafe { CoUninitialize() }; +impl EncodedString { + fn pointer(&mut self) -> *mut c_void { + match self { + Self::Utf16(value) => value.as_mut_ptr().cast(), + Self::Ansi(value) => value.as_mut_ptr().cast(), + } } } -enum ComInitialization { - Uninitialized, - Owned(ComApartment), +#[repr(align(16))] +#[derive(Debug, Clone, Copy)] +struct AlignedBufferBlock { + _bytes: [u8; 16], } -thread_local! { - static COM_INITIALIZATION: RefCell = - const { RefCell::new(ComInitialization::Uninitialized) }; +#[derive(Debug)] +enum ComBufferStorage { + Borrowed { + ptr: *mut u8, + byte_len: usize, + source_element_size: usize, + raw_bytes: bool, + writable: bool, + _empty_storage: Option>, + }, + OwnedInput { + bytes: Vec, + source_element_size: usize, + native_layout_name: String, + }, + StringArray { + encoding: StringEncoding, + strings: Vec, + pointers: Vec<*mut c_void>, + }, + InterfaceArray { + iid: GUID, + values: Vec, + pointers: Vec<*mut c_void>, + }, + BstrArray { + values: Vec, + }, + VariantArray { + values: Vec, + }, + CallerOutput { + blocks: Arc>>, + byte_len: usize, + source_element_size: usize, + native_layout_name: Option, + element_kind: BufferElementKind, + }, + Owned { + bytes: Vec, + count: usize, + }, + OwnedCom { + values: Vec, + }, + OwnedStrings { + values: Vec, + }, + OwnedVariants { + values: Vec, + }, } -pub fn initialize_apartment(apartment_type: ApartmentType) -> result::Result<()> { - COM_INITIALIZATION.with(|state| { - if let ComInitialization::Owned(existing) = &*state.borrow() { - return if existing.apartment_type == apartment_type { - Ok(()) - } else { - Err(result::Error::WindowsError( - windows_core::Error::from_hresult(RPC_E_CHANGED_MODE), - )) - }; - } - - let hr = unsafe { CoInitializeEx(None, apartment_type.as_flag()) }; - if hr.is_ok() { - *state.borrow_mut() = ComInitialization::Owned(ComApartment { apartment_type }); - Ok(()) - } else { - Err(result::Error::WindowsError( - windows_core::Error::from_hresult(hr), - )) +impl Clone for ComBufferStorage { + fn clone(&self) -> Self { + match self { + Self::Borrowed { + ptr, + byte_len, + source_element_size, + raw_bytes, + writable, + _empty_storage, + } => Self::Borrowed { + ptr: *ptr, + byte_len: *byte_len, + source_element_size: *source_element_size, + raw_bytes: *raw_bytes, + writable: *writable, + _empty_storage: _empty_storage.clone(), + }, + Self::OwnedInput { + bytes, + source_element_size, + native_layout_name, + } => Self::OwnedInput { + bytes: bytes.clone(), + source_element_size: *source_element_size, + native_layout_name: native_layout_name.clone(), + }, + Self::StringArray { + encoding, strings, .. + } => { + let mut strings = strings.clone(); + let pointers = strings.iter_mut().map(EncodedString::pointer).collect(); + Self::StringArray { + encoding: *encoding, + strings, + pointers, + } + } + Self::InterfaceArray { iid, values, .. } => { + let values = values.clone(); + let pointers = values.iter().map(|value| value.as_raw()).collect(); + Self::InterfaceArray { + iid: *iid, + values, + pointers, + } + } + Self::BstrArray { values } => Self::BstrArray { + values: values.clone(), + }, + Self::VariantArray { values } => Self::VariantArray { + values: values.clone(), + }, + Self::CallerOutput { + blocks, + byte_len, + source_element_size, + native_layout_name, + element_kind, + } => Self::CallerOutput { + blocks: Arc::clone(blocks), + byte_len: *byte_len, + source_element_size: *source_element_size, + native_layout_name: native_layout_name.clone(), + element_kind: *element_kind, + }, + Self::Owned { bytes, count } => Self::Owned { + bytes: bytes.clone(), + count: *count, + }, + Self::OwnedCom { values } => Self::OwnedCom { + values: values.clone(), + }, + Self::OwnedStrings { values } => Self::OwnedStrings { + values: values.clone(), + }, + Self::OwnedVariants { values } => Self::OwnedVariants { + values: values.clone(), + }, } - }) + } } -pub fn co_create_instance(clsid: GUID, iid: GUID) -> result::Result { - let unknown: IUnknown = unsafe { CoCreateInstance(&clsid, None, CLSCTX_INPROC_SERVER) } - .map_err(result::Error::WindowsError)?; - let mut result = std::ptr::null_mut(); - unsafe { unknown.query(&iid, &mut result) } - .ok() - .map_err(result::Error::WindowsError)?; - Ok(WinRTValue::Object(unsafe { IUnknown::from_raw(result) })) -} +#[repr(align(16))] +struct EmptyBufferStorage(UnsafeCell<[u8; 16]>); -/// Adopt an AddRef-owned COM interface pointer into a managed Object value. -/// -/// The pointer must represent a caller-owned COM reference (+1). This function -/// takes ownership with `IUnknown::from_raw` and must not be used for borrowed -/// pointers. -pub unsafe fn adopt_com_pointer(ptr: *mut c_void) -> WinRTValue { - if ptr.is_null() { - WinRTValue::Null - } else { - WinRTValue::Object(unsafe { IUnknown::from_raw(ptr) }) +impl std::fmt::Debug for EmptyBufferStorage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EmptyBufferStorage").finish_non_exhaustive() } } -pub fn call_method( - vtable_index: usize, - obj: *mut c_void, - signature: MethodSignature, - args: &[WinRTValue], -) -> result::Result> { - signature - .build(vtable_index) - .native - .call_dynamic(obj, args) - .map_err(result::Error::WindowsError) -} +// Safety: this storage is used only as a stable, non-null address for native +// contracts with a zero byte count. A conforming callee never dereferences it. +unsafe impl Send for EmptyBufferStorage {} +unsafe impl Sync for EmptyBufferStorage {} -#[cfg(test)] -fn call_method_1_ptr( - vtable_index: usize, - obj: *mut c_void, - ptr: *const c_void, -) -> result::Result<()> { - crate::call::call_winrt_method_1(vtable_index, obj, ptr) - .ok() - .map_err(result::Error::WindowsError) +#[derive(Debug, Clone)] +pub struct ComBufferValue { + storage: ComBufferStorage, } -#[cfg(test)] -fn call_method_2_ptr_i32( - vtable_index: usize, - obj: *mut c_void, - ptr: *mut c_void, - value: i32, -) -> result::Result<()> { - crate::call::call_winrt_method_2(vtable_index, obj, ptr, value) - .ok() - .map_err(result::Error::WindowsError) -} +impl ComBufferValue { + pub fn null() -> Self { + Self { + storage: ComBufferStorage::Borrowed { + ptr: std::ptr::null_mut(), + byte_len: 0, + source_element_size: 1, + raw_bytes: true, + writable: true, + _empty_storage: None, + }, + } + } -#[cfg(test)] -fn wide_null(text: &str) -> Vec { - text.encode_utf16().chain(std::iter::once(0)).collect() -} + /// # Safety + /// + /// `ptr` must remain valid for `byte_len` bytes while this value is used by + /// a COM invocation. Writable buffers must point to mutable storage. + pub unsafe fn borrowed( + ptr: *mut u8, + byte_len: usize, + source_element_size: usize, + raw_bytes: bool, + writable: bool, + ) -> result::Result { + if source_element_size == 0 { + return Err(invalid_argument( + "COM buffer source element size must be non-zero", + )); + } -#[cfg(test)] -fn wide_buffer(characters: usize) -> Vec { - vec![0; characters] -} + if byte_len > 0 && ptr.is_null() { + return Err(invalid_argument( + "non-empty COM buffers require non-null backing storage", + )); + } + let empty_storage = (byte_len == 0 && ptr.is_null()) + .then(|| Arc::new(EmptyBufferStorage(UnsafeCell::new([0; 16])))); + let ptr = empty_storage + .as_ref() + .map_or(ptr, |storage| storage.0.get().cast::()); + Ok(Self { + storage: ComBufferStorage::Borrowed { + ptr, + byte_len, + source_element_size, + raw_bytes, + writable, + _empty_storage: empty_storage, + }, + }) + } -#[cfg(test)] -fn wide_to_string(buffer: &[u16]) -> String { - let end = buffer - .iter() - .position(|ch| *ch == 0) - .unwrap_or(buffer.len()); - String::from_utf16_lossy(&buffer[..end]) -} + pub fn native_struct_input( + bytes: Vec, + layout: &NativeStructLayout, + ) -> result::Result { + if bytes.len() % layout.size() != 0 { + return Err(invalid_argument(format!( + "native struct array byte length {} is not a multiple of `{}` size {}", + bytes.len(), + layout.name(), + layout.size() + ))); + } + Ok(Self { + storage: ComBufferStorage::OwnedInput { + bytes, + source_element_size: layout.size(), + native_layout_name: layout.name().to_string(), + }, + }) + } -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - MetadataTable, com_helpers::E_NOINTERFACE, ro_get_activation_factory_2, - roapi::query_interface, - }; - use std::sync::atomic::{AtomicU32, Ordering}; - use windows::{ - ApplicationModel::DataTransfer::DataTransferManager, - Win32::{ - System::Com::{CoGetMalloc, IMalloc, IPersistFile, IStream}, - UI::Shell::{IDataTransferManagerInterop, SHCreateMemStream}, - UI::WindowsAndMessaging::{ - CreateWindowExW, DestroyWindow, WINDOW_EX_STYLE, WS_OVERLAPPED, + pub fn string_array(values: Vec, encoding: StringEncoding) -> result::Result { + let mut strings = Vec::with_capacity(values.len()); + for value in values { + if value.contains('\0') { + return Err(invalid_argument( + "COM string array elements cannot contain embedded NUL characters", + )); + } + let encoded = match encoding { + StringEncoding::Utf16 => EncodedString::Utf16( + value + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>() + .into_boxed_slice(), + ), + StringEncoding::Ansi => { + if !value.is_ascii() { + return Err(invalid_argument( + "COM ANSI string arrays currently accept ASCII text only", + )); + } + let mut bytes = value.into_bytes(); + bytes.push(0); + EncodedString::Ansi(bytes.into_boxed_slice()) + } + }; + strings.push(encoded); + } + let pointers = strings.iter_mut().map(EncodedString::pointer).collect(); + Ok(Self { + storage: ComBufferStorage::StringArray { + encoding, + strings, + pointers, }, - }, - }; - use windows_core::{HSTRING, w}; + }) + } - #[repr(C)] - struct FakeComObject { - vtable: *const *mut c_void, + pub fn interface_array(iid: GUID, values: Vec) -> result::Result { + let mut exact = Vec::with_capacity(values.len()); + for value in values { + let mut queried = std::ptr::null_mut(); + unsafe { value.query(&iid, &mut queried) } + .ok() + .map_err(result::Error::WindowsError)?; + exact.push(unsafe { IUnknown::from_raw(queried) }); + } + let pointers = exact.iter().map(|value| value.as_raw()).collect(); + Ok(Self { + storage: ComBufferStorage::InterfaceArray { + iid, + values: exact, + pointers, + }, + }) } - #[repr(C)] - struct TrackedComObject { - vtable: *const windows_core::IUnknown_Vtbl, - releases: AtomicU32, + pub fn bstr_array(values: Vec) -> Self { + Self { + storage: ComBufferStorage::BstrArray { values }, + } } - unsafe extern "system" fn tracked_query_interface( - _this: *mut c_void, - _iid: *const GUID, - result: *mut *mut c_void, - ) -> windows_core::HRESULT { - unsafe { *result = std::ptr::null_mut() }; - E_NOINTERFACE + pub fn variant_array(values: Vec) -> result::Result { + for value in &values { + value.validate_supported()?; + } + Ok(Self { + storage: ComBufferStorage::VariantArray { values }, + }) } - unsafe extern "system" fn tracked_add_ref(_this: *mut c_void) -> u32 { - 2 + pub fn caller_output(element_type: &Type, count: usize) -> result::Result { + let element = BufferElementPlan::from_type(element_type)?; + Self::caller_output_with_plan(element, count) } - unsafe extern "system" fn tracked_release(this: *mut c_void) -> u32 { - let object = unsafe { &*(this as *const TrackedComObject) }; - object.releases.fetch_add(1, Ordering::Relaxed); - 1 + pub fn enumerator_output(element_type: &Type, count: usize) -> result::Result { + let element = BufferElementPlan::from_enumerator_type(element_type)?; + Self::caller_output_with_plan(element, count) } - static TRACKED_VTABLE: windows_core::IUnknown_Vtbl = windows_core::IUnknown_Vtbl { - QueryInterface: tracked_query_interface, - AddRef: tracked_add_ref, - Release: tracked_release, - }; + fn caller_output_with_plan(element: BufferElementPlan, count: usize) -> result::Result { + let byte_len = count_bytes(count, &element, BufferCountUnit::Elements)?; + let block_count = byte_len.div_ceil(size_of::()); + Ok(Self { + storage: ComBufferStorage::CallerOutput { + blocks: Arc::new(Mutex::new(vec![ + AlignedBufferBlock { _bytes: [0; 16] }; + block_count + ])), + byte_len, + source_element_size: element.size, + native_layout_name: element.native_layout_name, + element_kind: element.kind, + }, + }) + } - #[repr(C)] - struct FailingOutCall { - vtable: *const *mut c_void, - output: *mut c_void, + fn owned(bytes: Vec, count: usize) -> Self { + Self { + storage: ComBufferStorage::Owned { bytes, count }, + } } - unsafe extern "system" fn write_object_then_fail( - this: *mut c_void, - output: *mut *mut c_void, - ) -> windows_core::HRESULT { - let call = unsafe { &*(this as *const FailingOutCall) }; - unsafe { *output = call.output }; - windows_core::HRESULT(0x80004005u32 as i32) + fn owned_com(values: Vec) -> Self { + Self { + storage: ComBufferStorage::OwnedCom { values }, + } + } + + fn owned_strings(values: Vec) -> Self { + Self { + storage: ComBufferStorage::OwnedStrings { values }, + } } - unsafe extern "system" fn write_object_and_i32_then_fail( - this: *mut c_void, - output: *mut *mut c_void, - number: *mut i32, - ) -> windows_core::HRESULT { - let call = unsafe { &*(this as *const FailingOutCall) }; - unsafe { - *output = call.output; - *number = 42; + fn owned_variants(values: Vec) -> Self { + Self { + storage: ComBufferStorage::OwnedVariants { values }, + } + } + + pub fn into_com_values(self) -> result::Result> { + match self.storage { + ComBufferStorage::OwnedCom { values } => Ok(values), + _ => Err(invalid_argument( + "COM buffer result does not contain managed interface elements", + )), + } + } + + pub fn into_strings(self) -> result::Result> { + match self.storage { + ComBufferStorage::OwnedStrings { values } => Ok(values), + _ => Err(invalid_argument( + "COM buffer result does not contain owned string elements", + )), + } + } + + pub fn into_variants(self) -> result::Result> { + match self.storage { + ComBufferStorage::OwnedVariants { values } => Ok(values), + _ => Err(invalid_argument( + "COM buffer result does not contain owned VARIANT elements", + )), + } + } + + pub fn bytes(&self) -> Option<&[u8]> { + match &self.storage { + ComBufferStorage::Owned { bytes, .. } => Some(bytes), + ComBufferStorage::OwnedInput { bytes, .. } => Some(bytes), + ComBufferStorage::Borrowed { .. } + | ComBufferStorage::StringArray { .. } + | ComBufferStorage::InterfaceArray { .. } + | ComBufferStorage::BstrArray { .. } + | ComBufferStorage::VariantArray { .. } + | ComBufferStorage::CallerOutput { .. } + | ComBufferStorage::OwnedCom { .. } + | ComBufferStorage::OwnedStrings { .. } + | ComBufferStorage::OwnedVariants { .. } => None, + } + } + + pub fn snapshot_bytes(&self) -> result::Result>> { + match &self.storage { + ComBufferStorage::Owned { bytes, .. } | ComBufferStorage::OwnedInput { bytes, .. } => { + Ok(Some(bytes.clone())) + } + ComBufferStorage::CallerOutput { + blocks, byte_len, .. + } => { + let blocks = blocks + .lock() + .map_err(|_| invalid_argument("caller-output COM storage lock is poisoned"))?; + Ok(Some( + unsafe { std::slice::from_raw_parts(blocks.as_ptr().cast::(), *byte_len) } + .to_vec(), + )) + } + ComBufferStorage::Borrowed { .. } + | ComBufferStorage::StringArray { .. } + | ComBufferStorage::InterfaceArray { .. } + | ComBufferStorage::BstrArray { .. } + | ComBufferStorage::VariantArray { .. } + | ComBufferStorage::OwnedCom { .. } + | ComBufferStorage::OwnedStrings { .. } + | ComBufferStorage::OwnedVariants { .. } => Ok(None), + } + } + + pub fn count(&self) -> usize { + match &self.storage { + ComBufferStorage::Owned { count, .. } => *count, + ComBufferStorage::StringArray { pointers, .. } => pointers.len(), + ComBufferStorage::InterfaceArray { pointers, .. } => pointers.len(), + ComBufferStorage::BstrArray { values } => values.len(), + ComBufferStorage::VariantArray { values } => values.len(), + ComBufferStorage::CallerOutput { + byte_len, + source_element_size, + .. + } => byte_len / source_element_size, + ComBufferStorage::OwnedCom { values } => values.len(), + ComBufferStorage::OwnedStrings { values } => values.len(), + ComBufferStorage::OwnedVariants { values } => values.len(), + ComBufferStorage::Borrowed { + byte_len, + source_element_size, + .. + } => byte_len / source_element_size, + ComBufferStorage::OwnedInput { + bytes, + source_element_size, + .. + } => bytes.len() / source_element_size, + } + } + + pub fn element_count(&self, element_type: &Type) -> result::Result { + let element = BufferElementPlan::from_type(element_type)?; + let prepared = prepare_borrowed_buffer(self, &element, false)?; + buffer_count(prepared.byte_len, &element, BufferCountUnit::Elements) + } + + fn borrowed_parts( + &self, + ) -> result::Result<( + *mut u8, + usize, + usize, + bool, + bool, + Option<&str>, + Option, + )> { + match &self.storage { + ComBufferStorage::Borrowed { + ptr, + byte_len, + source_element_size, + raw_bytes, + writable, + .. + } => Ok(( + *ptr, + *byte_len, + *source_element_size, + *raw_bytes, + *writable, + None, + None, + )), + ComBufferStorage::OwnedInput { + bytes, + source_element_size, + native_layout_name, + } => Ok(( + bytes.as_ptr().cast_mut(), + bytes.len(), + *source_element_size, + false, + false, + Some(native_layout_name), + None, + )), + ComBufferStorage::StringArray { + encoding, pointers, .. + } => Ok(( + pointers.as_ptr().cast_mut().cast(), + pointers.len() * size_of::<*mut c_void>(), + size_of::<*mut c_void>(), + false, + false, + None, + Some(*encoding), + )), + ComBufferStorage::InterfaceArray { pointers, .. } => Ok(( + pointers.as_ptr().cast_mut().cast(), + pointers.len() * size_of::<*mut c_void>(), + size_of::<*mut c_void>(), + false, + false, + None, + None, + )), + ComBufferStorage::BstrArray { .. } | ComBufferStorage::VariantArray { .. } => Err( + invalid_argument("owning COM input arrays require call-local prepared storage"), + ), + ComBufferStorage::CallerOutput { .. } => Err(invalid_argument( + "caller-output COM storage requires exclusive invocation access", + )), + ComBufferStorage::Owned { .. } => Err(invalid_argument( + "an owned COM buffer result cannot be reused as borrowed call storage", + )), + ComBufferStorage::OwnedCom { .. } => Err(invalid_argument( + "a managed COM array result cannot be reused as borrowed call storage", + )), + ComBufferStorage::OwnedStrings { .. } | ComBufferStorage::OwnedVariants { .. } => { + Err(invalid_argument( + "an owned COM array result cannot be reused as borrowed call storage", + )) + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BufferCountUnit { + Elements, + Bytes, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BufferAllocator { + CoTaskMem, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BufferElementCleanup { + None, + ComRelease, + BstrFree, + VariantClear, + CoTaskMemFree, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BufferElementKind { + Plain, + StringPointer(StringEncoding), + ComInterface(GUID), + Bstr, + Variant, + CoTaskMemWideString, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct BufferElementPlan { + size: usize, + alignment: usize, + cleanup: BufferElementCleanup, + native_layout_name: Option, + kind: BufferElementKind, +} + +impl BufferElementPlan { + fn from_type(typ: &Type) -> result::Result { + let (size, alignment) = match &typ.abi { + ParameterType::WinRT(handle) + if matches!( + handle.kind(), + TypeKind::Bool + | TypeKind::I8 + | TypeKind::U8 + | TypeKind::I16 + | TypeKind::U16 + | TypeKind::Char16 + | TypeKind::I32 + | TypeKind::U32 + | TypeKind::I64 + | TypeKind::U64 + | TypeKind::F32 + | TypeKind::F64 + | TypeKind::Guid + | TypeKind::HResult + | TypeKind::Enum(_) + ) => + { + (handle.size_of(), handle.align_of()) + } + ParameterType::NativeStruct(layout) => (layout.size(), layout.alignment()), + ParameterType::WinRT(handle) if handle.kind().is_com_pointer() => { + let iid = handle.iid().ok_or_else(|| { + invalid_argument("COM interface buffer elements require an exact IID") + })?; + return Ok(Self { + size: size_of::<*mut c_void>(), + alignment: align_of::<*mut c_void>(), + cleanup: BufferElementCleanup::ComRelease, + native_layout_name: None, + kind: BufferElementKind::ComInterface(iid), + }); + } + ParameterType::CoTaskMemWideString => { + return Ok(Self { + size: size_of::<*mut c_void>(), + alignment: align_of::<*mut c_void>(), + cleanup: BufferElementCleanup::CoTaskMemFree, + native_layout_name: None, + kind: BufferElementKind::CoTaskMemWideString, + }); + } + ParameterType::Pointer + | ParameterType::NativeStructPointer { .. } + | ParameterType::NativeUnionPointer(_) => { + return Err(invalid_argument( + "pointer buffer elements require explicit element ownership", + )); + } + ParameterType::Bstr { .. } => { + return Ok(Self { + size: size_of::<*mut c_void>(), + alignment: align_of::<*mut c_void>(), + cleanup: BufferElementCleanup::BstrFree, + native_layout_name: None, + kind: BufferElementKind::Bstr, + }); + } + ParameterType::Variant => { + return Ok(Self { + size: crate::com::automation::variant_size(), + alignment: crate::com::automation::variant_alignment(), + cleanup: BufferElementCleanup::VariantClear, + native_layout_name: None, + kind: BufferElementKind::Variant, + }); + } + ParameterType::VariantByValue + | ParameterType::SafeArray { .. } + | ParameterType::PropVariant + | ParameterType::DispatchParams + | ParameterType::ExcepInfo => { + return Err(invalid_argument( + "Automation buffer elements require dedicated ownership and cleanup plans", + )); + } + ParameterType::WinRT(_) => { + return Err(invalid_argument( + "counted COM buffers currently require primitive, GUID, or enum elements", + )); + } + }; + if size == 0 || alignment == 0 { + return Err(invalid_argument( + "counted COM buffer element layout must be non-zero", + )); + } + Ok(Self { + size, + alignment, + cleanup: BufferElementCleanup::None, + native_layout_name: match &typ.abi { + ParameterType::NativeStruct(layout) => Some(layout.name().to_string()), + _ => None, + }, + kind: BufferElementKind::Plain, + }) + } + + fn string_pointer(encoding: StringEncoding) -> Self { + Self { + size: size_of::<*mut c_void>(), + alignment: align_of::<*mut c_void>(), + cleanup: BufferElementCleanup::None, + native_layout_name: None, + kind: BufferElementKind::StringPointer(encoding), + } + } + + fn from_enumerator_type(typ: &Type) -> result::Result { + Self::from_type(typ) + } +} + +#[derive(Debug, Clone)] +pub struct Type { + abi: ParameterType, + pointer_output: PointerOutputKind, +} + +impl Type { + pub fn winrt(typ: TypeHandle) -> Self { + Self { + abi: ParameterType::winrt(typ), + pointer_output: PointerOutputKind::None, + } + } + + pub fn pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::Unclassified) + } + + pub fn borrowed_handle_output() -> Self { + Self::pointer_with_output(PointerOutputKind::None) + } + + pub fn owned_com_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::Com) + } + + pub fn co_task_mem_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::CoTaskMem) + } + + pub fn co_task_mem_wide_string() -> Self { + Self { + abi: ParameterType::co_task_mem_wide_string(), + pointer_output: PointerOutputKind::CoTaskMem, + } + } + + pub fn bstr_pointer() -> Self { + Self::pointer_with_output(PointerOutputKind::Bstr) + } + + pub fn bstr() -> Self { + Self { + abi: ParameterType::bstr(false), + pointer_output: PointerOutputKind::Bstr, + } + } + + pub fn nullable_bstr() -> Self { + Self { + abi: ParameterType::bstr(true), + pointer_output: PointerOutputKind::Bstr, + } + } + + pub fn native_struct(layout: Arc) -> Self { + Self { + abi: ParameterType::native_struct(layout), + pointer_output: PointerOutputKind::None, + } + } + + pub fn native_struct_pointer(layout: Arc) -> Self { + Self { + abi: ParameterType::native_struct_pointer(layout, false), + pointer_output: PointerOutputKind::None, + } + } + + pub fn nullable_native_struct_pointer(layout: Arc) -> Self { + Self { + abi: ParameterType::native_struct_pointer(layout, true), + pointer_output: PointerOutputKind::None, + } + } + + pub fn native_union_pointer(layout: Arc) -> Self { + Self { + abi: ParameterType::native_union_pointer(layout), + pointer_output: PointerOutputKind::None, + } + } + + pub fn variant() -> Self { + Self { + abi: ParameterType::variant(), + pointer_output: PointerOutputKind::None, + } + } + + pub fn variant_by_value() -> Self { + Self { + abi: ParameterType::variant_by_value(), + pointer_output: PointerOutputKind::None, + } + } + + pub fn safe_array() -> Self { + Self { + abi: ParameterType::safe_array(None), + pointer_output: PointerOutputKind::None, + } + } + + pub fn typed_safe_array(element: SafeArrayElementType) -> Self { + Self { + abi: ParameterType::safe_array(Some(element)), + pointer_output: PointerOutputKind::None, + } + } + + pub fn typed_interface_safe_array(iid: GUID) -> Self { + Self { + abi: ParameterType::interface_safe_array(iid), + pointer_output: PointerOutputKind::None, + } + } + + pub fn nullable_typed_safe_array(element: SafeArrayElementType) -> Self { + Self { + abi: ParameterType::nullable_safe_array(element, None), + pointer_output: PointerOutputKind::None, + } + } + + pub fn nullable_typed_interface_safe_array(iid: GUID) -> Self { + Self { + abi: ParameterType::nullable_safe_array(SafeArrayElementType::Unknown, Some(iid)), + pointer_output: PointerOutputKind::None, + } + } + + pub fn prop_variant() -> Self { + Self { + abi: ParameterType::prop_variant(), + pointer_output: PointerOutputKind::None, + } + } + + pub fn dispatch_params() -> Self { + Self { + abi: ParameterType::dispatch_params(), + pointer_output: PointerOutputKind::None, + } + } + + pub fn excep_info() -> Self { + Self { + abi: ParameterType::excep_info(), + pointer_output: PointerOutputKind::None, + } + } + + fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { + Self { + abi: ParameterType::pointer(), + pointer_output, + } + } + + fn output_cleanup(&self) -> OutputCleanup { + match self.pointer_output { + PointerOutputKind::Com => OutputCleanup::ComRelease, + PointerOutputKind::CoTaskMem => OutputCleanup::CoTaskMemFree, + PointerOutputKind::Bstr => OutputCleanup::BstrFree, + PointerOutputKind::None | PointerOutputKind::Unclassified => { + self.abi.default_output_cleanup() + } + } + } + + fn supports_direct_return(&self) -> bool { + matches!(self.abi, ParameterType::Pointer) + || matches!( + &self.abi, + ParameterType::WinRT(typ) + if matches!( + typ.kind(), + TypeKind::Bool + | TypeKind::I8 + | TypeKind::U8 + | TypeKind::I16 + | TypeKind::U16 + | TypeKind::Char16 + | TypeKind::I32 + | TypeKind::U32 + | TypeKind::I64 + | TypeKind::U64 + | TypeKind::F32 + | TypeKind::F64 + | TypeKind::HResult + | TypeKind::Enum(_) + ) + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ComParameterDirection { + In, + Out, + OptionalOut, + InOut, + OutFill, + InputBuffer, + CallerOutputBuffer, + CalleeAllocatedBuffer, +} + +impl ComParameterDirection { + const fn is_input(self) -> bool { + matches!( + self, + Self::In + | Self::OptionalOut + | Self::InOut + | Self::OutFill + | Self::InputBuffer + | Self::CallerOutputBuffer + ) + } + + const fn is_output(self) -> bool { + matches!( + self, + Self::Out + | Self::OptionalOut + | Self::InOut + | Self::OutFill + | Self::CallerOutputBuffer + | Self::CalleeAllocatedBuffer + ) + } + + const fn native_kind(self) -> ParamKind { + match self { + Self::In | Self::InputBuffer | Self::CallerOutputBuffer => ParamKind::In, + Self::Out | Self::CalleeAllocatedBuffer => ParamKind::Out, + Self::OptionalOut => ParamKind::OptionalOut, + Self::InOut => ParamKind::InOut, + Self::OutFill => ParamKind::OutFillArray, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ComArgumentStorage { + Value, + OutputPointer, + InOutPointer, + FillBuffer, + InputBuffer, + CallerOutputBuffer, + CalleeAllocatedBuffer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ComBufferParamRole { + InputCount { buffer_param: usize }, + InputActual { buffer_param: usize }, + CallerCapacity { buffer_param: usize }, + CallerActual { buffer_param: usize }, + CallerCapacityActual { buffer_param: usize }, + CalleeCount { buffer_param: usize }, +} + +impl ComBufferParamRole { + const fn buffer_param(self) -> usize { + match self { + Self::InputCount { buffer_param } + | Self::InputActual { buffer_param } + | Self::CallerCapacity { buffer_param } + | Self::CallerActual { buffer_param } + | Self::CallerCapacityActual { buffer_param } + | Self::CalleeCount { buffer_param } => buffer_param, + } + } + + const fn hides_input(self) -> bool { + matches!( + self, + Self::InputCount { .. } + | Self::CallerCapacity { .. } + | Self::CallerCapacityActual { .. } + ) + } + + const fn hides_output(self) -> bool { + !matches!(self, Self::InputActual { .. }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum ComBufferRelation { + Input { + count_param: usize, + actual_length_param: Option, + unit: BufferCountUnit, + }, + CallerCapacity { + capacity_param: usize, + actual_length_param: Option, + unit: BufferCountUnit, + two_call: bool, + }, + EnumeratorNext { + capacity_param: usize, + fetched_param: usize, + }, + CalleeAllocated { + count_param: usize, + unit: BufferCountUnit, + allocator: BufferAllocator, + }, +} + +impl ComBufferRelation { + fn related_params(&self) -> impl Iterator { + let (first, second) = match self { + Self::Input { + count_param, + actual_length_param, + .. + } => (*count_param, *actual_length_param), + Self::CallerCapacity { + capacity_param, + actual_length_param, + .. + } => (*capacity_param, *actual_length_param), + Self::EnumeratorNext { + capacity_param, + fetched_param, + } => (*capacity_param, Some(*fetched_param)), + Self::CalleeAllocated { count_param, .. } => (*count_param, None), + }; + std::iter::once(first).chain(second) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ComBufferContract { + element: BufferElementPlan, + relation: ComBufferRelation, +} + +#[derive(Debug, Clone)] +struct ComParameterSpec { + direction: ComParameterDirection, + typ: Type, + buffer: Option, +} + +#[derive(Debug, Clone)] +struct ComArgumentPlan { + typ: ParameterType, + direction: ComParameterDirection, + storage: ComArgumentStorage, + input_index: Option, + output_index: Option, + failure_cleanup: OutputCleanup, + buffer: Option, + buffer_roles: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ComResultSource { + DirectReturn, + Parameter(usize), + Buffer(usize), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ComSuccessDisposition { + Value, + BorrowedPointer, + OwnedComPointer, + OwnedCoTaskMemPointer, + OwnedBstr, +} + +impl From for ComSuccessDisposition { + fn from(kind: PointerOutputKind) -> Self { + match kind { + PointerOutputKind::None => Self::Value, + PointerOutputKind::Unclassified => Self::BorrowedPointer, + PointerOutputKind::Com => Self::OwnedComPointer, + PointerOutputKind::CoTaskMem => Self::OwnedCoTaskMemPointer, + PointerOutputKind::Bstr => Self::OwnedBstr, + } + } +} + +impl ComSuccessDisposition { + const fn pointer_output_kind(self) -> PointerOutputKind { + match self { + Self::Value => PointerOutputKind::None, + Self::BorrowedPointer => PointerOutputKind::Unclassified, + Self::OwnedComPointer => PointerOutputKind::Com, + Self::OwnedCoTaskMemPointer => PointerOutputKind::CoTaskMem, + Self::OwnedBstr => PointerOutputKind::Bstr, + } + } +} + +#[derive(Debug, Clone)] +struct ComResultPlan { + source: ComResultSource, + typ: Option, + success: ComSuccessDisposition, + failure_cleanup: OutputCleanup, +} + +#[derive(Debug)] +pub struct DispatchInvokeResult { + hresult: windows_core::HRESULT, + result: Option, + excep_info: Option, + arg_err: Option, + finalization_error: Option, +} + +impl DispatchInvokeResult { + pub fn hresult(&self) -> windows_core::HRESULT { + self.hresult + } + + pub fn result(&self) -> Option<&VariantValue> { + self.result.as_ref() + } + + pub fn excep_info(&self) -> Option<&ExcepInfoValue> { + self.excep_info.as_ref() + } + + pub fn arg_err(&self) -> Option { + self.arg_err + } + + pub fn finalization_error(&self) -> Option<&windows_core::Error> { + self.finalization_error.as_ref() + } + + pub fn into_parts( + self, + ) -> ( + windows_core::HRESULT, + Option, + Option, + Option, + Option, + ) { + ( + self.hresult, + self.result, + self.excep_info, + self.arg_err, + self.finalization_error, + ) + } +} + +#[derive(Debug, Clone)] +enum ComReturnPlan { + HResult, + SemanticHResult, + EnumeratorNextHResult, + DispatchInvokeHResult(CapturedHResultPlan), + Void, + Direct(Type), +} + +#[derive(Debug)] +struct ComCallPlan { + native: NativeMethod, + arguments: Vec, + results: Vec, + return_plan: ComReturnPlan, +} + +impl ComCallPlan { + fn new( + native: NativeMethod, + parameters: Vec, + return_plan: ComReturnPlan, + ) -> Self { + let mut buffer_roles = vec![Vec::new(); parameters.len()]; + for (buffer_param, parameter) in parameters.iter().enumerate() { + let Some(buffer) = ¶meter.buffer else { + continue; + }; + for related in buffer.relation.related_params() { + assert!( + related < parameters.len() && related != buffer_param, + "counted COM buffer relationships must reference another parameter" + ); + } + match buffer.relation { + ComBufferRelation::Input { + count_param, + actual_length_param, + .. + } => { + set_buffer_role( + &mut buffer_roles, + count_param, + ComBufferParamRole::InputCount { buffer_param }, + ); + if let Some(actual) = actual_length_param { + set_buffer_role( + &mut buffer_roles, + actual, + ComBufferParamRole::InputActual { buffer_param }, + ); + } + } + ComBufferRelation::CallerCapacity { + capacity_param, + actual_length_param, + .. + } => { + if actual_length_param == Some(capacity_param) { + set_buffer_role( + &mut buffer_roles, + capacity_param, + ComBufferParamRole::CallerCapacityActual { buffer_param }, + ); + } else { + set_buffer_role( + &mut buffer_roles, + capacity_param, + ComBufferParamRole::CallerCapacity { buffer_param }, + ); + if let Some(actual) = actual_length_param { + set_buffer_role( + &mut buffer_roles, + actual, + ComBufferParamRole::CallerActual { buffer_param }, + ); + } + } + } + ComBufferRelation::EnumeratorNext { + capacity_param, + fetched_param, + } => { + set_buffer_role( + &mut buffer_roles, + capacity_param, + ComBufferParamRole::CallerCapacity { buffer_param }, + ); + set_buffer_role( + &mut buffer_roles, + fetched_param, + ComBufferParamRole::CallerActual { buffer_param }, + ); + } + ComBufferRelation::CalleeAllocated { count_param, .. } => { + set_buffer_role( + &mut buffer_roles, + count_param, + ComBufferParamRole::CalleeCount { buffer_param }, + ); + } + } + } + + let mut input_index = 0; + let mut output_index = 0; + let mut arguments = Vec::with_capacity(parameters.len()); + let mut results = Vec::new(); + + match &return_plan { + ComReturnPlan::SemanticHResult | ComReturnPlan::EnumeratorNextHResult => { + results.push(ComResultPlan { + source: ComResultSource::DirectReturn, + typ: None, + success: ComSuccessDisposition::Value, + failure_cleanup: OutputCleanup::None, + }) + } + ComReturnPlan::Direct(typ) => results.push(ComResultPlan { + source: ComResultSource::DirectReturn, + typ: Some(typ.abi.clone()), + success: typ.pointer_output.into(), + failure_cleanup: typ.output_cleanup(), + }), + ComReturnPlan::HResult + | ComReturnPlan::DispatchInvokeHResult(_) + | ComReturnPlan::Void => {} + } + + for (parameter_index, parameter) in parameters.into_iter().enumerate() { + let direction = parameter.direction; + let typ = parameter.typ; + let roles = &buffer_roles[parameter_index]; + let has_logical_input = direction.is_input() && !buffer_roles_hide_input(roles); + let parameter_input_index = has_logical_input.then_some(input_index); + if has_logical_input { + input_index += 1; + } + let native_kind = direction.native_kind(); + let has_native_output = matches!( + native_kind, + ParamKind::Out + | ParamKind::OptionalOut + | ParamKind::InOut + | ParamKind::OutFillArray + ); + let parameter_output_index = has_native_output.then_some(output_index); + if has_native_output { + output_index += 1; + } + let (pointer_output, failure_cleanup) = match direction { + ComParameterDirection::Out | ComParameterDirection::OptionalOut => { + (typ.pointer_output, typ.output_cleanup()) + } + ComParameterDirection::InOut => { + if typ.abi.is_bstr() { + (PointerOutputKind::Bstr, OutputCleanup::BstrFree) + } else { + (PointerOutputKind::Unclassified, OutputCleanup::None) + } + } + ComParameterDirection::CalleeAllocatedBuffer => { + (PointerOutputKind::None, typ.output_cleanup()) + } + ComParameterDirection::OutFill + | ComParameterDirection::In + | ComParameterDirection::InputBuffer + | ComParameterDirection::CallerOutputBuffer => { + (PointerOutputKind::None, OutputCleanup::None) + } + }; + let storage = match direction { + ComParameterDirection::In => ComArgumentStorage::Value, + ComParameterDirection::Out => ComArgumentStorage::OutputPointer, + ComParameterDirection::OptionalOut => ComArgumentStorage::OutputPointer, + ComParameterDirection::InOut => ComArgumentStorage::InOutPointer, + ComParameterDirection::OutFill => ComArgumentStorage::FillBuffer, + ComParameterDirection::InputBuffer => ComArgumentStorage::InputBuffer, + ComParameterDirection::CallerOutputBuffer => ComArgumentStorage::CallerOutputBuffer, + ComParameterDirection::CalleeAllocatedBuffer => { + ComArgumentStorage::CalleeAllocatedBuffer + } + }; + if matches!( + direction, + ComParameterDirection::CallerOutputBuffer + | ComParameterDirection::CalleeAllocatedBuffer + ) { + results.push(ComResultPlan { + source: ComResultSource::Buffer(parameter_index), + typ: None, + success: ComSuccessDisposition::Value, + failure_cleanup, + }); + } else if direction.is_output() && !buffer_roles_hide_output(roles) { + results.push(ComResultPlan { + source: ComResultSource::Parameter(parameter_index), + typ: Some(typ.abi.clone()), + success: pointer_output.into(), + failure_cleanup, + }); + } + arguments.push(ComArgumentPlan { + typ: typ.abi, + direction, + storage, + input_index: parameter_input_index, + output_index: parameter_output_index, + failure_cleanup, + buffer: parameter.buffer, + buffer_roles: buffer_roles[parameter_index].clone(), + }); + } + + let plan = Self { + native, + arguments, + results, + return_plan, + }; + plan.assert_invariants(); + plan + } + + fn assert_invariants(&self) { + let mut expected_input = 0; + let mut expected_output = 0; + for (parameter_index, argument) in self.arguments.iter().enumerate() { + let has_logical_input = + argument.direction.is_input() && !buffer_roles_hide_input(&argument.buffer_roles); + assert_eq!( + argument.input_index, + has_logical_input.then_some(expected_input) + ); + if has_logical_input { + expected_input += 1; + } + let has_native_output = matches!( + argument.direction.native_kind(), + ParamKind::Out + | ParamKind::OptionalOut + | ParamKind::InOut + | ParamKind::OutFillArray + ); + assert_eq!( + argument.output_index, + has_native_output.then_some(expected_output) + ); + if has_native_output { + expected_output += 1; + assert_eq!( + self.native.output_cleanup(parameter_index), + argument.failure_cleanup + ); + } + assert_eq!( + argument.storage, + match argument.direction { + ComParameterDirection::In => ComArgumentStorage::Value, + ComParameterDirection::Out | ComParameterDirection::OptionalOut => { + ComArgumentStorage::OutputPointer + } + ComParameterDirection::InOut => ComArgumentStorage::InOutPointer, + ComParameterDirection::OutFill => ComArgumentStorage::FillBuffer, + ComParameterDirection::InputBuffer => ComArgumentStorage::InputBuffer, + ComParameterDirection::CallerOutputBuffer => { + ComArgumentStorage::CallerOutputBuffer + } + ComParameterDirection::CalleeAllocatedBuffer => { + ComArgumentStorage::CalleeAllocatedBuffer + } + } + ); + assert_eq!(&argument.typ, self.native.parameter_type(parameter_index)); + } + for result in &self.results { + if result.typ.is_none() { + assert!(matches!( + result.source, + ComResultSource::DirectReturn | ComResultSource::Buffer(_) + )); + } + if let ComResultSource::Parameter(index) | ComResultSource::Buffer(index) = + result.source + { + assert_eq!( + result.failure_cleanup, + self.arguments[index].failure_cleanup + ); + } + } + let planned_direct_type = self + .results + .first() + .filter(|result| result.source == ComResultSource::DirectReturn) + .and_then(|result| result.typ.as_ref()); + assert_eq!(planned_direct_type, self.native.direct_return_type()); + let has_direct_result = self + .results + .first() + .is_some_and(|result| result.source == ComResultSource::DirectReturn); + assert_eq!( + has_direct_result, + matches!( + self.return_plan, + ComReturnPlan::SemanticHResult + | ComReturnPlan::EnumeratorNextHResult + | ComReturnPlan::Direct(_) + ) + ); + } + + fn invoke(&self, obj: *mut c_void, args: &[WinRTValue]) -> result::Result> { + if self.native.uses_com_value_path() + || self + .arguments + .iter() + .any(|argument| argument.buffer.is_some()) + || self + .results + .iter() + .any(|result| matches!(result.source, ComResultSource::Buffer(_))) + { + return Err(invalid_argument( + "COM-local struct, union, Automation, or buffer signatures require the COM value invocation path", + )); + } + let values = args.iter().cloned().map(Value::WinRt).collect::>(); + self.invoke_values(obj, &values)? + .into_iter() + .map(|value| match value { + Value::WinRt(value) => Ok(value), + Value::NativeStruct(_) => Err(invalid_argument( + "native POD result requires the COM value invocation path", + )), + Value::NativeUnion(_) + | Value::Bstr(_) + | Value::Variant(_) + | Value::SafeArray(_) + | Value::PropVariant(_) + | Value::DispatchParams(_) + | Value::ExcepInfo(_) => Err(invalid_argument( + "COM-local result requires the COM value invocation path", + )), + Value::Buffer(_) => Err(invalid_argument( + "counted COM buffer result requires the COM value invocation path", + )), + }) + .collect() + } + + fn invoke_values(&self, obj: *mut c_void, args: &[Value]) -> result::Result> { + if matches!(self.return_plan, ComReturnPlan::DispatchInvokeHResult(_)) { + return Err(invalid_argument( + "IDispatch::Invoke captured HRESULT calls require invoke_dispatch()", + )); + } + let expected_args = self + .arguments + .iter() + .filter(|argument| argument.input_index.is_some()) + .count(); + if args.len() != expected_args { + return Err(invalid_argument(format!( + "COM call expects {expected_args} argument(s), received {}", + args.len() + ))); + } + + let mut prepared_buffers = (0..self.arguments.len()).map(|_| None).collect::>(); + for (parameter_index, argument) in self.arguments.iter().enumerate() { + if !matches!( + argument.direction, + ComParameterDirection::InputBuffer | ComParameterDirection::CallerOutputBuffer + ) { + continue; + } + let input_index = argument + .input_index + .expect("borrowed buffer is a logical input"); + let Value::Buffer(value) = &args[input_index] else { + return Err(invalid_argument(format!( + "COM buffer parameter {parameter_index} requires DynCom.buffer() storage" + ))); + }; + let contract = argument + .buffer + .as_ref() + .expect("buffer parameter has a contract"); + let prepared = prepare_borrowed_buffer( + value, + &contract.element, + argument.direction == ComParameterDirection::CallerOutputBuffer, + )?; + if argument.direction == ComParameterDirection::CallerOutputBuffer { + prepared.initialize_output(&contract.element); + } + prepared_buffers[parameter_index] = Some(prepared); + } + + for (buffer_param, argument) in self.arguments.iter().enumerate() { + let Some(ComBufferContract { + relation: ComBufferRelation::EnumeratorNext { fetched_param, .. }, + .. + }) = &argument.buffer + else { + continue; + }; + let buffer = prepared_buffers[buffer_param] + .as_ref() + .expect("enumerator output buffer prepared"); + let capacity = buffer_count( + buffer.byte_len, + &argument.buffer.as_ref().unwrap().element, + BufferCountUnit::Elements, + )?; + if self.arguments[*fetched_param].direction == ComParameterDirection::OptionalOut { + let input_index = self.arguments[*fetched_param] + .input_index + .expect("optional fetched output has a request argument"); + let requested = matches!( + args.get(input_index), + Some(Value::WinRt(WinRTValue::Bool(true))) + ); + if !requested && capacity != 1 { + return Err(invalid_argument( + "IEnum::Next permits a null pceltFetched only when requested capacity is exactly one", + )); + } + } + } + + let mut native_args = Vec::new(); + for (parameter_index, argument) in self.arguments.iter().enumerate() { + if !matches!( + argument.direction.native_kind(), + ParamKind::In | ParamKind::OptionalOut | ParamKind::InOut + ) { + continue; + } + if matches!( + argument.direction, + ComParameterDirection::InputBuffer | ComParameterDirection::CallerOutputBuffer + ) { + let buffer = prepared_buffers[parameter_index] + .as_ref() + .expect("borrowed buffer prepared"); + native_args.push(Value::WinRt(WinRTValue::RawPtr(buffer.ptr.cast()))); + continue; + } + if buffer_roles_hide_input(&argument.buffer_roles) { + let mut derived_count = None; + for role in argument + .buffer_roles + .iter() + .copied() + .filter(|role| role.hides_input()) + { + let buffer_param = role.buffer_param(); + let buffer = prepared_buffers[buffer_param] + .as_ref() + .expect("count source buffer prepared"); + let contract = self.arguments[buffer_param] + .buffer + .as_ref() + .expect("buffer contract"); + let count = buffer_count( + buffer.byte_len, + &contract.element, + relation_unit(&contract.relation), + )?; + if derived_count + .replace(count) + .is_some_and(|existing| existing != count) + { + return Err(invalid_argument( + "COM buffers sharing an authoritative count have different lengths", + )); + } + } + native_args.push(Value::WinRt(count_value( + &argument.typ, + derived_count.expect("hidden count has a source buffer"), + )?)); + continue; + } + native_args.push(args[argument.input_index.expect("visible native input")].clone()); + } + + let native_result = if self.native.uses_com_value_path() + || native_args + .iter() + .any(|value| !matches!(value, Value::WinRt(_) | Value::Buffer(_))) + { + self.native + .call_com_dynamic(obj, &native_args) + .map_err(result::Error::WindowsError) + } else { + let winrt_args = native_args + .iter() + .map(|value| match value { + Value::WinRt(value) => Ok(value.clone()), + Value::NativeStruct(_) => Err(invalid_argument( + "native POD value passed to a non-struct COM method", + )), + Value::NativeUnion(_) + | Value::Bstr(_) + | Value::Variant(_) + | Value::SafeArray(_) + | Value::PropVariant(_) + | Value::DispatchParams(_) + | Value::ExcepInfo(_) => Err(invalid_argument( + "COM-local value passed to a scalar COM method", + )), + Value::Buffer(_) => Err(invalid_argument( + "COM buffer reached the private native-call backend", + )), + }) + .collect::>>()?; + self.native + .call_dynamic(obj, &winrt_args) + .map(|values| values.into_iter().map(Value::WinRt).collect()) + .map_err(result::Error::WindowsError) + }; + let native_values = match native_result { + Ok(values) => values, + Err(error) => { + cleanup_prepared_owning_outputs(&self.arguments, &prepared_buffers); + return Err(error); + } + }; + + let direct_offset = usize::from(matches!( + self.return_plan, + ComReturnPlan::SemanticHResult + | ComReturnPlan::EnumeratorNextHResult + | ComReturnPlan::Direct(_) + )); + let enumerator_hresult = matches!(self.return_plan, ComReturnPlan::EnumeratorNextHResult) + .then(|| match native_values.first() { + Some(Value::WinRt(WinRTValue::HResult(value))) => Ok(*value), + _ => Err(invalid_argument( + "IEnum::Next native call did not preserve its HRESULT", + )), + }) + .transpose()?; + let native_param_result = |parameter_index: usize| -> result::Result<&Value> { + let output_index = self.arguments[parameter_index] + .output_index + .ok_or_else(|| { + invalid_argument("COM buffer relation does not reference an output") + })?; + native_values + .get(direct_offset + output_index) + .ok_or_else(|| invalid_argument("native COM output result is missing")) + }; + + let mut guarded_buffer_allocations = BTreeSet::new(); + if let Some(hresult) = enumerator_hresult.filter(|value| value.is_err()) { + for (parameter_index, argument) in self.arguments.iter().enumerate() { + let Some(contract) = &argument.buffer else { + continue; + }; + if !matches!(contract.relation, ComBufferRelation::EnumeratorNext { .. }) + || contract.element.cleanup == BufferElementCleanup::None + { + continue; + } + let buffer = prepared_buffers[parameter_index] + .as_ref() + .expect("enumerator output buffer prepared"); + let capacity = buffer_count( + buffer.byte_len, + &contract.element, + BufferCountUnit::Elements, + )?; + buffer.cleanup_slots(&contract.element, 0, capacity); + } + self.cleanup_post_call_outputs( + &native_values, + direct_offset, + &guarded_buffer_allocations, + ); + return Err(result::Error::WindowsError( + hresult + .ok() + .expect_err("failed IEnum::Next HRESULT must produce an error"), + )); + } + let processed = (|| -> result::Result> { + let mut values = Vec::with_capacity(self.results.len()); + for result_plan in &self.results { + let value = match result_plan.source { + ComResultSource::DirectReturn => native_values + .first() + .cloned() + .ok_or_else(|| invalid_argument("native COM direct result is missing"))?, + ComResultSource::Parameter(parameter_index) => { + native_param_result(parameter_index)?.clone() + } + ComResultSource::Buffer(parameter_index) => { + let argument = &self.arguments[parameter_index]; + let contract = argument.buffer.as_ref().expect("buffer result contract"); + match &contract.relation { + ComBufferRelation::CallerCapacity { + actual_length_param, + unit, + two_call, + .. + } => { + let buffer = prepared_buffers[parameter_index] + .as_ref() + .expect("caller output buffer prepared"); + let capacity = + buffer_count(buffer.byte_len, &contract.element, *unit)?; + let actual = actual_length_param + .map(|index| count_from_value(native_param_result(index)?)) + .transpose()? + .unwrap_or(capacity); + if actual > capacity && !*two_call { + return Err(invalid_argument(format!( + "COM buffer actual length {actual} exceeds capacity {capacity}" + ))); + } + if contract.element.cleanup != BufferElementCleanup::None { + if actual > capacity { + return Err(invalid_argument(format!( + "COM owning array actual length {actual} exceeds capacity {capacity}" + ))); + } + Value::Buffer(buffer.take_owned_slots( + &contract.element, + actual, + capacity, + )?) + } else { + let copy_count = actual.min(capacity); + let copy_bytes = + count_bytes(copy_count, &contract.element, *unit)?; + let bytes = if copy_bytes == 0 { + Vec::new() + } else { + unsafe { + std::slice::from_raw_parts(buffer.ptr, copy_bytes) + .to_vec() + } + }; + Value::Buffer(ComBufferValue::owned(bytes, actual)) + } + } + ComBufferRelation::EnumeratorNext { fetched_param, .. } => { + let buffer = prepared_buffers[parameter_index] + .as_ref() + .expect("enumerator output buffer prepared"); + let capacity = buffer_count( + buffer.byte_len, + &contract.element, + BufferCountUnit::Elements, + )?; + let fetched_argument = &self.arguments[*fetched_param]; + let fetched_requested = fetched_argument.direction + != ComParameterDirection::OptionalOut + || matches!( + args.get( + fetched_argument + .input_index + .expect("optional fetched request input") + ), + Some(Value::WinRt(WinRTValue::Bool(true))) + ); + let actual = if fetched_requested { + count_from_value(native_param_result(*fetched_param)?)? + } else { + match enumerator_hresult + .expect("enumerator result has an HRESULT") + .0 + { + 0 => 1, + 1 => 0, + value => { + if contract.element.cleanup + != BufferElementCleanup::None + { + buffer.cleanup_slots( + &contract.element, + 0, + capacity, + ); + } + return Err(invalid_argument(format!( + "IEnum::Next returned unexpected success HRESULT 0x{:08X} without pceltFetched", + value as u32 + ))); + } + } + }; + if actual > capacity { + if contract.element.cleanup != BufferElementCleanup::None { + buffer.cleanup_slots(&contract.element, 0, capacity); + } + return Err(invalid_argument(format!( + "IEnum::Next fetched count {actual} exceeds requested capacity {capacity}" + ))); + } + match contract.element.cleanup { + BufferElementCleanup::None => { + let copy_bytes = count_bytes( + actual, + &contract.element, + BufferCountUnit::Elements, + )?; + let bytes = if copy_bytes == 0 { + Vec::new() + } else { + unsafe { + std::slice::from_raw_parts(buffer.ptr, copy_bytes) + .to_vec() + } + }; + Value::Buffer(ComBufferValue::owned(bytes, actual)) + } + BufferElementCleanup::ComRelease + | BufferElementCleanup::BstrFree + | BufferElementCleanup::VariantClear + | BufferElementCleanup::CoTaskMemFree => { + Value::Buffer(buffer.take_owned_slots( + &contract.element, + actual, + capacity, + )?) + } + } + } + ComBufferRelation::CalleeAllocated { + count_param, + unit, + allocator, + } => { + let ptr = + pointer_from_value(native_param_result(parameter_index)?)?; + guarded_buffer_allocations.insert(parameter_index); + let mut allocation = BufferAllocationGuard::new(ptr, *allocator); + let count = count_from_value(native_param_result(*count_param)?)?; + let bytes = count_bytes(count, &contract.element, *unit)?; + if bytes > 0 && ptr.is_null() { + return Err(invalid_argument( + "callee returned a null buffer with a non-zero count", + )); + } + let copied = if bytes == 0 { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(ptr.cast::(), bytes) } + .to_vec() + }; + allocation.free(); + Value::Buffer(ComBufferValue::owned(copied, count)) + } + ComBufferRelation::Input { .. } => { + return Err(invalid_argument( + "input-only COM buffer cannot produce a buffer result", + )); + } + } + } + }; + values.push(value); + } + Ok(values) + })(); + if processed.is_err() { + cleanup_prepared_owning_outputs(&self.arguments, &prepared_buffers); + self.cleanup_post_call_outputs( + &native_values, + direct_offset, + &guarded_buffer_allocations, + ); + } + processed + } + + fn invoke_dispatch( + &self, + obj: *mut c_void, + args: &[Value], + ) -> result::Result { + let ComReturnPlan::DispatchInvokeHResult(plan) = &self.return_plan else { + return Err(invalid_argument( + "method does not use the IDispatch::Invoke captured HRESULT convention", + )); + }; + if self + .arguments + .iter() + .any(|argument| argument.buffer.is_some()) + { + return Err(invalid_argument( + "IDispatch::Invoke captured HRESULT calls cannot use buffer plans", + )); + } + + let captured = self + .native + .call_com_dynamic_captured(obj, args) + .map_err(result::Error::WindowsError)?; + let mut outputs = captured.outputs; + let result = match outputs[plan.result_output_index].take() { + Some(crate::native_call::NativeCallValue::Variant(value)) => Some(value), + None => None, + Some(_) => { + return Err(invalid_argument( + "IDispatch::Invoke result output was not a VARIANT", + )); + } + }; + let excep_info = match outputs[plan.excep_info_output_index].take() { + Some(crate::native_call::NativeCallValue::ExcepInfo(value)) => Some(value), + None => None, + Some(_) => { + return Err(invalid_argument( + "IDispatch::Invoke exception output was not EXCEPINFO", + )); + } + }; + let arg_err = match outputs[plan.arg_err_output_index].take() { + Some(crate::native_call::NativeCallValue::WinRt(WinRTValue::U32(value))) => Some(value), + None => None, + Some(_) => { + return Err(invalid_argument( + "IDispatch::Invoke argument error output was not UINT", + )); + } + }; + if outputs.into_iter().any(|value| value.is_some()) { + return Err(invalid_argument( + "IDispatch::Invoke captured an unexpected native output", + )); + } + + Ok(DispatchInvokeResult { + hresult: captured.hresult, + result, + excep_info, + arg_err, + finalization_error: captured.finalization_error, + }) + } + + fn cleanup_post_call_outputs( + &self, + native_values: &[Value], + direct_offset: usize, + guarded_parameters: &BTreeSet, + ) { + let mut cleaned = BTreeSet::new(); + let mut direct_cleaned = false; + for result in &self.results { + let parameter_index = match result.source { + ComResultSource::Parameter(index) | ComResultSource::Buffer(index) => index, + ComResultSource::DirectReturn => { + if direct_cleaned || result.failure_cleanup == OutputCleanup::None { + continue; + } + direct_cleaned = true; + let Some(value) = native_values.first() else { + continue; + }; + let Ok(ptr) = pointer_from_value(value) else { + continue; + }; + unsafe { result.failure_cleanup.cleanup(ptr) }; + continue; + } + }; + if guarded_parameters.contains(¶meter_index) || !cleaned.insert(parameter_index) { + continue; + } + let cleanup = self.arguments[parameter_index].failure_cleanup; + if cleanup == OutputCleanup::None { + continue; + } + let Some(output_index) = self.arguments[parameter_index].output_index else { + continue; + }; + let Some(value) = native_values.get(direct_offset + output_index) else { + continue; + }; + let Ok(ptr) = pointer_from_value(value) else { + continue; + }; + unsafe { cleanup.cleanup(ptr) }; + } + } + + fn invoke_with_output_kinds( + &self, + obj: *mut c_void, + args: &[WinRTValue], + ) -> result::Result> { + let values = self.invoke(obj, args)?; + if values.len() != self.results.len() { + return Err(invalid_argument(format!( + "COM result plan mismatch: native call returned {} value(s), plan describes {}", + values.len(), + self.results.len() + ))); + } + Ok(values + .into_iter() + .zip( + self.results + .iter() + .map(|result| result.success.pointer_output_kind()), + ) + .collect()) + } + + fn invoke_values_with_output_kinds( + &self, + obj: *mut c_void, + args: &[Value], + ) -> result::Result> { + let values = self.invoke_values(obj, args)?; + if values.len() != self.results.len() { + return Err(invalid_argument(format!( + "COM result plan mismatch: native call returned {} value(s), plan describes {}", + values.len(), + self.results.len() + ))); + } + Ok(values + .into_iter() + .zip( + self.results + .iter() + .map(|result| result.success.pointer_output_kind()), + ) + .collect()) + } +} + +fn cleanup_prepared_owning_outputs( + arguments: &[ComArgumentPlan], + prepared_buffers: &[Option>], +) { + for (index, argument) in arguments.iter().enumerate() { + let Some(contract) = &argument.buffer else { + continue; + }; + if argument.direction != ComParameterDirection::CallerOutputBuffer + || contract.element.cleanup == BufferElementCleanup::None + { + continue; + } + let Some(buffer) = prepared_buffers[index].as_ref() else { + continue; + }; + let Ok(capacity) = buffer_count( + buffer.byte_len, + &contract.element, + relation_unit(&contract.relation), + ) else { + continue; + }; + buffer.cleanup_slots(&contract.element, 0, capacity); + } +} + +fn set_buffer_role(roles: &mut [Vec], index: usize, role: ComBufferParamRole) { + roles[index].push(role); +} + +fn buffer_roles_hide_input(roles: &[ComBufferParamRole]) -> bool { + roles.iter().any(|role| role.hides_input()) +} + +fn buffer_roles_hide_output(roles: &[ComBufferParamRole]) -> bool { + !roles.is_empty() && roles.iter().all(|role| role.hides_output()) +} + +#[derive(Debug)] +struct PreparedBuffer<'a> { + ptr: *mut u8, + byte_len: usize, + element_kind: BufferElementKind, + _owned_input: Option, + _caller_output_guard: Option>>, +} + +enum PreparedOwnedInput { + Bstr(Vec), + Variant(crate::com::automation::VariantArrayCopyValue), +} + +impl std::fmt::Debug for PreparedOwnedInput { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::Bstr(_) => "PreparedOwnedInput::Bstr", + Self::Variant(_) => "PreparedOwnedInput::Variant", + }) + } +} + +impl PreparedBuffer<'_> { + fn initialize_output(&self, element: &BufferElementPlan) { + debug_assert_eq!(self.element_kind, element.kind); + if self.byte_len == 0 { + return; + } + match element.cleanup { + BufferElementCleanup::VariantClear => { + for index in 0..(self.byte_len / element.size) { + unsafe { + crate::com::automation::initialize_variant_slot( + self.ptr.add(index * element.size).cast(), + ) + }; + } + } + BufferElementCleanup::None + | BufferElementCleanup::ComRelease + | BufferElementCleanup::BstrFree + | BufferElementCleanup::CoTaskMemFree => unsafe { + std::ptr::write_bytes(self.ptr, 0, self.byte_len) + }, + } + } + + fn cleanup_slots(&self, element: &BufferElementPlan, start: usize, end: usize) { + for index in start..end { + let slot = unsafe { self.ptr.add(index * element.size) }; + match element.cleanup { + BufferElementCleanup::None => {} + BufferElementCleanup::ComRelease + | BufferElementCleanup::BstrFree + | BufferElementCleanup::CoTaskMemFree => { + let slot = slot.cast::<*mut c_void>(); + let value = unsafe { slot.read() }; + if !value.is_null() { + unsafe { + match element.cleanup { + BufferElementCleanup::ComRelease => { + OutputCleanup::ComRelease.cleanup(value) + } + BufferElementCleanup::BstrFree => { + OutputCleanup::BstrFree.cleanup(value) + } + BufferElementCleanup::CoTaskMemFree => { + OutputCleanup::CoTaskMemFree.cleanup(value) + } + BufferElementCleanup::None | BufferElementCleanup::VariantClear => { + unreachable!() + } + } + }; + unsafe { slot.write(std::ptr::null_mut()) }; + } + } + BufferElementCleanup::VariantClear => unsafe { + crate::com::automation::clear_variant_slot(slot.cast()); + crate::com::automation::initialize_variant_slot(slot.cast()); + }, + } + } + } + + fn take_owned_slots( + &self, + element: &BufferElementPlan, + actual: usize, + capacity: usize, + ) -> result::Result { + match element.cleanup { + BufferElementCleanup::ComRelease => self + .take_com_slots(element, actual, capacity) + .map(ComBufferValue::owned_com), + BufferElementCleanup::BstrFree => self + .take_bstr_slots(element, actual, capacity) + .map(ComBufferValue::owned_strings), + BufferElementCleanup::VariantClear => self + .take_variant_slots(element, actual, capacity) + .map(ComBufferValue::owned_variants), + BufferElementCleanup::CoTaskMemFree => self + .take_wide_string_slots(element, actual, capacity) + .map(ComBufferValue::owned_strings), + BufferElementCleanup::None => Err(invalid_argument( + "plain COM buffers do not use owning element transfer", + )), + } + } + + fn take_com_slots( + &self, + element: &BufferElementPlan, + fetched: usize, + capacity: usize, + ) -> result::Result> { + let mut values = Vec::with_capacity(fetched); + for index in 0..fetched { + let slot = unsafe { self.ptr.add(index * element.size).cast::<*mut c_void>() }; + let value = unsafe { slot.read() }; + if value.is_null() { + self.cleanup_slots(element, index, capacity); + return Err(invalid_argument( + "COM array returned a null interface pointer within the initialized range", + )); + } + unsafe { slot.write(std::ptr::null_mut()) }; + values.push(WinRTValue::Object(unsafe { IUnknown::from_raw(value) })); + } + self.cleanup_slots(element, fetched, capacity); + Ok(values) + } + + fn take_bstr_slots( + &self, + element: &BufferElementPlan, + actual: usize, + capacity: usize, + ) -> result::Result> { + let mut values = Vec::with_capacity(actual); + for index in 0..actual { + let slot = unsafe { self.ptr.add(index * element.size).cast::<*mut u16>() }; + let raw = unsafe { slot.read() }; + if raw.is_null() { + values.push(String::new()); + continue; + } + let value = unsafe { windows_core::BSTR::from_raw(raw.cast_const()) }; + values.push(value.to_string()); + unsafe { slot.write(std::ptr::null_mut()) }; + } + self.cleanup_slots(element, actual, capacity); + Ok(values) + } + + fn take_variant_slots( + &self, + element: &BufferElementPlan, + actual: usize, + capacity: usize, + ) -> result::Result> { + for index in 0..actual { + let slot = unsafe { self.ptr.add(index * element.size) }; + if let Err(error) = + unsafe { crate::com::automation::validate_variant_slot(slot.cast()) } + { + self.cleanup_slots(element, 0, capacity); + return Err(error); + } + } + let mut values = Vec::with_capacity(actual); + for index in 0..actual { + let slot = unsafe { self.ptr.add(index * element.size) }; + values.push(unsafe { crate::com::automation::take_variant_slot(slot.cast()) }?); + } + self.cleanup_slots(element, actual, capacity); + Ok(values) + } + + fn take_wide_string_slots( + &self, + element: &BufferElementPlan, + actual: usize, + capacity: usize, + ) -> result::Result> { + let mut values = Vec::with_capacity(actual); + for index in 0..actual { + let slot = unsafe { self.ptr.add(index * element.size).cast::<*mut u16>() }; + let raw = unsafe { slot.read() }; + if raw.is_null() { + self.cleanup_slots(element, 0, capacity); + return Err(invalid_argument( + "COM string array returned a null pointer within the initialized range", + )); + } + let value = unsafe { windows_core::PWSTR(raw).to_string() } + .map_err(|error| invalid_argument(format!("invalid UTF-16 COM string: {error}"))); + match value { + Ok(value) => values.push(value), + Err(error) => { + self.cleanup_slots(element, 0, capacity); + return Err(error); + } + } + } + self.cleanup_slots(element, 0, capacity); + Ok(values) + } +} + +fn prepare_borrowed_buffer<'a>( + value: &'a ComBufferValue, + element: &BufferElementPlan, + require_writable: bool, +) -> result::Result> { + let mut caller_output_guard = None; + let mut owned_input = None; + let ( + ptr, + byte_len, + source_element_size, + raw_bytes, + writable, + native_layout_name, + string_encoding, + source_element_kind, + ) = match &value.storage { + ComBufferStorage::CallerOutput { + blocks, + byte_len, + source_element_size, + native_layout_name, + element_kind, + } => { + let mut guard = blocks.try_lock().map_err(|error| match error { + TryLockError::WouldBlock => invalid_argument( + "caller-output COM storage cannot be aliased or used concurrently", + ), + TryLockError::Poisoned(_) => { + invalid_argument("caller-output COM storage lock is poisoned") + } + })?; + let ptr = guard.as_mut_ptr().cast::(); + caller_output_guard = Some(guard); + ( + ptr, + *byte_len, + *source_element_size, + false, + true, + native_layout_name.as_deref(), + None, + Some(*element_kind), + ) + } + ComBufferStorage::InterfaceArray { iid, pointers, .. } => ( + pointers.as_ptr().cast_mut().cast(), + pointers.len() * size_of::<*mut c_void>(), + size_of::<*mut c_void>(), + false, + false, + None, + None, + Some(BufferElementKind::ComInterface(*iid)), + ), + ComBufferStorage::BstrArray { values } => { + let mut allocated = Vec::with_capacity(values.len()); + for value in values { + let utf16 = value.encode_utf16().collect::>(); + let bstr = unsafe { windows::Win32::Foundation::SysAllocStringLen(Some(&utf16)) }; + if bstr.is_empty() && !utf16.is_empty() { + return Err(result::Error::WindowsError( + windows_core::Error::from_hresult(windows_core::HRESULT( + 0x8007000Eu32 as i32, + )), + )); + } + allocated.push(bstr); + } + owned_input = Some(PreparedOwnedInput::Bstr(allocated)); + let PreparedOwnedInput::Bstr(values) = + owned_input.as_mut().expect("BSTR input storage") + else { + unreachable!() + }; + ( + values.as_mut_ptr().cast(), + values.len() * size_of::<*mut c_void>(), + size_of::<*mut c_void>(), + false, + false, + None, + None, + Some(BufferElementKind::Bstr), + ) + } + ComBufferStorage::VariantArray { values } => { + owned_input = Some(PreparedOwnedInput::Variant( + crate::com::automation::VariantArrayCopyValue::new(values)?, + )); + let PreparedOwnedInput::Variant(values) = + owned_input.as_mut().expect("VARIANT input storage") + else { + unreachable!() + }; + ( + values.as_mut_ptr().cast(), + values.len() * crate::com::automation::variant_size(), + crate::com::automation::variant_size(), + false, + false, + None, + None, + Some(BufferElementKind::Variant), + ) + } + _ => { + let parts = value.borrowed_parts()?; + let source_element_kind = match parts.6 { + Some(encoding) => Some(BufferElementKind::StringPointer(encoding)), + None => Some(BufferElementKind::Plain), + }; + ( + parts.0, + parts.1, + parts.2, + parts.3, + parts.4, + parts.5, + parts.6, + source_element_kind, + ) + } + }; + if require_writable && !writable { + return Err(invalid_argument( + "caller-owned COM output buffers require writable backing storage", + )); + } + let _ = string_encoding; + if source_element_kind != Some(element.kind) { + return Err(invalid_argument( + "COM caller-output storage element contract does not match the method", + )); + } + if !raw_bytes && source_element_size != element.size { + return Err(invalid_argument(format!( + "COM typed buffer element width mismatch: expected {}, received {}", + element.size, source_element_size + ))); + } + if native_layout_name != element.native_layout_name.as_deref() { + return Err(invalid_argument( + "COM native struct buffer element layout identity mismatch", + )); + } + if byte_len % element.size != 0 { + return Err(invalid_argument(format!( + "COM buffer byte length {byte_len} is not a multiple of element width {}", + element.size + ))); + } + if byte_len > 0 && ptr as usize % element.alignment != 0 { + return Err(invalid_argument(format!( + "COM buffer backing address is not aligned to {} bytes", + element.alignment + ))); + } + Ok(PreparedBuffer { + ptr, + byte_len, + element_kind: element.kind, + _owned_input: owned_input, + _caller_output_guard: caller_output_guard, + }) +} + +fn relation_unit(relation: &ComBufferRelation) -> BufferCountUnit { + match relation { + ComBufferRelation::Input { unit, .. } + | ComBufferRelation::CallerCapacity { unit, .. } + | ComBufferRelation::CalleeAllocated { unit, .. } => *unit, + ComBufferRelation::EnumeratorNext { .. } => BufferCountUnit::Elements, + } +} + +fn buffer_count( + byte_len: usize, + element: &BufferElementPlan, + unit: BufferCountUnit, +) -> result::Result { + match unit { + BufferCountUnit::Elements => { + if byte_len % element.size != 0 { + return Err(invalid_argument( + "COM buffer length does not contain a whole number of elements", + )); + } + Ok(byte_len / element.size) + } + BufferCountUnit::Bytes => Ok(byte_len), + } +} + +fn count_bytes( + count: usize, + element: &BufferElementPlan, + unit: BufferCountUnit, +) -> result::Result { + let bytes = match unit { + BufferCountUnit::Elements => count + .checked_mul(element.size) + .ok_or_else(|| invalid_argument("COM buffer byte length overflow")), + BufferCountUnit::Bytes => { + if element.size != 1 { + return Err(invalid_argument( + "byte-counted COM buffers currently require one-byte elements", + )); + } + Ok(count) + } + }?; + const MAX_PROJECTED_BUFFER_BYTES: usize = i32::MAX as usize; + if bytes > isize::MAX as usize || bytes > MAX_PROJECTED_BUFFER_BYTES { + return Err(invalid_argument( + "COM buffer byte length exceeds the supported projected Buffer size", + )); + } + Ok(bytes) +} + +fn count_value(typ: &ParameterType, value: usize) -> result::Result { + let ParameterType::WinRT(typ) = typ else { + return Err(invalid_argument( + "COM buffer count parameters must use integer scalar ABI types", + )); + }; + match typ.kind() { + TypeKind::I8 => i8::try_from(value) + .map(WinRTValue::I8) + .map_err(|_| invalid_argument("COM buffer count does not fit i8")), + TypeKind::U8 => u8::try_from(value) + .map(WinRTValue::U8) + .map_err(|_| invalid_argument("COM buffer count does not fit u8")), + TypeKind::I16 => i16::try_from(value) + .map(WinRTValue::I16) + .map_err(|_| invalid_argument("COM buffer count does not fit i16")), + TypeKind::U16 | TypeKind::Char16 => u16::try_from(value) + .map(WinRTValue::U16) + .map_err(|_| invalid_argument("COM buffer count does not fit u16")), + TypeKind::I32 => i32::try_from(value) + .map(WinRTValue::I32) + .map_err(|_| invalid_argument("COM buffer count does not fit i32")), + TypeKind::U32 => u32::try_from(value) + .map(WinRTValue::U32) + .map_err(|_| invalid_argument("COM buffer count does not fit u32")), + TypeKind::I64 => i64::try_from(value) + .map(WinRTValue::I64) + .map_err(|_| invalid_argument("COM buffer count does not fit i64")), + TypeKind::U64 => u64::try_from(value) + .map(WinRTValue::U64) + .map_err(|_| invalid_argument("COM buffer count does not fit u64")), + _ => Err(invalid_argument( + "COM buffer count parameters must use an integer scalar ABI type", + )), + } +} + +fn count_from_value(value: &Value) -> result::Result { + let Value::WinRt(value) = value else { + return Err(invalid_argument( + "COM buffer count output must use an integer scalar ABI type", + )); + }; + let value = match value { + WinRTValue::I8(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count cannot be negative"))?, + WinRTValue::U8(value) => usize::from(*value), + WinRTValue::I16(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count cannot be negative"))?, + WinRTValue::U16(value) => usize::from(*value), + WinRTValue::I32(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count cannot be negative"))?, + WinRTValue::U32(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count does not fit usize"))?, + WinRTValue::I64(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count cannot be negative or exceed usize"))?, + WinRTValue::U64(value) => usize::try_from(*value) + .map_err(|_| invalid_argument("COM buffer count does not fit usize"))?, + _ => { + return Err(invalid_argument( + "COM buffer count output must use an integer scalar ABI type", + )); + } + }; + Ok(value) +} + +fn pointer_from_value(value: &Value) -> result::Result<*mut c_void> { + match value { + Value::WinRt(WinRTValue::RawPtr(ptr)) => Ok(*ptr), + Value::WinRt(WinRTValue::Null) => Ok(std::ptr::null_mut()), + _ => Err(invalid_argument( + "callee-allocated COM buffer output did not return a native pointer", + )), + } +} + +struct BufferAllocationGuard { + ptr: *mut c_void, + allocator: BufferAllocator, +} + +impl BufferAllocationGuard { + fn new(ptr: *mut c_void, allocator: BufferAllocator) -> Self { + Self { ptr, allocator } + } + + fn free(&mut self) { + if self.ptr.is_null() { + return; + } + match self.allocator { + BufferAllocator::CoTaskMem => unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(self.ptr)); + }, + } + self.ptr = std::ptr::null_mut(); + } +} + +impl Drop for BufferAllocationGuard { + fn drop(&mut self) { + self.free(); + } +} + +// Safety: a ComCallPlan is fully built before publication and remains +// immutable. NativeMethod invokes libffi's CIF only through shared references; +// ffi_call treats the prepared CIF and its type graph as read-only. +unsafe impl Send for ComCallPlan {} +unsafe impl Sync for ComCallPlan {} + +#[derive(Debug, Clone)] +pub struct MethodSignature { + table: Arc, + parameters: Vec, + return_plan: ComReturnPlan, + enumerator_next_vtable_index: Option, +} + +impl MethodSignature { + pub fn new(table: &std::sync::Arc) -> Self { + Self { + table: Arc::clone(table), + parameters: Vec::new(), + return_plan: ComReturnPlan::HResult, + enumerator_next_vtable_index: None, + } + } + + pub fn add_in(mut self, typ: Type) -> Self { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::In, + typ, + buffer: None, + }); + self + } + + pub fn add_out(mut self, typ: Type) -> Self { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::Out, + typ, + buffer: None, + }); + self + } + + pub fn add_optional_out(mut self, typ: Type) -> Self { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::OptionalOut, + typ, + buffer: None, + }); + self + } + + pub fn add_in_out(mut self, typ: Type) -> Self { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::InOut, + typ, + buffer: None, + }); + self + } + + pub fn add_out_fill(mut self, typ: Type) -> Self { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::OutFill, + typ, + buffer: None, + }); + self + } + + pub fn add_input_buffer( + mut self, + element_type: Type, + count_param: usize, + actual_length_param: Option, + unit: BufferCountUnit, + ) -> result::Result { + let element = BufferElementPlan::from_type(&element_type)?; + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::InputBuffer, + typ: Type::pointer(), + buffer: Some(ComBufferContract { + element, + relation: ComBufferRelation::Input { + count_param, + actual_length_param, + unit, + }, + }), + }); + Ok(self) + } + + pub fn add_input_string_array( + mut self, + encoding: StringEncoding, + count_param: usize, + ) -> result::Result { + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::InputBuffer, + typ: Type::pointer(), + buffer: Some(ComBufferContract { + element: BufferElementPlan::string_pointer(encoding), + relation: ComBufferRelation::Input { + count_param, + actual_length_param: None, + unit: BufferCountUnit::Elements, + }, + }), + }); + Ok(self) + } + + pub fn add_caller_output_buffer( + mut self, + element_type: Type, + capacity_param: usize, + actual_length_param: Option, + unit: BufferCountUnit, + two_call: bool, + ) -> result::Result { + let element = BufferElementPlan::from_type(&element_type)?; + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::CallerOutputBuffer, + typ: Type::pointer(), + buffer: Some(ComBufferContract { + element, + relation: ComBufferRelation::CallerCapacity { + capacity_param, + actual_length_param, + unit, + two_call, + }, + }), + }); + Ok(self) + } + + pub fn add_enumerator_next_buffer( + mut self, + element_type: Type, + capacity_param: usize, + fetched_param: usize, + ) -> result::Result { + let element = BufferElementPlan::from_enumerator_type(&element_type)?; + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::CallerOutputBuffer, + typ: Type::pointer(), + buffer: Some(ComBufferContract { + element, + relation: ComBufferRelation::EnumeratorNext { + capacity_param, + fetched_param, + }, + }), + }); + Ok(self) + } + + pub fn add_callee_allocated_buffer( + mut self, + element_type: Type, + count_param: usize, + unit: BufferCountUnit, + allocator: BufferAllocator, + ) -> result::Result { + let element = BufferElementPlan::from_type(&element_type)?; + let typ = match allocator { + BufferAllocator::CoTaskMem => Type::co_task_mem_pointer(), + }; + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::CalleeAllocatedBuffer, + typ, + buffer: Some(ComBufferContract { + element, + relation: ComBufferRelation::CalleeAllocated { + count_param, + unit, + allocator, + }, + }), + }); + Ok(self) + } + + pub fn returns(mut self, typ: Type) -> Self { + assert!( + typ.supports_direct_return(), + "direct native returns currently support scalars, enums, and pointers" + ); + self.return_plan = ComReturnPlan::Direct(typ); + self + } + + pub fn returns_void(mut self) -> Self { + self.return_plan = ComReturnPlan::Void; + self + } + + pub fn preserve_hresult(mut self) -> Self { + self.return_plan = ComReturnPlan::SemanticHResult; + self + } + + pub fn preserve_enumerator_next_hresult(mut self) -> Self { + self.enumerator_next_vtable_index = Some(3); + self.return_plan = ComReturnPlan::EnumeratorNextHResult; + self + } + + pub fn preserve_enumerator_next_hresult_at(mut self, vtable_index: usize) -> Self { + self.enumerator_next_vtable_index = Some(vtable_index); + self.return_plan = ComReturnPlan::EnumeratorNextHResult; + self + } + + pub fn capture_dispatch_invoke_hresult(mut self) -> Self { + self.return_plan = ComReturnPlan::DispatchInvokeHResult(CapturedHResultPlan { + result_output_index: 0, + excep_info_output_index: 1, + arg_err_output_index: 2, + }); + self + } + + fn validate_registration( + &self, + interface_iid: GUID, + method_name: &str, + vtable_index: usize, + ) -> result::Result<()> { + const IID_IDISPATCH: GUID = GUID::from_u128(0x00020400_0000_0000_c000_000000000046); + if matches!(self.return_plan, ComReturnPlan::EnumeratorNextHResult) { + let exact_contract = interface_iid != GUID::zeroed() + && method_name == "Next" + && self.enumerator_next_vtable_index == Some(vtable_index) + && self.parameters.len() == 3 + && self.parameters[0].direction == ComParameterDirection::In + && self.parameters[1].direction == ComParameterDirection::CallerOutputBuffer + && matches!( + self.parameters[2].direction, + ComParameterDirection::Out | ComParameterDirection::OptionalOut + ) + && matches!( + &self.parameters[0].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U32) + ) + && matches!( + &self.parameters[2].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U32) + ) + && matches!( + self.parameters[1] + .buffer + .as_ref() + .map(|contract| &contract.relation), + Some(ComBufferRelation::EnumeratorNext { + capacity_param: 0, + fetched_param: 2, + }) + ); + return exact_contract.then_some(()).ok_or_else(|| { + invalid_argument( + "enumerator HRESULT convention is restricted to the exact IEnum*::Next ABI shape", + ) + }); + } + if !matches!(self.return_plan, ComReturnPlan::DispatchInvokeHResult(_)) { + return Ok(()); + } + + let direction = |index: usize| self.parameters[index].direction; + let exact_contract = interface_iid == IID_IDISPATCH + && method_name == "Invoke" + && vtable_index == 6 + && self.parameters.len() == 8 + && self + .parameters + .iter() + .all(|parameter| parameter.buffer.is_none()) + && (0..5).all(|index| direction(index) == ComParameterDirection::In) + && (5..8).all(|index| direction(index) == ComParameterDirection::OptionalOut) + && matches!( + &self.parameters[0].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::I32) + ) + && matches!(&self.parameters[1].typ.abi, ParameterType::Pointer) + && matches!( + &self.parameters[2].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U32) + ) + && matches!( + &self.parameters[3].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U16) + ) + && self.parameters[4].typ.abi.is_dispatch_params() + && self.parameters[5].typ.abi.is_variant() + && self.parameters[6].typ.abi.is_excep_info() + && matches!( + &self.parameters[7].typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U32) + ); + if exact_contract { + Ok(()) + } else { + Err(invalid_argument( + "captured HRESULT convention is restricted to the exact IDispatch::Invoke ABI contract", + )) + } + } + + fn build(self, vtable_index: usize) -> result::Result { + validate_automation_contracts(&self.parameters, &self.return_plan)?; + validate_buffer_contracts(&self.parameters)?; + let enumerator_buffers = self + .parameters + .iter() + .filter(|parameter| { + parameter.buffer.as_ref().is_some_and(|contract| { + matches!(contract.relation, ComBufferRelation::EnumeratorNext { .. }) + }) + }) + .count(); + if matches!(self.return_plan, ComReturnPlan::EnumeratorNextHResult) { + if enumerator_buffers != 1 { + return Err(invalid_argument( + "enumerator HRESULT calls require exactly one EnumeratorNext buffer", + )); + } + } else if enumerator_buffers != 0 { + return Err(invalid_argument( + "EnumeratorNext buffers require the enumerator HRESULT return convention", + )); + } + let native_parameters = self + .parameters + .iter() + .map(|parameter| { + let cleanup = match parameter.direction { + ComParameterDirection::Out + | ComParameterDirection::OptionalOut + | ComParameterDirection::CalleeAllocatedBuffer => { + parameter.typ.output_cleanup() + } + ComParameterDirection::InOut if parameter.typ.abi.is_bstr() => { + OutputCleanup::BstrFree + } + ComParameterDirection::In + | ComParameterDirection::InOut + | ComParameterDirection::OutFill + | ComParameterDirection::InputBuffer + | ComParameterDirection::CallerOutputBuffer => OutputCleanup::None, + }; + ( + parameter.direction.native_kind(), + parameter.typ.abi.clone(), + cleanup, + ) + }) + .collect(); + let native_return = match &self.return_plan { + ComReturnPlan::HResult => MethodReturn::HResult, + ComReturnPlan::SemanticHResult => MethodReturn::SemanticHResult, + ComReturnPlan::EnumeratorNextHResult => MethodReturn::PreservedHResult, + ComReturnPlan::DispatchInvokeHResult(plan) => MethodReturn::CapturedHResult(*plan), + ComReturnPlan::Void => MethodReturn::Void, + ComReturnPlan::Direct(typ) => MethodReturn::Value { + typ: typ.abi.clone(), + cleanup: typ.output_cleanup(), + }, + }; + let native = + lower_completed_method(&self.table, vtable_index, native_parameters, native_return); + Ok(RegisteredMethod { + plan: ComCallPlan::new(native, self.parameters, self.return_plan), + }) + } +} + +fn validate_automation_contracts( + parameters: &[ComParameterSpec], + return_plan: &ComReturnPlan, +) -> result::Result<()> { + for parameter in parameters { + if parameter.typ.abi.native_union_layout().is_some() + && parameter.direction != ComParameterDirection::In + { + return Err(invalid_argument( + "native union pointers are input-only because outputs lack a proven active-field contract", + )); + } + if parameter.typ.abi.is_dispatch_params() + && parameter.direction != ComParameterDirection::In + { + return Err(invalid_argument("DISPPARAMS is input-only")); + } + if parameter.typ.abi.is_excep_info() + && !matches!( + parameter.direction, + ComParameterDirection::Out | ComParameterDirection::OptionalOut + ) + { + return Err(invalid_argument("EXCEPINFO is output-only")); + } + if parameter.typ.abi.is_excep_info() + && !matches!( + return_plan, + ComReturnPlan::HResult + | ComReturnPlan::SemanticHResult + | ComReturnPlan::DispatchInvokeHResult(_) + ) + { + return Err(invalid_argument( + "EXCEPINFO outputs require an HRESULT return convention", + )); + } + if parameter.typ.abi.is_variant() + || parameter.typ.abi.is_safe_array() + || parameter.typ.abi.is_prop_variant() + { + if !matches!( + parameter.direction, + ComParameterDirection::In + | ComParameterDirection::Out + | ComParameterDirection::OptionalOut + ) { + return Err(invalid_argument( + "Automation values support only explicit input or owned output parameters; BYREF/InOut and buffer combinations are rejected", + )); + } + } + if parameter.typ.abi.is_nullable_safe_array() + && parameter.direction != ComParameterDirection::Out + { + return Err(invalid_argument( + "nullable SAFEARRAY is supported only for an exact documented owned output", + )); + } + if parameter.typ.abi.is_variant_by_value() + && parameter.direction != ComParameterDirection::In + { + return Err(invalid_argument( + "by-value VARIANT is input-only; pointer output and InOut contracts remain unsupported", + )); + } + } + Ok(()) +} + +fn validate_buffer_contracts(parameters: &[ComParameterSpec]) -> result::Result<()> { + let mut related = vec![Vec::new(); parameters.len()]; + for (buffer_index, parameter) in parameters.iter().enumerate() { + let Some(contract) = ¶meter.buffer else { + continue; + }; + if contract.element.cleanup != BufferElementCleanup::None { + let supported = matches!( + (¶meter.direction, &contract.relation), + ( + ComParameterDirection::InputBuffer, + ComBufferRelation::Input { + unit: BufferCountUnit::Elements, + .. + } + ) | ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::CallerCapacity { + unit: BufferCountUnit::Elements, + two_call: false, + .. + } + ) | ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::EnumeratorNext { .. } + ) + ); + if !supported { + return Err(invalid_argument( + "owned COM buffer elements require an authoritative initialized range and per-element cleanup", + )); + } + } + if relation_unit(&contract.relation) == BufferCountUnit::Bytes && contract.element.size != 1 + { + return Err(invalid_argument( + "byte-counted COM buffers require one-byte elements", + )); + } + if matches!(contract.element.kind, BufferElementKind::StringPointer(_)) + && !matches!( + (¶meter.direction, &contract.relation), + ( + ComParameterDirection::InputBuffer, + ComBufferRelation::Input { + actual_length_param: None, + unit: BufferCountUnit::Elements, + .. + } + ) + ) + { + return Err(invalid_argument( + "COM string pointer arrays must be borrowed, element-counted inputs", + )); + } + if matches!( + contract.element.kind, + BufferElementKind::CoTaskMemWideString + ) && !matches!( + (¶meter.direction, &contract.relation), + ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::EnumeratorNext { .. } + ) + ) { + return Err(invalid_argument( + "CoTaskMem string array elements require the exact EnumeratorNext contract", + )); + } + let mut contract_indices = BTreeSet::new(); + for index in contract.relation.related_params() { + if !contract_indices.insert(index) { + continue; + } + if index >= parameters.len() || index == buffer_index { + return Err(invalid_argument( + "COM buffer count relationship references an invalid parameter index", + )); + } + if !related[index].contains(&buffer_index) { + related[index].push(buffer_index); + } + validate_count_type(¶meters[index].typ)?; + } + match (¶meter.direction, &contract.relation) { + ( + ComParameterDirection::InputBuffer, + ComBufferRelation::Input { + count_param, + actual_length_param, + .. + }, + ) => { + require_direction(parameters, *count_param, &[ComParameterDirection::In])?; + if let Some(actual) = actual_length_param { + require_direction(parameters, *actual, &[ComParameterDirection::Out])?; + } + } + ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::CallerCapacity { + capacity_param, + actual_length_param, + two_call, + .. + }, + ) => { + if actual_length_param == &Some(*capacity_param) { + require_direction( + parameters, + *capacity_param, + &[ComParameterDirection::InOut], + )?; + } else { + require_direction(parameters, *capacity_param, &[ComParameterDirection::In])?; + if let Some(actual) = actual_length_param { + require_direction(parameters, *actual, &[ComParameterDirection::Out])?; + } + } + if *two_call && actual_length_param.is_none() { + return Err(invalid_argument( + "two-call COM buffer sizing requires an actual-length output", + )); + } + } + ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::EnumeratorNext { + capacity_param, + fetched_param, + }, + ) => { + require_direction(parameters, *capacity_param, &[ComParameterDirection::In])?; + require_direction( + parameters, + *fetched_param, + &[ + ComParameterDirection::Out, + ComParameterDirection::OptionalOut, + ], + )?; + validate_u32_count_type(¶meters[*capacity_param].typ)?; + validate_u32_count_type(¶meters[*fetched_param].typ)?; + } + ( + ComParameterDirection::CalleeAllocatedBuffer, + ComBufferRelation::CalleeAllocated { count_param, .. }, + ) => { + require_direction(parameters, *count_param, &[ComParameterDirection::Out])?; + } + _ => { + return Err(invalid_argument( + "COM buffer direction and count relationship do not agree", + )); + } + } + } + for (count_index, buffers) in related.iter().enumerate() { + if buffers.len() > 1 { + validate_shared_count_group(parameters, count_index, buffers)?; + } + } + Ok(()) +} + +fn validate_shared_count_group( + parameters: &[ComParameterSpec], + count_index: usize, + buffers: &[usize], +) -> result::Result<()> { + let shared_input_units = buffers + .iter() + .map(|&buffer_index| { + let parameter = ¶meters[buffer_index]; + let contract = parameter.buffer.as_ref().expect("validated buffer"); + match (¶meter.direction, &contract.relation) { + ( + ComParameterDirection::InputBuffer, + ComBufferRelation::Input { + count_param, + actual_length_param: None, + unit, + }, + ) if *count_param == count_index => Some(*unit), + _ => None, + } + }) + .collect::>>(); + if shared_input_units.is_some_and(|units| { + units + .first() + .is_some_and(|first| units.iter().all(|unit| unit == first)) + }) { + return Ok(()); + } + let mut parallel_inputs = 0usize; + let mut parallel_outputs = 0usize; + let parallel = buffers.iter().all(|&buffer_index| { + let parameter = ¶meters[buffer_index]; + let contract = parameter.buffer.as_ref().expect("validated buffer"); + match (¶meter.direction, &contract.relation) { + ( + ComParameterDirection::InputBuffer, + ComBufferRelation::Input { + count_param, + actual_length_param: None, + unit: BufferCountUnit::Elements, + }, + ) if *count_param == count_index => { + parallel_inputs += 1; + true + } + ( + ComParameterDirection::CallerOutputBuffer, + ComBufferRelation::CallerCapacity { + capacity_param, + actual_length_param: None, + unit: BufferCountUnit::Elements, + two_call: false, + }, + ) if *capacity_param == count_index => { + parallel_outputs += 1; + true + } + _ => false, + } + }); + if parallel && parallel_inputs != 0 && parallel_outputs != 0 { + return Ok(()); + } + if buffers.len() != 2 { + return Err(invalid_argument( + "shared COM counts require exactly one string input array and one caller output array", + )); + } + let mut string_input = false; + let mut caller_output = false; + for &buffer_index in buffers { + let parameter = ¶meters[buffer_index]; + let contract = parameter.buffer.as_ref().expect("validated buffer"); + match ( + ¶meter.direction, + &contract.element.kind, + &contract.relation, + ) { + ( + ComParameterDirection::InputBuffer, + BufferElementKind::StringPointer(_), + ComBufferRelation::Input { + count_param, + actual_length_param: None, + unit: BufferCountUnit::Elements, + }, + ) if *count_param == count_index && !string_input => string_input = true, + ( + ComParameterDirection::CallerOutputBuffer, + BufferElementKind::Plain, + ComBufferRelation::CallerCapacity { + capacity_param, + actual_length_param: None, + unit: BufferCountUnit::Elements, + two_call: false, + }, + ) if *capacity_param == count_index && !caller_output => caller_output = true, + ( + ComParameterDirection::CallerOutputBuffer, + _, + ComBufferRelation::EnumeratorNext { .. }, + ) => { + return Err(invalid_argument( + "enumerator counts cannot be shared with unrelated COM buffers", + )); + } + _ => { + return Err(invalid_argument( + "unrelated COM buffers cannot share one count parameter", + )); + } + } + } + if string_input && caller_output { + Ok(()) + } else { + Err(invalid_argument( + "shared COM counts require one string input array and one caller output array", + )) + } +} + +fn validate_count_type(typ: &Type) -> result::Result<()> { + let ParameterType::WinRT(typ) = &typ.abi else { + return Err(invalid_argument( + "COM buffer count parameters require integer scalar ABI types", + )); + }; + if matches!( + typ.kind(), + TypeKind::I8 + | TypeKind::U8 + | TypeKind::I16 + | TypeKind::U16 + | TypeKind::I32 + | TypeKind::U32 + | TypeKind::I64 + | TypeKind::U64 + ) { + Ok(()) + } else { + Err(invalid_argument( + "COM buffer count parameters require an integer scalar ABI type", + )) + } +} + +fn validate_u32_count_type(typ: &Type) -> result::Result<()> { + if matches!( + &typ.abi, + ParameterType::WinRT(typ) if matches!(typ.kind(), TypeKind::U32) + ) { + Ok(()) + } else { + Err(invalid_argument( + "IEnum::Next capacity and fetched parameters must use ULONG/u32", + )) + } +} + +fn require_direction( + parameters: &[ComParameterSpec], + index: usize, + allowed: &[ComParameterDirection], +) -> result::Result<()> { + if allowed.contains(¶meters[index].direction) { + Ok(()) + } else { + Err(invalid_argument(format!( + "COM buffer relationship parameter {index} has direction {:?}, expected one of {allowed:?}", + parameters[index].direction + ))) + } +} + +#[derive(Debug)] +struct RegisteredMethod { + plan: ComCallPlan, +} + +#[derive(Debug, Clone)] +pub struct Interface { + name: String, + iid: GUID, + base_slot: usize, + methods: Arc)>>>, +} + +impl Interface { + pub fn name(&self) -> &str { + &self.name + } + + pub fn iid(&self) -> GUID { + self.iid + } + + pub fn add_method(self, name: &str, signature: MethodSignature) -> Self { + let vtable_index = self + .methods + .read() + .unwrap() + .last_key_value() + .map_or(self.base_slot, |(slot, _)| slot + 1); + self.add_method_at(vtable_index, name, signature) + .expect("sequential COM method registration must use a free vtable slot") + } + + pub fn add_method_at( + self, + vtable_index: usize, + name: &str, + signature: MethodSignature, + ) -> result::Result { + if vtable_index < self.base_slot { + return Err(invalid_argument(format!( + "COM method '{name}' uses vtable slot {vtable_index}, before the interface base slot {}", + self.base_slot + ))); + } + signature.validate_registration(self.iid, name, vtable_index)?; + + let mut methods = self.methods.write().unwrap(); + if methods.contains_key(&vtable_index) { + return Err(invalid_argument(format!( + "COM vtable slot {vtable_index} is already registered on '{}'", + self.name + ))); + } + methods.insert( + vtable_index, + (name.to_string(), Arc::new(signature.build(vtable_index)?)), + ); + drop(methods); + Ok(self) + } + + pub fn method(&self, vtable_index: usize) -> Option { + self.methods + .read() + .unwrap() + .get(&vtable_index) + .map(|(_, method)| MethodHandle(Arc::clone(method))) + } +} + +#[derive(Clone)] +pub struct MethodHandle(Arc); + +impl std::fmt::Debug for MethodHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MethodHandle").finish_non_exhaustive() + } +} + +impl MethodHandle { + pub fn result_count(&self) -> usize { + self.0.plan.results.len() + } + + /// # Safety + /// + /// `obj` must point to a live COM interface whose vtable contains this + /// method at its registered slot for the duration of the call. + pub unsafe fn invoke( + &self, + obj: *mut c_void, + args: &[WinRTValue], + ) -> result::Result> { + self.0.plan.invoke(obj, args) + } + + /// # Safety + /// + /// `obj` must point to a live COM interface whose vtable contains this + /// method at its registered slot for the duration of the call. + pub unsafe fn invoke_with_output_kinds( + &self, + obj: *mut c_void, + args: &[WinRTValue], + ) -> result::Result> { + self.0.plan.invoke_with_output_kinds(obj, args) + } + + /// # Safety + /// + /// `obj` must point to a live COM interface whose vtable contains this + /// method at its registered slot for the duration of the call. + pub unsafe fn invoke_values_with_output_kinds( + &self, + obj: *mut c_void, + args: &[Value], + ) -> result::Result> { + self.0.plan.invoke_values_with_output_kinds(obj, args) + } + + /// # Safety + /// + /// `obj` must point to a live IDispatch interface whose vtable contains + /// Invoke at slot 6 for the duration of the call. + pub unsafe fn invoke_dispatch( + &self, + obj: *mut c_void, + args: &[Value], + ) -> result::Result { + self.0.plan.invoke_dispatch(obj, args) + } + + /// # Safety + /// + /// `obj` must point to a live COM interface whose vtable contains this + /// HSTRING getter at its registered slot for the duration of the call. + pub unsafe fn call_getter_hstring( + &self, + obj: *mut c_void, + ) -> result::Result { + self.0 + .plan + .native + .call_getter_hstring(obj) + .map_err(result::Error::WindowsError) + } +} + +pub fn register_interface( + _table: &std::sync::Arc, + name: &str, + iid: GUID, + base: InterfaceBase, +) -> Interface { + Interface { + name: name.to_string(), + iid, + base_slot: base.first_method_slot(), + methods: Arc::new(RwLock::new(BTreeMap::new())), + } +} + +fn invalid_argument(message: impl Into) -> result::Error { + let message = message.into(); + result::Error::WindowsError(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &message, + )) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ApartmentType { + SingleThreaded, + MultiThreaded, +} + +impl ApartmentType { + fn as_flag(self) -> windows::Win32::System::Com::COINIT { + match self { + Self::SingleThreaded => COINIT_APARTMENTTHREADED, + Self::MultiThreaded => COINIT_MULTITHREADED, + } + } +} + +struct ComApartment { + apartment_type: ApartmentType, +} + +impl Drop for ComApartment { + fn drop(&mut self) { + unsafe { CoUninitialize() }; + } +} + +enum ComInitialization { + Uninitialized, + Owned(ComApartment), +} + +thread_local! { + static COM_INITIALIZATION: RefCell = + const { RefCell::new(ComInitialization::Uninitialized) }; +} + +pub fn initialize_apartment(apartment_type: ApartmentType) -> result::Result<()> { + COM_INITIALIZATION.with(|state| { + if let ComInitialization::Owned(existing) = &*state.borrow() { + return if existing.apartment_type == apartment_type { + Ok(()) + } else { + Err(result::Error::WindowsError( + windows_core::Error::from_hresult(RPC_E_CHANGED_MODE), + )) + }; + } + + let hr = unsafe { CoInitializeEx(None, apartment_type.as_flag()) }; + if hr.is_ok() { + *state.borrow_mut() = ComInitialization::Owned(ComApartment { apartment_type }); + Ok(()) + } else { + Err(result::Error::WindowsError( + windows_core::Error::from_hresult(hr), + )) + } + }) +} + +pub fn co_create_instance(clsid: GUID, iid: GUID) -> result::Result { + let unknown: IUnknown = unsafe { CoCreateInstance(&clsid, None, CLSCTX_INPROC_SERVER) } + .map_err(result::Error::WindowsError)?; + let mut result = std::ptr::null_mut(); + unsafe { unknown.query(&iid, &mut result) } + .ok() + .map_err(result::Error::WindowsError)?; + Ok(WinRTValue::Object(unsafe { IUnknown::from_raw(result) })) +} + +/// Adopt an AddRef-owned COM interface pointer into a managed Object value. +/// +/// The pointer must represent a caller-owned COM reference (+1). This function +/// takes ownership with `IUnknown::from_raw` and must not be used for borrowed +/// pointers. +pub unsafe fn adopt_com_pointer(ptr: *mut c_void) -> WinRTValue { + if ptr.is_null() { + WinRTValue::Null + } else { + WinRTValue::Object(unsafe { IUnknown::from_raw(ptr) }) + } +} + +#[cfg(test)] +fn call_method( + vtable_index: usize, + obj: *mut c_void, + signature: MethodSignature, + args: &[WinRTValue], +) -> result::Result> { + signature.build(vtable_index)?.plan.invoke(obj, args) +} + +#[cfg(test)] +fn call_method_1_ptr( + vtable_index: usize, + obj: *mut c_void, + ptr: *const c_void, +) -> result::Result<()> { + crate::call::call_winrt_method_1(vtable_index, obj, ptr) + .ok() + .map_err(result::Error::WindowsError) +} + +#[cfg(test)] +fn call_method_2_ptr_i32( + vtable_index: usize, + obj: *mut c_void, + ptr: *mut c_void, + value: i32, +) -> result::Result<()> { + crate::call::call_winrt_method_2(vtable_index, obj, ptr, value) + .ok() + .map_err(result::Error::WindowsError) +} + +#[cfg(test)] +fn wide_null(text: &str) -> Vec { + text.encode_utf16().chain(std::iter::once(0)).collect() +} + +#[cfg(test)] +fn wide_buffer(characters: usize) -> Vec { + vec![0; characters] +} + +#[cfg(test)] +fn wide_to_string(buffer: &[u16]) -> String { + let end = buffer + .iter() + .position(|ch| *ch == 0) + .unwrap_or(buffer.len()); + String::from_utf16_lossy(&buffer[..end]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + MetadataTable, com_helpers::E_NOINTERFACE, ro_get_activation_factory_2, + roapi::query_interface, + }; + use std::sync::atomic::{AtomicU32, Ordering}; + use windows::{ + ApplicationModel::DataTransfer::DataTransferManager, + Win32::{ + System::Com::{CoGetMalloc, IMalloc, IPersistFile, IStream}, + UI::Shell::{IDataTransferManagerInterop, SHCreateMemStream}, + UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, WINDOW_EX_STYLE, WS_OVERLAPPED, + }, + }, + }; + use windows_core::{HSTRING, w}; + + #[repr(C)] + struct FakeComObject { + vtable: *const *mut c_void, + } + + #[repr(C)] + struct TrackedComObject { + vtable: *const windows_core::IUnknown_Vtbl, + addrefs: AtomicU32, + releases: AtomicU32, + } + + unsafe extern "system" fn tracked_query_interface( + _this: *mut c_void, + _iid: *const GUID, + result: *mut *mut c_void, + ) -> windows_core::HRESULT { + unsafe { *result = std::ptr::null_mut() }; + E_NOINTERFACE + } + + unsafe extern "system" fn tracked_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*(this as *const TrackedComObject) }; + object.addrefs.fetch_add(1, Ordering::Relaxed); + 2 + } + + unsafe extern "system" fn tracked_release(this: *mut c_void) -> u32 { + let object = unsafe { &*(this as *const TrackedComObject) }; + object.releases.fetch_add(1, Ordering::Relaxed); + 1 + } + + static TRACKED_VTABLE: windows_core::IUnknown_Vtbl = windows_core::IUnknown_Vtbl { + QueryInterface: tracked_query_interface, + AddRef: tracked_add_ref, + Release: tracked_release, + }; + + unsafe extern "system" fn tracked_dispatch_query_interface( + this: *mut c_void, + _iid: *const GUID, + result: *mut *mut c_void, + ) -> windows_core::HRESULT { + unsafe { *result = this }; + unsafe { tracked_add_ref(this) }; + windows_core::HRESULT(0) + } + + static TRACKED_DISPATCH_VTABLE: windows_core::IUnknown_Vtbl = windows_core::IUnknown_Vtbl { + QueryInterface: tracked_dispatch_query_interface, + AddRef: tracked_add_ref, + Release: tracked_release, + }; + + #[repr(C)] + struct FailingOutCall { + vtable: *const *mut c_void, + output: *mut c_void, + } + + unsafe extern "system" fn write_object_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { *output = call.output }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn write_object_and_i32_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + number: *mut i32, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + *output = call.output; + *number = 42; + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + #[test] + fn interface_and_method_handle_are_send_and_sync() { + fn assert_send_sync() {} + + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + } + + unsafe extern "system" fn return_u32(_this: *mut c_void) -> u32 { + u32::MAX + } + + unsafe extern "system" fn return_s_false(_this: *mut c_void) -> windows_core::HRESULT { + windows_core::HRESULT(1) + } + + unsafe extern "system" fn return_failure(_this: *mut c_void) -> windows_core::HRESULT { + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn return_hstring( + _this: *mut c_void, + value: *mut *mut c_void, + ) -> windows_core::HRESULT { + unsafe { + *value = std::mem::transmute(HSTRING::from("dynwinrt HSTRING")); + } + windows_core::HRESULT(0) + } + + static VOID_CALLS: AtomicU32 = AtomicU32::new(0); + static BSTR_FAKE_ALLOCS: AtomicU32 = AtomicU32::new(0); + static BSTR_FAKE_FREES: AtomicU32 = AtomicU32::new(0); + static BSTR_INPUT_MATCHES: AtomicU32 = AtomicU32::new(0); + static BSTR_EMPTY_INPUT_IS_NONNULL: AtomicU32 = AtomicU32::new(0); + static BSTR_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + unsafe fn borrowed_bstr_string(value: *const u16) -> String { + if value.is_null() { + return String::new(); + } + let value = std::mem::ManuallyDrop::new(unsafe { windows_core::BSTR::from_raw(value) }); + String::try_from(&*value).unwrap() + } + + unsafe fn replace_bstr_slot(slot: *mut *const u16, replacement: Option<&str>) { + let current = unsafe { *slot }; + if !current.is_null() { + BSTR_FAKE_FREES.fetch_add(1, Ordering::Relaxed); + drop(unsafe { windows_core::BSTR::from_raw(current) }); + } + let replacement = replacement.map(|replacement| { + let utf16 = replacement.encode_utf16().collect::>(); + let value = + unsafe { windows::Win32::Foundation::SysAllocStringLen(Some(utf16.as_slice())) }; + assert!(!value.is_empty() || utf16.is_empty()); + BSTR_FAKE_ALLOCS.fetch_add(1, Ordering::Relaxed); + value.into_raw() + }); + unsafe { *slot = replacement.unwrap_or(std::ptr::null()) }; + } + + unsafe extern "system" fn observe_bstr_input( + _this: *mut c_void, + value: *const u16, + ) -> windows_core::HRESULT { + let observed = unsafe { borrowed_bstr_string(value) }; + if observed == "embedded\0nul" { + BSTR_INPUT_MATCHES.fetch_add(1, Ordering::Relaxed); + } + if !value.is_null() && observed.is_empty() { + BSTR_EMPTY_INPUT_IS_NONNULL.fetch_add(1, Ordering::Relaxed); + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_bstr_output( + _this: *mut c_void, + value: *mut *const u16, + ) -> windows_core::HRESULT { + unsafe { replace_bstr_slot(value, Some("output\0value")) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn leave_bstr_unchanged( + _this: *mut c_void, + _value: *mut *const u16, + ) -> windows_core::HRESULT { + windows_core::HRESULT(0) + } + + unsafe extern "system" fn replace_bstr( + _this: *mut c_void, + value: *mut *const u16, + ) -> windows_core::HRESULT { + unsafe { replace_bstr_slot(value, Some("replaced\0value")) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn null_bstr( + _this: *mut c_void, + value: *mut *const u16, + ) -> windows_core::HRESULT { + unsafe { replace_bstr_slot(value, None) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn leave_bstr_unchanged_then_fail( + _this: *mut c_void, + _value: *mut *const u16, + ) -> windows_core::HRESULT { + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn replace_bstr_then_fail( + _this: *mut c_void, + value: *mut *const u16, + ) -> windows_core::HRESULT { + unsafe { replace_bstr_slot(value, Some("failure replacement")) }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn null_bstr_then_fail( + _this: *mut c_void, + value: *mut *const u16, + ) -> windows_core::HRESULT { + unsafe { replace_bstr_slot(value, None) }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn return_void(_this: *mut c_void) { + VOID_CALLS.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn increment_i32( + _this: *mut c_void, + value: *mut i32, + ) -> windows_core::HRESULT { + unsafe { *value += 1 }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_native_pointer( + _this: *mut c_void, + value: *mut *mut c_void, + ) -> windows_core::HRESULT { + unsafe { *value = 0x1234usize as *mut c_void }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn succeed_without_writing_native_pointer( + _this: *mut c_void, + _value: *mut *mut c_void, + ) -> windows_core::HRESULT { + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_guid_and_i32( + _this: *mut c_void, + guid: *mut GUID, + value: *mut i32, + ) -> windows_core::HRESULT { + unsafe { + *guid = GUID::from_u128(0x11111111_2222_3333_4444_555555555555); + *value = 42; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn copy_variant_value( + _this: *mut c_void, + input: *const windows::Win32::System::Variant::VARIANT, + output: *mut windows::Win32::System::Variant::VARIANT, + ) -> windows_core::HRESULT { + match unsafe { windows::Win32::System::Variant::VariantCopy(output, input) } { + Ok(()) => windows_core::HRESULT(0), + Err(error) => error.code(), + } + } + + unsafe extern "system" fn observe_variant_by_value_i32( + _this: *mut c_void, + input: windows::Win32::System::Variant::VARIANT, + output: *mut i32, + ) -> windows_core::HRESULT { + let input = std::mem::ManuallyDrop::new(input); + unsafe { *output = automation::variant_i32_for_test(&*input) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn observe_variant_by_value_bstr( + _this: *mut c_void, + input: windows::Win32::System::Variant::VARIANT, + output: *mut u32, + ) -> windows_core::HRESULT { + let input = std::mem::ManuallyDrop::new(input); + let matches = unsafe { automation::variant_bstr_for_test(&*input) == "by value" }; + unsafe { *output = u32::from(matches) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn observe_variant_by_value_unknown( + _this: *mut c_void, + input: windows::Win32::System::Variant::VARIANT, + output: *mut u32, + ) -> windows_core::HRESULT { + let input = std::mem::ManuallyDrop::new(input); + let matches = unsafe { automation::variant_unknown_is_non_null_for_test(&*input) }; + unsafe { *output = u32::from(matches) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn mutate_variant_by_value_then_fail( + _this: *mut c_void, + input: windows::Win32::System::Variant::VARIANT, + ) -> windows_core::HRESULT { + let mut input = std::mem::ManuallyDrop::new(input); + unsafe { + automation::set_variant_vartype_for_test( + &mut *input, + windows::Win32::System::Variant::VT_EMPTY.0, + ) + }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + static VARIANT_BY_VALUE_DISPATCH_CALLS: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn count_variant_by_value_dispatch( + _this: *mut c_void, + _input: windows::Win32::System::Variant::VARIANT, + ) -> windows_core::HRESULT { + VARIANT_BY_VALUE_DISPATCH_CALLS.fetch_add(1, Ordering::Relaxed); + windows_core::HRESULT(0) + } + + static DEFERRED_FILL_CALLS: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn deferred_fill_success( + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + DEFERRED_FILL_CALLS.fetch_add(1, Ordering::Relaxed); + unsafe { + (*info).wCode = 23; + (*info).bstrSource = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred source")); + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred description")); + (*info).bstrHelpFile = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred help")); + (*info).dwHelpContext = 42; + (*info).scode = 0x80020009u32 as i32; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn deferred_fill_failure( + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + DEFERRED_FILL_CALLS.fetch_add(1, Ordering::Relaxed); + unsafe { + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("partial failure")); + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn deferred_fill_reinstalls_callback( + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + DEFERRED_FILL_CALLS.fetch_add(1, Ordering::Relaxed); + unsafe { + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("unsupported deferred")); + (*info).pfnDeferredFillIn = Some(deferred_fill_success); + } + windows_core::HRESULT(0) + } + + static DISPATCH_OPTIONAL_NULL_MASK: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn inspect_dispatch_params_and_fill_outputs( + _this: *mut c_void, + params: *mut windows::Win32::System::Com::DISPPARAMS, + result: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + arg_error: *mut u32, + ) -> windows_core::HRESULT { + let params = unsafe { &*params }; + assert_eq!((params.cArgs, params.cNamedArgs), (3, 2)); + assert_eq!( + unsafe { + std::slice::from_raw_parts(params.rgdispidNamedArgs, params.cNamedArgs as usize) + }, + &[200, 100] + ); + assert_eq!( + unsafe { automation::variant_i32_for_test(params.rgvarg) }, + 30 + ); + assert_eq!( + unsafe { automation::variant_i32_for_test(params.rgvarg.add(1)) }, + 20 + ); + assert_eq!( + unsafe { automation::variant_i32_for_test(params.rgvarg.add(2)) }, + 10 + ); + assert_eq!( + unsafe { params.rgvarg.add(1).byte_offset_from(params.rgvarg) }, + size_of::() as isize + ); + + let mut null_mask = 0; + if result.is_null() { + null_mask |= 1; + } else if let Err(error) = + unsafe { windows::Win32::System::Variant::VariantCopy(result, params.rgvarg) } + { + return error.code(); + } + if info.is_null() { + null_mask |= 2; + } else { + unsafe { + (*info).wCode = 17; + (*info).bstrSource = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("source")); + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("description")); + (*info).bstrHelpFile = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("help.chm")); + (*info).dwHelpContext = 91; + (*info).scode = 0x80020009u32 as i32; + } + } + if arg_error.is_null() { + null_mask |= 4; + } else { + unsafe { *arg_error = 2 }; + } + DISPATCH_OPTIONAL_NULL_MASK.store(null_mask, Ordering::Relaxed); + windows_core::HRESULT(0) + } + + const DISP_E_TYPEMISMATCH: windows_core::HRESULT = windows_core::HRESULT(0x80020005u32 as i32); + const DISP_E_EXCEPTION: windows_core::HRESULT = windows_core::HRESULT(0x80020009u32 as i32); + + static DISPATCH_INVOKE_NULL_MASK: AtomicU32 = AtomicU32::new(0); + static DISPATCH_DEFERRED_SUCCESS_CALLS: AtomicU32 = AtomicU32::new(0); + static DISPATCH_DEFERRED_FAILURE_CALLS: AtomicU32 = AtomicU32::new(0); + + type DispatchInvokeFn = unsafe extern "system" fn( + *mut c_void, + i32, + *const GUID, + u32, + u16, + *mut windows::Win32::System::Com::DISPPARAMS, + *mut windows::Win32::System::Variant::VARIANT, + *mut windows::Win32::System::Com::EXCEPINFO, + *mut u32, + ) -> windows_core::HRESULT; + + unsafe extern "system" fn dispatch_deferred_fill_success( + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + DISPATCH_DEFERRED_SUCCESS_CALLS.fetch_add(1, Ordering::Relaxed); + unsafe { + (*info).wCode = 23; + (*info).bstrSource = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred source")); + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred description")); + (*info).bstrHelpFile = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("deferred help")); + (*info).dwHelpContext = 42; + (*info).scode = DISP_E_EXCEPTION.0; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn dispatch_deferred_fill_failure( + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + DISPATCH_DEFERRED_FAILURE_CALLS.fetch_add(1, Ordering::Relaxed); + unsafe { + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("partial failure")); + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn dispatch_invoke_success( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + result: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + arg_err: *mut u32, + ) -> windows_core::HRESULT { + assert!(!result.is_null()); + let value = VariantValue::from_i32(42); + unsafe { windows::Win32::System::Variant::VariantCopy(result, value.raw()) }.unwrap(); + if !info.is_null() { + unsafe { + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("ignored on success")); + (*info).pfnDeferredFillIn = Some(dispatch_deferred_fill_success); + } + } + if !arg_err.is_null() { + unsafe { *arg_err = 99 }; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn dispatch_invoke_exception( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + _result: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + _arg_err: *mut u32, + ) -> windows_core::HRESULT { + assert!(!info.is_null()); + unsafe { (*info).pfnDeferredFillIn = Some(dispatch_deferred_fill_success) }; + DISP_E_EXCEPTION + } + + unsafe extern "system" fn dispatch_invoke_exception_with_failing_deferred( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + _result: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + _arg_err: *mut u32, + ) -> windows_core::HRESULT { + assert!(!info.is_null()); + unsafe { (*info).pfnDeferredFillIn = Some(dispatch_deferred_fill_failure) }; + DISP_E_EXCEPTION + } + + unsafe extern "system" fn dispatch_invoke_type_mismatch( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + _result: *mut windows::Win32::System::Variant::VARIANT, + _info: *mut windows::Win32::System::Com::EXCEPINFO, + arg_err: *mut u32, + ) -> windows_core::HRESULT { + assert!(!arg_err.is_null()); + unsafe { *arg_err = 3 }; + DISP_E_TYPEMISMATCH + } + + unsafe extern "system" fn dispatch_invoke_fail( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + _result: *mut windows::Win32::System::Variant::VARIANT, + _info: *mut windows::Win32::System::Com::EXCEPINFO, + _arg_err: *mut u32, + ) -> windows_core::HRESULT { + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn dispatch_invoke_disabled_outputs( + _this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + result: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + arg_err: *mut u32, + ) -> windows_core::HRESULT { + let mut mask = 0; + if result.is_null() { + mask |= 1; + } + if info.is_null() { + mask |= 2; + } + if arg_err.is_null() { + mask |= 4; + } + DISPATCH_INVOKE_NULL_MASK.store(mask, Ordering::Relaxed); + windows_core::HRESULT(0) + } + + #[repr(C)] + struct DispatchTrackedCall { + vtable: *const *mut c_void, + output: *mut c_void, + } + + unsafe extern "system" fn dispatch_invoke_partial_result_then_fail( + this: *mut c_void, + _disp_id: i32, + _riid: *const GUID, + _lcid: u32, + _flags: u16, + _params: *mut windows::Win32::System::Com::DISPPARAMS, + result: *mut windows::Win32::System::Variant::VARIANT, + _info: *mut windows::Win32::System::Com::EXCEPINFO, + _arg_err: *mut u32, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const DispatchTrackedCall) }; + let borrowed = unsafe { IUnknown::from_raw_borrowed(&call.output) }.unwrap(); + let value = VariantValue::from_unknown(Some(borrowed)); + unsafe { windows::Win32::System::Variant::VariantCopy(result, value.raw()) }.unwrap(); + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn install_deferred_excep_info( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { (*info).pfnDeferredFillIn = Some(deferred_fill_success) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn install_failing_deferred_excep_info( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { (*info).pfnDeferredFillIn = Some(deferred_fill_failure) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn install_reinstalling_deferred_excep_info( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { (*info).pfnDeferredFillIn = Some(deferred_fill_reinstalls_callback) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_reserved_excep_info( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { + (*info).wReserved = 1; + (*info).bstrDescription = + std::mem::ManuallyDrop::new(windows_core::BSTR::from("reserved")); + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn install_deferred_excep_info_then_fail( + _this: *mut c_void, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { (*info).pfnDeferredFillIn = Some(deferred_fill_success) }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn write_unsupported_variant_and_deferred_excep_info( + _this: *mut c_void, + variant: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + unsafe { + automation::set_variant_vartype_for_test( + variant, + windows::Win32::System::Variant::VT_DATE.0, + ); + (*info).pfnDeferredFillIn = Some(deferred_fill_success); + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_unsupported_variant_and_deferred_excep_info_then_fail( + this: *mut c_void, + variant: *mut windows::Win32::System::Variant::VARIANT, + info: *mut windows::Win32::System::Com::EXCEPINFO, + ) -> windows_core::HRESULT { + let _ = unsafe { write_unsupported_variant_and_deferred_excep_info(this, variant, info) }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn write_unsupported_variant_and_object( + this: *mut c_void, + variant: *mut windows::Win32::System::Variant::VARIANT, + output: *mut *mut c_void, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + automation::set_variant_vartype_for_test( + variant, + windows::Win32::System::Variant::VT_DATE.0, + ); + *output = call.output; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_object_and_unsupported_variant( + this: *mut c_void, + output: *mut *mut c_void, + variant: *mut windows::Win32::System::Variant::VARIANT, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + *output = call.output; + automation::set_variant_vartype_for_test( + variant, + windows::Win32::System::Variant::VT_DATE.0, + ); + } + windows_core::HRESULT(0) + } + + static AUTOMATION_DISPATCH_CALLS: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn count_automation_dispatch( + _this: *mut c_void, + _variant: *mut windows::Win32::System::Variant::VARIANT, + ) -> windows_core::HRESULT { + AUTOMATION_DISPATCH_CALLS.fetch_add(1, Ordering::Relaxed); + windows_core::HRESULT(0) + } + + unsafe extern "system" fn return_object_with_unsupported_variant( + this: *mut c_void, + variant: *mut windows::Win32::System::Variant::VARIANT, + ) -> *mut c_void { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + automation::set_variant_vartype_for_test( + variant, + windows::Win32::System::Variant::VT_DATE.0, + ); + } + call.output + } + + unsafe extern "system" fn copy_safe_array_value( + _this: *mut c_void, + input: *mut windows::Win32::System::Com::SAFEARRAY, + output: *mut *mut windows::Win32::System::Com::SAFEARRAY, + ) -> windows_core::HRESULT { + match unsafe { windows::Win32::System::Ole::SafeArrayCopy(input) } { + Ok(value) => { + unsafe { *output = value }; + windows_core::HRESULT(0) + } + Err(error) => error.code(), + } + } + + unsafe extern "system" fn return_null_safe_array( + _this: *mut c_void, + output: *mut *mut windows::Win32::System::Com::SAFEARRAY, + ) -> windows_core::HRESULT { + unsafe { *output = std::ptr::null_mut() }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn observe_aliased_safe_arrays( + _this: *mut c_void, + first: *mut windows::Win32::System::Com::SAFEARRAY, + second: *mut windows::Win32::System::Com::SAFEARRAY, + ) -> windows_core::HRESULT { + assert_eq!(first, second); + windows_core::HRESULT(0) + } + + unsafe extern "system" fn copy_prop_variant_value( + _this: *mut c_void, + input: *const windows::Win32::System::Com::StructuredStorage::PROPVARIANT, + output: *mut windows::Win32::System::Com::StructuredStorage::PROPVARIANT, + ) -> windows_core::HRESULT { + match unsafe { + windows::Win32::System::Com::StructuredStorage::PropVariantCopy(output, input) + } { + Ok(()) => windows_core::HRESULT(0), + Err(error) => error.code(), + } + } + + unsafe extern "system" fn read_native_union( + _this: *mut c_void, + input: *const u64, + output: *mut u64, + ) -> windows_core::HRESULT { + unsafe { *output = *input }; + windows_core::HRESULT(0) + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct TestPod { + first: u32, + second: u16, + tag: u16, + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct AlignedPod { + value: u64, + } + + fn test_pod_layout(name: &str) -> Arc { + Arc::new( + NativeStructLayout::new( + name, + size_of::(), + align_of::(), + vec![ + NativeStructField::new( + "first", + 0, + 1, + NativeStructFieldType::Scalar(NativeStructScalar::U32), + ) + .unwrap(), + NativeStructField::new( + "second", + 4, + 1, + NativeStructFieldType::Scalar(NativeStructScalar::U16), + ) + .unwrap(), + NativeStructField::new( + "tag", + 6, + 1, + NativeStructFieldType::Scalar(NativeStructScalar::U16), + ) + .unwrap(), + ], + ) + .unwrap(), + ) + } + + fn test_pod_value(layout: Arc, value: TestPod) -> NativeStructValue { + let bytes = unsafe { + std::slice::from_raw_parts( + (&value as *const TestPod).cast::(), + size_of::(), + ) + } + .to_vec(); + NativeStructValue::new(layout, bytes).unwrap() + } + + fn read_test_pod(value: &NativeStructValue) -> TestPod { + unsafe { std::ptr::read_unaligned(value.bytes().as_ptr().cast::()) } + } + + unsafe extern "system" fn require_aligned_pod( + _this: *mut c_void, + value: *const AlignedPod, + ) -> windows_core::HRESULT { + if (value as usize) % align_of::() == 0 { + windows_core::HRESULT(0) + } else { + windows_core::HRESULT(0x80004005u32 as i32) + } + } + + unsafe extern "system" fn sum_pod_by_value( + _this: *mut c_void, + value: TestPod, + result: *mut u32, + ) -> windows_core::HRESULT { + unsafe { *result = value.first + u32::from(value.second) + u32::from(value.tag) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn sum_pod_pointer( + _this: *mut c_void, + value: *const TestPod, + result: *mut u32, + ) -> windows_core::HRESULT { + let value = unsafe { &*value }; + unsafe { *result = value.first + u32::from(value.second) + u32::from(value.tag) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn nullable_pod_pointer_is_null( + _this: *mut c_void, + value: *const TestPod, + result: *mut u32, + ) -> windows_core::HRESULT { + unsafe { *result = u32::from(value.is_null()) }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_zeroed_pod( + _this: *mut c_void, + value: *mut TestPod, + ) -> windows_core::HRESULT { + let value = unsafe { &mut *value }; + if value.first != 0 || value.second != 0 || value.tag != 0 { + return windows_core::HRESULT(0x80004005u32 as i32); + } + *value = TestPod { + first: 40, + second: 2, + tag: 7, + }; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn update_pod_in_out( + _this: *mut c_void, + value: *mut TestPod, + ) -> windows_core::HRESULT { + let value = unsafe { &mut *value }; + value.first += 1; + value.second += 2; + value.tag += 3; + windows_core::HRESULT(0) + } + + unsafe extern "system" fn update_nullable_pod_in_out( + _this: *mut c_void, + value: *mut TestPod, + ) -> windows_core::HRESULT { + if !value.is_null() { + unsafe { + (*value).first += 1; + (*value).second += 2; + (*value).tag += 3; + } + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn write_pod_then_fail( + _this: *mut c_void, + value: *mut TestPod, + ) -> windows_core::HRESULT { + unsafe { + *value = TestPod { + first: 1, + second: 2, + tag: 3, + }; + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn read_counted_bytes( + _this: *mut c_void, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + let bytes = [4u8, 5, 6]; + let written = bytes.len().min(capacity as usize); + unsafe { + assert!((0..capacity as usize).all(|index| *buffer.add(index) == 0)); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, written); + *actual = written as u32; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn read_counted_bytes_then_fail( + _this: *mut c_void, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + unsafe { + if capacity > 0 { + *buffer = 9; + } + *actual = usize::min(capacity as usize, 1) as u32; + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + unsafe extern "system" fn report_larger_count( + _this: *mut c_void, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + unsafe { + if capacity > 0 { + *buffer = 7; + } + *actual = capacity.saturating_add(2); + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn get_blob_fixed_capacity( + _this: *mut c_void, + guid: *const GUID, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + assert!(!guid.is_null()); + assert!(!buffer.is_null()); + assert!(!actual.is_null()); + let bytes = [11u8, 22, 33]; + unsafe { + assert!((0..capacity as usize).all(|index| *buffer.add(index) == 0)); + *actual = bytes.len() as u32; + if capacity < bytes.len() as u32 { + if capacity > 0 { + *buffer = 0xEE; + } + return windows_core::HRESULT(0x8007007Au32 as i32); + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, bytes.len()); + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn get_blob_then_fail( + _this: *mut c_void, + _guid: *const GUID, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + unsafe { + if capacity > 0 { + *buffer = 0xAA; + } + *actual = u32::from(capacity > 0); + } + windows_core::HRESULT(0x80004005u32 as i32) + } + + static ENUMERATOR_NEXT_CALLS: AtomicU32 = AtomicU32::new(0); + static OPTIONAL_ENUMERATOR_NEXT_CALLS: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn enum_next_partial_u32( + _this: *mut c_void, + capacity: u32, + values: *mut u32, + fetched: *mut u32, + ) -> windows_core::HRESULT { + ENUMERATOR_NEXT_CALLS.fetch_add(1, Ordering::Relaxed); + assert!(!fetched.is_null()); + unsafe { + if capacity != 0 { + *values = 41; + } + *fetched = u32::from(capacity != 0); + } + windows_core::HRESULT(1) + } + + unsafe extern "system" fn optional_enum_next_should_not_run( + _this: *mut c_void, + _capacity: u32, + _values: *mut u32, + _fetched: *mut u32, + ) -> windows_core::HRESULT { + OPTIONAL_ENUMERATOR_NEXT_CALLS.fetch_add(1, Ordering::Relaxed); + windows_core::HRESULT(0) + } + + #[repr(C)] + struct EnumInterfaceCall { + vtable: *const *mut c_void, + values: [*mut c_void; 2], + fetched: u32, + hresult: windows_core::HRESULT, + } + + unsafe extern "system" fn enum_next_interfaces( + this: *mut c_void, + capacity: u32, + values: *mut *mut c_void, + fetched: *mut u32, + ) -> windows_core::HRESULT { + ENUMERATOR_NEXT_CALLS.fetch_add(1, Ordering::Relaxed); + let call = unsafe { &*(this as *const EnumInterfaceCall) }; + for (index, value) in call + .values + .iter() + .copied() + .take(capacity.min(2) as usize) + .enumerate() + { + unsafe { values.add(index).write(value) }; + } + if !fetched.is_null() { + unsafe { *fetched = call.fetched }; + } + call.hresult + } + + #[repr(C)] + struct OwningVariantArrayCall { + vtable: *const *mut c_void, + values: [*mut c_void; 2], + actual: u32, + hresult: windows_core::HRESULT, + invalid_slot: i32, + } + + unsafe extern "system" fn fill_variant_array( + this: *mut c_void, + values: *mut windows::Win32::System::Variant::VARIANT, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + use windows::Win32::System::Variant::{ + VT_BYREF, VT_EMPTY, VT_I4, VariantClear, VariantCopy, + }; + + let call = unsafe { &*(this as *const OwningVariantArrayCall) }; + for index in 0..capacity as usize { + assert_eq!( + unsafe { automation::variant_vartype_for_test(values.add(index)) }, + VT_EMPTY.0 + ); + } + for (index, pointer) in call + .values + .iter() + .copied() + .take(capacity.min(2) as usize) + .enumerate() + { + let unknown = + std::mem::ManuallyDrop::new(unsafe { IUnknown::from_raw(pointer.cast()) }); + let source = VariantValue::from_unknown(Some(&unknown)); + unsafe { VariantCopy(values.add(index), source.raw()) }.unwrap(); + } + if call.invalid_slot >= 0 && (call.invalid_slot as u32) < capacity { + let slot = unsafe { values.add(call.invalid_slot as usize) }; + unsafe { VariantClear(slot) }.unwrap(); + unsafe { + automation::initialize_variant_slot(slot.cast()); + automation::set_variant_vartype_for_test(slot, VT_I4.0 | VT_BYREF.0); + } + } + unsafe { *actual = call.actual }; + call.hresult + } + + #[repr(C)] + struct OwningStringArrayCall { + vtable: *const *mut c_void, + actual: u32, + hresult: windows_core::HRESULT, + co_task_mem: bool, + } + + unsafe extern "system" fn fill_string_array( + this: *mut c_void, + values: *mut *mut u16, + capacity: u32, + actual: *mut u32, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const OwningStringArrayCall) }; + for index in 0..capacity as usize { + assert!(unsafe { values.add(index).read() }.is_null()); + } + let strings = ["embedded\0nul", "unused"]; + for (index, value) in strings.iter().take(capacity.min(2) as usize).enumerate() { + let utf16 = value.encode_utf16().collect::>(); + let pointer = if call.co_task_mem { + let bytes = (utf16.len() + 1) * size_of::(); + let pointer = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes) }.cast::(); + assert!(!pointer.is_null()); + unsafe { + std::ptr::copy_nonoverlapping(utf16.as_ptr(), pointer, utf16.len()); + pointer.add(utf16.len()).write(0); + } + pointer + } else { + unsafe { windows::Win32::Foundation::SysAllocStringLen(Some(&utf16)) }.into_raw() + as *mut u16 + }; + unsafe { values.add(index).write(pointer) }; + } + unsafe { *actual = call.actual }; + call.hresult + } + + unsafe extern "system" fn enum_next_string_array( + this: *mut c_void, + capacity: u32, + values: *mut *mut u16, + fetched: *mut u32, + ) -> windows_core::HRESULT { + unsafe { fill_string_array(this, values, capacity, fetched) } + } + + unsafe extern "system" fn observe_bstr_array( + _this: *mut c_void, + values: *const *const u16, + count: u32, + ) -> windows_core::HRESULT { + assert_eq!(count, 2); + assert_eq!(unsafe { borrowed_bstr_string(*values) }, "embedded\0nul"); + assert_eq!(unsafe { borrowed_bstr_string(*values.add(1)) }, ""); + windows_core::HRESULT(0) + } + + unsafe extern "system" fn observe_variant_array( + _this: *mut c_void, + values: *const windows::Win32::System::Variant::VARIANT, + count: u32, + ) -> windows_core::HRESULT { + assert_eq!(count, 2); + let first = unsafe { VariantValue::from_owned_raw(values.read()) }.unwrap(); + let second = unsafe { VariantValue::from_owned_raw(values.add(1).read()) }.unwrap(); + assert!(matches!(first.data().unwrap(), VariantData::I32(17))); + assert!(matches!( + second.data().unwrap(), + VariantData::Bstr(value) if value == "embedded\0nul" + )); + std::mem::forget(first); + std::mem::forget(second); + windows_core::HRESULT(0) + } + + unsafe extern "system" fn report_larger_count_with_object( + this: *mut c_void, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + output: *mut *mut c_void, + ) -> windows_core::HRESULT { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + if capacity > 0 { + *buffer = 7; + } + *actual = capacity.saturating_add(1); + *output = call.output; + } + windows_core::HRESULT(0) + } + + unsafe extern "system" fn return_object_with_larger_count( + this: *mut c_void, + buffer: *mut u8, + capacity: u32, + actual: *mut u32, + ) -> *mut c_void { + let call = unsafe { &*(this as *const FailingOutCall) }; + unsafe { + if capacity > 0 { + *buffer = 7; + } + *actual = capacity.saturating_add(1); + } + call.output + } + + unsafe extern "system" fn return_cotaskmem_bytes( + _this: *mut c_void, + buffer: *mut *mut u8, + count: *mut u32, + ) -> windows_core::HRESULT { + let bytes = [10u8, 20, 30, 40]; + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.len()) }.cast::(); + if allocation.is_null() { + return windows_core::HRESULT(0x8007000Eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), allocation, bytes.len()); + *buffer = allocation; + *count = bytes.len() as u32; + } + windows_core::HRESULT(0) + } + + static STRING_ARRAY_CALLS: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn resolve_string_ids( + _this: *mut c_void, + names: *const *const u16, + count: u32, + outputs: *mut i32, + ) -> windows_core::HRESULT { + STRING_ARRAY_CALLS.fetch_add(1, Ordering::Relaxed); + assert_eq!(count, 2); + let names = unsafe { std::slice::from_raw_parts(names, count as usize) }; + let outputs = unsafe { std::slice::from_raw_parts_mut(outputs, count as usize) }; + assert_eq!(outputs, [0, 0]); + let decode = |ptr: *const u16| { + let mut len = 0; + while unsafe { *ptr.add(len) } != 0 { + len += 1; + } + String::from_utf16(unsafe { std::slice::from_raw_parts(ptr, len) }).unwrap() + }; + assert_eq!(decode(names[0]), "First"); + assert_eq!(decode(names[1]), "Second"); + outputs.copy_from_slice(&[17, 29]); + windows_core::HRESULT(0) + } + + unsafe extern "system" fn resolve_string_ids_then_fail( + this: *mut c_void, + names: *const *const u16, + count: u32, + outputs: *mut i32, + ) -> windows_core::HRESULT { + let _ = unsafe { resolve_string_ids(this, names, count, outputs) }; + windows_core::HRESULT(0x80004005u32 as i32) + } + + fn invoke_test_pod( + function: *mut c_void, + signature: MethodSignature, + args: &[Value], + ) -> result::Result> { + let vtable = [function]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + signature + .build(0) + .expect("valid native POD signature") + .plan + .invoke_values((&mut object as *mut FakeComObject).cast(), args) + } + + fn reset_bstr_counts() { + crate::call::reset_bstr_test_counts(); + BSTR_FAKE_ALLOCS.store(0, Ordering::Relaxed); + BSTR_FAKE_FREES.store(0, Ordering::Relaxed); + BSTR_INPUT_MATCHES.store(0, Ordering::Relaxed); + BSTR_EMPTY_INPUT_IS_NONNULL.store(0, Ordering::Relaxed); + } + + fn assert_bstr_counts(allocations: usize, frees: usize) { + let (runtime_allocations, runtime_frees) = crate::call::bstr_test_counts(); + let fake_allocations = BSTR_FAKE_ALLOCS.load(Ordering::Relaxed) as usize; + let fake_frees = BSTR_FAKE_FREES.load(Ordering::Relaxed) as usize; + assert_eq!( + runtime_allocations + fake_allocations, + allocations, + "runtime allocations {runtime_allocations}, callee allocations {fake_allocations}" + ); + assert_eq!( + runtime_frees + fake_frees, + frees, + "runtime frees {runtime_frees}, callee/consumer frees {fake_frees}" + ); + } + + fn take_bstr_output(value: Value) -> Option { + let Value::WinRt(WinRTValue::RawPtr(value)) = value else { + panic!("expected raw BSTR result"); + }; + if value.is_null() { + return None; + } + let value = unsafe { windows_core::BSTR::from_raw(value.cast()) }; + let result = String::try_from(&value).unwrap(); + BSTR_FAKE_FREES.fetch_add(1, Ordering::Relaxed); + drop(value); + Some(result) + } + + #[test] + fn bstr_input_preserves_embedded_nul_and_is_call_local() { + let _guard = BSTR_TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + reset_bstr_counts(); + let original = BstrValue::new("embedded\0nul"); + let first_outputs = invoke_test_pod( + observe_bstr_input as *mut c_void, + MethodSignature::new(&MetadataTable::new()).add_in(Type::bstr()), + &[Value::Bstr(original.clone())], + ) + .unwrap(); + let empty_outputs = invoke_test_pod( + observe_bstr_input as *mut c_void, + MethodSignature::new(&MetadataTable::new()).add_in(Type::bstr()), + &[Value::Bstr(BstrValue::new(""))], + ) + .unwrap(); + + assert!(first_outputs.is_empty()); + assert!(empty_outputs.is_empty()); + assert_eq!(BSTR_INPUT_MATCHES.load(Ordering::Relaxed), 1); + assert_eq!(BSTR_EMPTY_INPUT_IS_NONNULL.load(Ordering::Relaxed), 1); + assert_eq!(original.as_deref(), Some("embedded\0nul")); + assert_bstr_counts(2, 2); + } + + #[test] + fn null_bstr_input_requires_an_explicit_nullable_contract() { + let _guard = BSTR_TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + reset_bstr_counts(); + let null = Value::Bstr(BstrValue::null()); + let required = invoke_test_pod( + observe_bstr_input as *mut c_void, + MethodSignature::new(&MetadataTable::new()).add_in(Type::bstr()), + std::slice::from_ref(&null), + ) + .unwrap_err(); + assert!(required.message().contains("nullable BSTR")); + + let outputs = invoke_test_pod( + observe_bstr_input as *mut c_void, + MethodSignature::new(&MetadataTable::new()).add_in(Type::nullable_bstr()), + &[null], + ) + .unwrap(); + assert!(outputs.is_empty()); + assert_eq!(BSTR_EMPTY_INPUT_IS_NONNULL.load(Ordering::Relaxed), 0); + assert_bstr_counts(0, 0); + } + + #[test] + fn bstr_output_preserves_embedded_nul_and_transfers_one_owner() { + let _guard = BSTR_TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + reset_bstr_counts(); + let outputs = invoke_test_pod( + write_bstr_output as *mut c_void, + MethodSignature::new(&MetadataTable::new()).add_out(Type::bstr()), + &[], + ) + .unwrap(); + + assert_eq!(outputs.len(), 1); + assert_eq!( + take_bstr_output(outputs.into_iter().next().unwrap()).as_deref(), + Some("output\0value") + ); + assert_bstr_counts(1, 1); + } + + #[test] + fn bstr_in_out_success_owns_unchanged_replaced_and_null_slots() { + let _guard = BSTR_TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + for (function, expected, allocations, frees) in [ + ( + leave_bstr_unchanged as *mut c_void, + Some("original\0value"), + 1, + 1, + ), + (replace_bstr as *mut c_void, Some("replaced\0value"), 2, 2), + (null_bstr as *mut c_void, None, 1, 1), + ] { + reset_bstr_counts(); + let original = BstrValue::new("original\0value"); + let outputs = invoke_test_pod( + function, + MethodSignature::new(&MetadataTable::new()).add_in_out(Type::bstr()), + &[Value::Bstr(original.clone())], + ) + .unwrap(); + + assert_eq!(outputs.len(), 1); + assert_eq!( + take_bstr_output(outputs.into_iter().next().unwrap()).as_deref(), + expected + ); + assert_eq!(original.as_deref(), Some("original\0value")); + assert_bstr_counts(allocations, frees); + } + } + + #[test] + fn bstr_in_out_failure_cleans_unchanged_replaced_and_null_slots() { + let _guard = BSTR_TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + for (function, allocations, frees) in [ + (leave_bstr_unchanged_then_fail as *mut c_void, 1, 1), + (replace_bstr_then_fail as *mut c_void, 2, 2), + (null_bstr_then_fail as *mut c_void, 1, 1), + ] { + reset_bstr_counts(); + let original = BstrValue::new("original\0value"); + let error = invoke_test_pod( + function, + MethodSignature::new(&MetadataTable::new()).add_in_out(Type::bstr()), + &[Value::Bstr(original.clone())], + ) + .unwrap_err(); + + assert!(matches!( + error, + result::Error::WindowsError(error) + if error.code() == windows_core::HRESULT(0x80004005u32 as i32) + )); + assert_eq!(original.as_deref(), Some("original\0value")); + assert_bstr_counts(allocations, frees); + } + } + + fn dispatch_invoke_signature(table: &Arc) -> MethodSignature { + MethodSignature::new(table) + .add_in(Type::winrt(table.i32_type())) + .add_in(Type::pointer()) + .add_in(Type::winrt(table.u32_type())) + .add_in(Type::winrt(table.u16_type())) + .add_in(Type::dispatch_params()) + .add_optional_out(Type::variant()) + .add_optional_out(Type::excep_info()) + .add_optional_out(Type::winrt(table.u32_type())) + .capture_dispatch_invoke_hresult() + } + + fn dispatch_invoke_args( + request_result: bool, + request_excep_info: bool, + request_arg_err: bool, + ) -> Vec { + vec![ + Value::WinRt(WinRTValue::I32(7)), + Value::WinRt(WinRTValue::RawPtr(std::ptr::null_mut())), + Value::WinRt(WinRTValue::U32(0)), + Value::WinRt(WinRTValue::U16(1)), + Value::DispatchParams(DispatchParamsValue::new(&[], &[]).unwrap()), + Value::WinRt(WinRTValue::Bool(request_result)), + Value::WinRt(WinRTValue::Bool(request_excep_info)), + Value::WinRt(WinRTValue::Bool(request_arg_err)), + ] + } + + fn dispatch_method( + table: &Arc, + function: DispatchInvokeFn, + ) -> (MethodHandle, [*mut c_void; 7]) { + let interface = register_interface( + table, + "Windows.Win32.System.Com.IDispatch", + GUID::from_u128(0x00020400_0000_0000_c000_000000000046), + InterfaceBase::IUnknown, + ) + .add_method_at(6, "Invoke", dispatch_invoke_signature(table)) + .unwrap(); + let mut vtable = [std::ptr::null_mut(); 7]; + vtable[6] = function as *mut c_void; + (interface.method(6).unwrap(), vtable) + } + + fn invoke_test_buffer( + function: *mut c_void, + signature: MethodSignature, + args: &[Value], + ) -> result::Result> { + let vtable = [function]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + signature + .build(0)? + .plan + .invoke_values((&mut object as *mut FakeComObject).cast(), args) + } + + fn test_union_layout() -> Arc { + Arc::new( + NativeUnionLayout::new( + "Tests.NativeUnion", + size_of::(), + align_of::(), + vec![ + NativeUnionField::new( + "integer", + 1, + NativeUnionFieldType::Scalar(NativeStructScalar::U64), + ) + .unwrap(), + NativeUnionField::new("pointer", 1, NativeUnionFieldType::Pointer).unwrap(), + ], + ) + .unwrap(), + ) + } + + fn borrowed_buffer(bytes: &mut [u8], source_element_size: usize) -> Value { + Value::Buffer( + unsafe { + ComBufferValue::borrowed( + bytes.as_mut_ptr(), + bytes.len(), + source_element_size, + source_element_size == 1, + true, + ) + } + .unwrap(), + ) + } + + #[test] + fn shared_string_input_and_scalar_output_arrays_are_safe_and_authoritative() { + STRING_ARRAY_CALLS.store(0, Ordering::Relaxed); + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_input_string_array(StringEncoding::Utf16, 1) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_caller_output_buffer( + Type::winrt(table.i32_type()), + 1, + None, + BufferCountUnit::Elements, + false, + ) + .unwrap(); + let names = Value::Buffer( + ComBufferValue::string_array( + vec!["First".into(), "Second".into()], + StringEncoding::Utf16, + ) + .unwrap(), + ); + let outputs = Value::Buffer( + ComBufferValue::caller_output(&Type::winrt(table.i32_type()), 2).unwrap(), + ); + let values = invoke_test_buffer( + resolve_string_ids as *mut c_void, + signature.clone(), + &[names.clone(), outputs], + ) + .unwrap(); + assert_eq!(STRING_ARRAY_CALLS.load(Ordering::Relaxed), 1); + let Value::Buffer(output) = &values[0] else { + panic!("caller output must produce an owned scalar array"); + }; + let values = output + .bytes() + .unwrap() + .chunks_exact(size_of::()) + .map(|bytes| i32::from_ne_bytes(bytes.try_into().unwrap())) + .collect::>(); + assert_eq!(values, [17, 29]); + + let failed_output = Value::Buffer( + ComBufferValue::caller_output(&Type::winrt(table.i32_type()), 2).unwrap(), + ); + let error = invoke_test_buffer( + resolve_string_ids_then_fail as *mut c_void, + signature.clone(), + &[ + Value::Buffer( + ComBufferValue::string_array( + vec!["First".into(), "Second".into()], + StringEncoding::Utf16, + ) + .unwrap(), + ), + failed_output, + ], + ) + .unwrap_err(); + assert!(matches!(error, result::Error::WindowsError(_))); + assert_eq!(STRING_ARRAY_CALLS.load(Ordering::Relaxed), 2); + + let short_output = Value::Buffer( + ComBufferValue::caller_output(&Type::winrt(table.i32_type()), 1).unwrap(), + ); + let error = invoke_test_buffer( + resolve_string_ids as *mut c_void, + signature, + &[names, short_output], + ) + .unwrap_err(); + assert!(error.message().contains("different lengths")); + assert_eq!(STRING_ARRAY_CALLS.load(Ordering::Relaxed), 2); + + assert!( + ComBufferValue::string_array(vec!["embedded\0nul".into()], StringEncoding::Utf16) + .unwrap_err() + .message() + .contains("embedded NUL") + ); + assert!( + ComBufferValue::string_array(vec!["caf\u{e9}".into()], StringEncoding::Ansi) + .unwrap_err() + .message() + .contains("ASCII") + ); + assert_eq!(STRING_ARRAY_CALLS.load(Ordering::Relaxed), 2); + } + + #[test] + fn parallel_input_and_output_buffers_can_share_an_authoritative_count() { + let table = MetadataTable::new(); + MethodSignature::new(&table) + .add_input_buffer( + Type::winrt(table.u8_type()), + 1, + None, + BufferCountUnit::Elements, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_caller_output_buffer( + Type::winrt(table.i32_type()), + 1, + None, + BufferCountUnit::Elements, + false, + ) + .unwrap() + .build(0) + .unwrap(); + assert_eq!( + count_from_value(&Value::WinRt(WinRTValue::I32(3))).unwrap(), + 3 + ); + assert!( + count_from_value(&Value::WinRt(WinRTValue::I32(-1))) + .unwrap_err() + .message() + .contains("negative") + ); + } + + #[test] + fn caller_output_storage_cannot_be_aliased_across_parameters() { + STRING_ARRAY_CALLS.store(0, Ordering::Relaxed); + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.i32_type()), + 2, + None, + BufferCountUnit::Elements, + false, + ) + .unwrap() + .add_caller_output_buffer( + Type::winrt(table.i32_type()), + 3, + None, + BufferCountUnit::Elements, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_in(Type::winrt(table.u32_type())); + let output = Value::Buffer( + ComBufferValue::caller_output(&Type::winrt(table.i32_type()), 2).unwrap(), + ); + let error = invoke_test_buffer( + resolve_string_ids as *mut c_void, + signature, + &[output.clone(), output], + ) + .unwrap_err(); + assert!(error.message().contains("cannot be aliased")); + assert_eq!(STRING_ARRAY_CALLS.load(Ordering::Relaxed), 0); + } + + #[test] + fn enumerator_next_preserves_partial_success_and_validates_optional_fetched() { + ENUMERATOR_NEXT_CALLS.store(0, Ordering::Relaxed); + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::winrt(table.u32_type()), 0, 2) + .unwrap() + .add_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult(); + let interface = register_interface( + &table, + "ITestEnumU32", + GUID::from_u128(0x11111111_2222_3333_4444_555555555555), + InterfaceBase::IUnknown, + ) + .add_method_at(3, "Next", signature) + .unwrap(); + let mut vtable = [std::ptr::null_mut(); 4]; + vtable[3] = enum_next_partial_u32 as *mut c_void; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let output = ComBufferValue::enumerator_output(&Type::winrt(table.u32_type()), 2).unwrap(); + let values = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut object as *mut FakeComObject).cast(), + &[Value::Buffer(output)], + ) + } + .unwrap(); + assert!(matches!( + values[0].0, + Value::WinRt(WinRTValue::HResult(value)) if value.0 == 1 + )); + let Value::Buffer(buffer) = &values[1].0 else { + panic!("IEnum::Next must return its fetched values"); + }; + assert_eq!(buffer.count(), 1); + assert_eq!(buffer.bytes(), Some(41u32.to_ne_bytes().as_slice())); + let optional = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::winrt(table.u32_type()), 0, 2) + .unwrap() + .add_optional_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult(); + let interface = register_interface( + &table, + "ITestEnumOptional", + GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee), + InterfaceBase::IUnknown, + ) + .add_method_at(3, "Next", optional) + .unwrap(); + OPTIONAL_ENUMERATOR_NEXT_CALLS.store(0, Ordering::Relaxed); + let optional_vtable = [ + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + optional_enum_next_should_not_run as *mut c_void, + ]; + let mut optional_object = FakeComObject { + vtable: optional_vtable.as_ptr(), + }; + let output = ComBufferValue::enumerator_output(&Type::winrt(table.u32_type()), 2).unwrap(); + let error = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut optional_object as *mut FakeComObject).cast(), + &[Value::Buffer(output), Value::WinRt(WinRTValue::Bool(false))], + ) + } + .unwrap_err(); + assert!(error.message().contains("null pceltFetched")); + assert_eq!(OPTIONAL_ENUMERATOR_NEXT_CALLS.load(Ordering::Relaxed), 0); + } + + #[test] + fn enumerator_next_interface_cleanup_is_bounded_and_exactly_once() { + ENUMERATOR_NEXT_CALLS.store(0, Ordering::Relaxed); + let table = MetadataTable::new(); + let element_iid = GUID::from_u128(0xbbbbbbbb_cccc_dddd_eeee_ffffffffffff); + let element_type = Type::winrt(table.interface(element_iid)); + let signature = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(element_type.clone(), 0, 2) + .unwrap() + .add_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult(); + let interface = register_interface( + &table, + "ITestEnumInterface", + GUID::from_u128(0x22222222_3333_4444_5555_666666666666), + InterfaceBase::IUnknown, + ) + .add_method_at(3, "Next", signature) + .unwrap(); + let first = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let second = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let mut vtable = [std::ptr::null_mut(); 4]; + vtable[3] = enum_next_interfaces as *mut c_void; + let mut call = EnumInterfaceCall { + vtable: vtable.as_ptr(), + values: [ + (&first as *const TrackedComObject).cast_mut().cast(), + (&second as *const TrackedComObject).cast_mut().cast(), + ], + fetched: 1, + hresult: windows_core::HRESULT(0), + }; + let output = ComBufferValue::enumerator_output(&element_type, 2).unwrap(); + let mut values = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut call as *mut EnumInterfaceCall).cast(), + &[Value::Buffer(output)], + ) + } + .unwrap(); + assert_eq!(first.releases.load(Ordering::Relaxed), 0); + assert_eq!(second.releases.load(Ordering::Relaxed), 1); + let Value::Buffer(buffer) = values.pop().unwrap().0 else { + panic!("interface enumerator must return a managed array"); + }; + let adopted = buffer.into_com_values().unwrap(); + assert_eq!(adopted.len(), 1); + drop(adopted); + assert_eq!(first.releases.load(Ordering::Relaxed), 1); + + call.fetched = 3; + call.hresult = windows_core::HRESULT(0); + let output = ComBufferValue::enumerator_output(&element_type, 2).unwrap(); + let error = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut call as *mut EnumInterfaceCall).cast(), + &[Value::Buffer(output)], + ) + } + .unwrap_err(); + assert!(error.message().contains("exceeds requested capacity")); + assert_eq!(first.releases.load(Ordering::Relaxed), 2); + assert_eq!(second.releases.load(Ordering::Relaxed), 2); + + call.fetched = 1; + call.hresult = windows_core::HRESULT(0x80004005u32 as i32); + let output = ComBufferValue::enumerator_output(&element_type, 2).unwrap(); + assert!( + unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut call as *mut EnumInterfaceCall).cast(), + &[Value::Buffer(output)], + ) + } + .is_err() + ); + assert_eq!(first.releases.load(Ordering::Relaxed), 3); + assert_eq!(second.releases.load(Ordering::Relaxed), 3); + + call.values[1] = std::ptr::null_mut(); + call.fetched = 2; + call.hresult = windows_core::HRESULT(0); + let output = ComBufferValue::enumerator_output(&element_type, 2).unwrap(); + let error = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut call as *mut EnumInterfaceCall).cast(), + &[Value::Buffer(output)], + ) + } + .unwrap_err(); + assert!(error.message().contains("null interface pointer")); + assert_eq!(first.releases.load(Ordering::Relaxed), 4); + assert_eq!(second.releases.load(Ordering::Relaxed), 3); + } + + #[test] + fn owning_variant_arrays_are_transactional_and_clear_each_initialized_slot_once() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::variant(), + 1, + Some(2), + BufferCountUnit::Elements, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())); + let first = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let second = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let vtable = [fill_variant_array as *mut c_void]; + let mut call = OwningVariantArrayCall { + vtable: vtable.as_ptr(), + values: [ + (&first as *const TrackedComObject).cast_mut().cast(), + (&second as *const TrackedComObject).cast_mut().cast(), + ], + actual: 1, + hresult: windows_core::HRESULT(0), + invalid_slot: -1, + }; + let invoke = |call: &mut OwningVariantArrayCall| { + let output = + ComBufferValue::caller_output(&Type::variant(), 2).expect("VARIANT output"); + signature.clone().build(0).unwrap().plan.invoke_values( + (call as *mut OwningVariantArrayCall).cast(), + &[Value::Buffer(output)], + ) + }; + + let mut values = invoke(&mut call).unwrap(); + assert_eq!(first.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(second.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(first.releases.load(Ordering::Relaxed), 1); + assert_eq!(second.releases.load(Ordering::Relaxed), 2); + let Value::Buffer(output) = values.pop().unwrap() else { + panic!("VARIANT output must be an owned array"); + }; + let variants = output.into_variants().unwrap(); + assert_eq!(variants.len(), 1); + drop(variants); + assert_eq!(first.releases.load(Ordering::Relaxed), 2); + + call.actual = 3; + let error = invoke(&mut call).unwrap_err(); + assert!(error.message().contains("exceeds capacity")); + assert_eq!(first.releases.load(Ordering::Relaxed), 4); + assert_eq!(second.releases.load(Ordering::Relaxed), 4); + + call.actual = 1; + call.hresult = windows_core::HRESULT(0x80004005u32 as i32); + assert!(invoke(&mut call).is_err()); + assert_eq!(first.releases.load(Ordering::Relaxed), 6); + assert_eq!(second.releases.load(Ordering::Relaxed), 6); + + call.hresult = windows_core::HRESULT(0); + call.invalid_slot = 0; + let error = invoke(&mut call).unwrap_err(); + assert!(error.message().contains("VARIANT BYREF")); + assert_eq!(first.releases.load(Ordering::Relaxed), 8); + assert_eq!(second.releases.load(Ordering::Relaxed), 8); + } + + #[test] + fn owning_bstr_and_ienumstring_arrays_preserve_strings_and_initialized_ranges() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_caller_output_buffer(Type::bstr(), 1, Some(2), BufferCountUnit::Elements, false) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())); + let vtable = [fill_string_array as *mut c_void]; + let mut call = OwningStringArrayCall { + vtable: vtable.as_ptr(), + actual: 1, + hresult: windows_core::HRESULT(0), + co_task_mem: false, + }; + let output = ComBufferValue::caller_output(&Type::bstr(), 2).unwrap(); + let mut values = signature + .build(0) + .unwrap() + .plan + .invoke_values( + (&mut call as *mut OwningStringArrayCall).cast(), + &[Value::Buffer(output)], + ) + .unwrap(); + let Value::Buffer(output) = values.pop().unwrap() else { + panic!("BSTR output must be an owned string array"); + }; + assert_eq!(output.into_strings().unwrap(), ["embedded\0nul"]); + + let enum_signature = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::co_task_mem_wide_string(), 0, 2) + .unwrap() + .add_optional_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult(); + let interface = register_interface( + &table, + "IEnumString", + GUID::from_u128(0x00000101_0000_0000_c000_000000000046), + InterfaceBase::IUnknown, + ) + .add_method_at(3, "Next", enum_signature) + .unwrap(); + let mut enum_vtable = [std::ptr::null_mut(); 4]; + enum_vtable[3] = enum_next_string_array as *mut c_void; + call.vtable = enum_vtable.as_ptr(); + call.actual = 1; + call.hresult = windows_core::HRESULT(1); + call.co_task_mem = true; + let output = + ComBufferValue::enumerator_output(&Type::co_task_mem_wide_string(), 2).unwrap(); + let mut values = unsafe { + interface + .method(3) + .unwrap() + .invoke_values_with_output_kinds( + (&mut call as *mut OwningStringArrayCall).cast(), + &[Value::Buffer(output), Value::WinRt(WinRTValue::Bool(true))], + ) + } + .unwrap(); + assert!(matches!( + values[0].0, + Value::WinRt(WinRTValue::HResult(value)) if value.0 == 1 + )); + let Value::Buffer(output) = values.pop().unwrap().0 else { + panic!("IEnumString output must be an owned string array"); + }; + assert_eq!(output.into_strings().unwrap(), ["embedded"]); + } + + #[test] + fn owning_input_arrays_keep_exact_borrowed_resources_alive_for_the_call() { + let table = MetadataTable::new(); + let bstr_signature = MethodSignature::new(&table) + .add_input_buffer(Type::bstr(), 1, None, BufferCountUnit::Elements) + .unwrap() + .add_in(Type::winrt(table.u32_type())); + invoke_test_buffer( + observe_bstr_array as *mut c_void, + bstr_signature, + &[Value::Buffer(ComBufferValue::bstr_array(vec![ + "embedded\0nul".into(), + String::new(), + ]))], + ) + .unwrap(); + + let variant_signature = MethodSignature::new(&table) + .add_input_buffer(Type::variant(), 1, None, BufferCountUnit::Elements) + .unwrap() + .add_in(Type::winrt(table.u32_type())); + invoke_test_buffer( + observe_variant_array as *mut c_void, + variant_signature, + &[Value::Buffer( + ComBufferValue::variant_array(vec![ + VariantValue::from_i32(17), + VariantValue::from_bstr("embedded\0nul").unwrap(), + ]) + .unwrap(), + )], + ) + .unwrap(); + + let object = TrackedComObject { + vtable: &TRACKED_DISPATCH_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let source = std::mem::ManuallyDrop::new(unsafe { + IUnknown::from_raw( + (&object as *const TrackedComObject) + .cast_mut() + .cast::(), + ) + }); + let array = ComBufferValue::interface_array( + GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee), + vec![(&*source).clone()], + ) + .unwrap(); + assert_eq!(object.addrefs.load(Ordering::Relaxed), 2); + drop(array); + assert_eq!(object.releases.load(Ordering::Relaxed), 2); + } + + #[test] + fn enumerator_next_accepts_exact_owning_elements_and_rejects_unproven_shapes() { + let table = MetadataTable::new(); + assert!( + MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::bstr_pointer(), 0, 2) + .unwrap_err() + .message() + .contains("pointer buffer elements") + ); + MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::bstr(), 0, 2) + .unwrap(); + MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::variant(), 0, 2) + .unwrap(); + MethodSignature::new(&table) + .add_caller_output_buffer(Type::bstr(), 1, None, BufferCountUnit::Elements, false) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .build(0) + .unwrap(); + MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::co_task_mem_wide_string(), 0, 2) + .unwrap(); + assert!( + MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::co_task_mem_pointer(), 0, 2) + .unwrap_err() + .message() + .contains("pointer buffer elements") + ); + let nonstandard = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::winrt(table.guid_type()), 0, 2) + .unwrap() + .add_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult(); + assert!( + register_interface( + &table, + "ITestEnumNonstandard", + GUID::from_u128(0x33333333_4444_5555_6666_777777777777), + InterfaceBase::IUnknown, + ) + .add_method_at(4, "Next", nonstandard) + .unwrap_err() + .message() + .contains("exact IEnum*::Next ABI shape") + ); + let exact_slot_four = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_enumerator_next_buffer(Type::winrt(table.guid_type()), 0, 2) + .unwrap() + .add_out(Type::winrt(table.u32_type())) + .preserve_enumerator_next_hresult_at(4); + register_interface( + &table, + "IEnumExactSlotFour", + GUID::from_u128(0x44444444_5555_6666_7777_888888888888), + InterfaceBase::IUnknown, + ) + .add_method_at(4, "Next", exact_slot_four) + .unwrap(); + } + + #[test] + fn counted_buffer_runtime_handles_actual_failure_sizing_and_cotaskmem() { + let table = MetadataTable::new(); + let caller_signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())); + + let mut storage = [0xCCu8; 8]; + let values = invoke_test_buffer( + read_counted_bytes as *mut c_void, + caller_signature.clone(), + &[borrowed_buffer(&mut storage, 1)], + ) + .unwrap(); + let Value::Buffer(output) = &values[0] else { + panic!("caller output must synthesize an owned buffer"); + }; + assert_eq!(output.bytes(), Some([4, 5, 6].as_slice())); + assert_eq!(output.count(), 3); + + let mut failed_storage = [0xCCu8; 4]; + let error = invoke_test_buffer( + read_counted_bytes_then_fail as *mut c_void, + caller_signature.clone(), + &[borrowed_buffer(&mut failed_storage, 1)], + ) + .unwrap_err(); + assert!(matches!(error, result::Error::WindowsError(_))); + assert_eq!(failed_storage, [9, 0, 0, 0]); + + let mut short_storage = [0u8; 2]; + assert!( + invoke_test_buffer( + report_larger_count as *mut c_void, + caller_signature, + &[borrowed_buffer(&mut short_storage, 1)], + ) + .unwrap_err() + .message() + .contains("exceeds capacity") + ); + + let two_call_signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + true, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())); + let mut sizing_storage = [0u8; 2]; + let sizing = invoke_test_buffer( + report_larger_count as *mut c_void, + two_call_signature, + &[borrowed_buffer(&mut sizing_storage, 1)], + ) + .unwrap(); + let Value::Buffer(sizing) = &sizing[0] else { + panic!("two-call sizing must return a buffer result"); + }; + assert_eq!(sizing.bytes(), Some([7, 0].as_slice())); + assert_eq!(sizing.count(), 4); + + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let vtable = [report_larger_count_with_object as *mut c_void]; + let mut call = FailingOutCall { + vtable: vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let post_call_failure_signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())) + .add_out(Type::owned_com_pointer()); + let mut post_call_storage = [0u8; 2]; + let error = post_call_failure_signature + .build(0) + .unwrap() + .plan + .invoke_values( + (&mut call as *mut FailingOutCall).cast(), + &[borrowed_buffer(&mut post_call_storage, 1)], + ) + .unwrap_err(); + assert!(error.message().contains("exceeds capacity")); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + + let direct_tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let direct_vtable = [return_object_with_larger_count as *mut c_void]; + let mut direct_call = FailingOutCall { + vtable: direct_vtable.as_ptr(), + output: (&direct_tracked as *const TrackedComObject) + .cast_mut() + .cast(), + }; + let direct_failure_signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())) + .returns(Type::owned_com_pointer()); + let mut direct_storage = [0u8; 2]; + let error = direct_failure_signature + .build(0) + .unwrap() + .plan + .invoke_values( + (&mut direct_call as *mut FailingOutCall).cast(), + &[borrowed_buffer(&mut direct_storage, 1)], + ) + .unwrap_err(); + assert!(error.message().contains("exceeds capacity")); + assert_eq!(direct_tracked.releases.load(Ordering::Relaxed), 1); + + let callee_signature = MethodSignature::new(&table) + .add_callee_allocated_buffer( + Type::winrt(table.u8_type()), + 1, + BufferCountUnit::Bytes, + BufferAllocator::CoTaskMem, + ) + .unwrap() + .add_out(Type::winrt(table.u32_type())); + let allocated = + invoke_test_buffer(return_cotaskmem_bytes as *mut c_void, callee_signature, &[]) + .unwrap(); + let Value::Buffer(allocated) = &allocated[0] else { + panic!("callee allocation must synthesize an owned buffer"); + }; + assert_eq!(allocated.bytes(), Some([10, 20, 30, 40].as_slice())); + assert_eq!(allocated.count(), 4); + } + + #[test] + fn fixed_capacity_byte_output_uses_exclusive_zeroed_storage() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_in(Type::pointer()) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 2, + Some(3), + BufferCountUnit::Bytes, + false, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())); + let guid = GUID::from_u128(0x11111111_2222_3333_4444_555555555555); + let input_guid = Value::WinRt(WinRTValue::RawPtr((&guid as *const GUID).cast_mut().cast())); + + let output = + Value::Buffer(ComBufferValue::caller_output(&Type::winrt(table.u8_type()), 4).unwrap()); + let values = invoke_test_buffer( + get_blob_fixed_capacity as *mut c_void, + signature.clone(), + &[input_guid.clone(), output], + ) + .unwrap(); + let Value::Buffer(bytes) = &values[0] else { + panic!("fixed-capacity output must return an owned byte buffer"); + }; + assert_eq!(bytes.bytes(), Some([11, 22, 33].as_slice())); + assert_eq!(bytes.count(), 3); + + let too_small = + Value::Buffer(ComBufferValue::caller_output(&Type::winrt(table.u8_type()), 2).unwrap()); + assert!(matches!( + invoke_test_buffer( + get_blob_fixed_capacity as *mut c_void, + signature.clone(), + &[input_guid.clone(), too_small], + ), + Err(result::Error::WindowsError(_)) + )); + + let failed = + Value::Buffer(ComBufferValue::caller_output(&Type::winrt(table.u8_type()), 4).unwrap()); + assert!(matches!( + invoke_test_buffer( + get_blob_then_fail as *mut c_void, + signature, + &[input_guid, failed], + ), + Err(result::Error::WindowsError(_)) + )); + } + + #[test] + fn empty_buffers_use_non_null_storage_and_slice_lengths_are_bounded() { + let empty = + unsafe { ComBufferValue::borrowed(std::ptr::null_mut(), 0, 1, true, false).unwrap() }; + let (ptr, byte_len, ..) = empty.borrowed_parts().unwrap(); + assert!(!ptr.is_null()); + assert_eq!(byte_len, 0); + let null = ComBufferValue::null(); + let (ptr, byte_len, ..) = null.borrowed_parts().unwrap(); + assert!(ptr.is_null()); + assert_eq!(byte_len, 0); + + let table = MetadataTable::new(); + let element = BufferElementPlan::from_type(&Type::winrt(table.u8_type())).unwrap(); + assert!( + count_bytes(usize::MAX, &element, BufferCountUnit::Bytes) + .unwrap_err() + .message() + .contains("projected Buffer size") + ); + } + + #[test] + fn one_in_out_count_can_be_capacity_and_actual_length() { + let table = MetadataTable::new(); + MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(1), + BufferCountUnit::Bytes, + false, + ) + .unwrap() + .add_in_out(Type::winrt(table.u32_type())) + .build(0) + .unwrap(); + } + + #[test] + fn counted_buffer_runtime_rejects_width_alignment_and_owned_elements() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_input_buffer( + Type::winrt(table.u32_type()), + 1, + None, + BufferCountUnit::Elements, + ) + .unwrap() + .add_in(Type::winrt(table.u32_type())); + + let mut wrong_width = [0u8; 8]; + let value = Value::Buffer( + unsafe { + ComBufferValue::borrowed( + wrong_width.as_mut_ptr(), + wrong_width.len(), + 2, + false, + true, + ) + } + .unwrap(), + ); + assert!( + invoke_test_buffer( + read_counted_bytes as *mut c_void, + signature.clone(), + &[value] + ) + .unwrap_err() + .message() + .contains("element width mismatch") + ); + + let mut partial_element = [0u8; 6]; + let value = Value::Buffer( + unsafe { + ComBufferValue::borrowed( + partial_element.as_mut_ptr(), + partial_element.len(), + 1, + true, + true, + ) + } + .unwrap(), + ); + assert!( + invoke_test_buffer( + read_counted_bytes as *mut c_void, + signature.clone(), + &[value] + ) + .unwrap_err() + .message() + .contains("not a multiple") + ); + + let mut unaligned = [0u8; 9]; + let offset = (0..=1) + .find(|offset| (unaligned.as_ptr() as usize + offset) % 4 != 0) + .expect("one adjacent byte address must be unaligned"); + let value = Value::Buffer( + unsafe { + ComBufferValue::borrowed(unaligned.as_mut_ptr().add(offset), 8, 4, false, true) + } + .unwrap(), + ); + assert!( + invoke_test_buffer(read_counted_bytes as *mut c_void, signature, &[value]) + .unwrap_err() + .message() + .contains("not aligned") + ); + + assert!( + MethodSignature::new(&table) + .add_input_buffer(Type::pointer(), 1, None, BufferCountUnit::Elements) + .unwrap_err() + .message() + .contains("explicit element ownership") + ); + let layout = test_pod_layout("BufferPod"); + let element = BufferElementPlan::from_type(&Type::native_struct(layout.clone())).unwrap(); + let mut raw = vec![0u8; layout.size()]; + let unbranded = unsafe { + ComBufferValue::borrowed(raw.as_mut_ptr(), raw.len(), 1, true, false).unwrap() + }; + assert!( + prepare_borrowed_buffer(&unbranded, &element, false) + .unwrap_err() + .message() + .contains("layout identity") + ); + let branded = ComBufferValue::native_struct_input(raw, &layout).unwrap(); + assert_eq!(branded.count(), 1); + prepare_borrowed_buffer(&branded, &element, false).unwrap(); + + let borrowed = + unsafe { ComBufferValue::borrowed(unaligned.as_mut_ptr(), 8, 4, false, false) } + .unwrap(); + assert_eq!(borrowed.count(), 2); + } + + #[test] + fn native_pod_runtime_supports_value_pointer_out_and_in_out_storage() { + let table = MetadataTable::new(); + let layout = test_pod_layout("TestPod"); + let input = test_pod_value( + layout.clone(), + TestPod { + first: 10, + second: 20, + tag: 12, + }, + ); + + let by_value = invoke_test_pod( + sum_pod_by_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::native_struct(layout.clone())) + .add_out(Type::winrt(table.u32_type())), + &[Value::NativeStruct(input.clone())], + ) + .unwrap(); + assert!(matches!(&by_value[0], Value::WinRt(WinRTValue::U32(42)))); + + let pointer = invoke_test_pod( + sum_pod_pointer as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::native_struct_pointer(layout.clone())) + .add_out(Type::winrt(table.u32_type())), + &[Value::NativeStruct(input.clone())], + ) + .unwrap(); + assert!(matches!(&pointer[0], Value::WinRt(WinRTValue::U32(42)))); + + let nullable = invoke_test_pod( + nullable_pod_pointer_is_null as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::nullable_native_struct_pointer(layout.clone())) + .add_out(Type::winrt(table.u32_type())), + &[Value::WinRt(WinRTValue::Null)], + ) + .unwrap(); + assert!(matches!(&nullable[0], Value::WinRt(WinRTValue::U32(1)))); + + let aligned_layout = Arc::new( + NativeStructLayout::new( + "AlignedPod", + size_of::(), + align_of::(), + vec![ + NativeStructField::new( + "value", + 0, + 1, + NativeStructFieldType::Scalar(NativeStructScalar::U64), + ) + .unwrap(), + ], + ) + .unwrap(), + ); + invoke_test_pod( + require_aligned_pod as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::native_struct_pointer(aligned_layout.clone())), + &[Value::NativeStruct( + NativeStructValue::new(aligned_layout, 42u64.to_ne_bytes().to_vec()).unwrap(), + )], + ) + .unwrap(); + + let output = invoke_test_pod( + write_zeroed_pod as *mut c_void, + MethodSignature::new(&table).add_out(Type::native_struct(layout.clone())), + &[], + ) + .unwrap(); + let Value::NativeStruct(output) = &output[0] else { + panic!("expected native POD output"); + }; + let output = read_test_pod(output); + assert_eq!((output.first, output.second, output.tag), (40, 2, 7)); + + let in_out_layout = layout.clone(); + let in_out = invoke_test_pod( + update_pod_in_out as *mut c_void, + MethodSignature::new(&table).add_in_out(Type::native_struct(layout.clone())), + &[Value::NativeStruct(input.clone())], + ) + .unwrap(); + let Value::NativeStruct(in_out) = &in_out[0] else { + panic!("expected native POD in/out result"); + }; + let in_out = read_test_pod(in_out); + assert_eq!((in_out.first, in_out.second, in_out.tag), (11, 22, 15)); + + let nullable_in_out = invoke_test_pod( + update_nullable_pod_in_out as *mut c_void, + MethodSignature::new(&table) + .add_in_out(Type::nullable_native_struct_pointer(in_out_layout)), + &[Value::NativeStruct(input)], + ) + .unwrap(); + let Value::NativeStruct(nullable_in_out) = &nullable_in_out[0] else { + panic!("expected nullable native POD in/out result"); + }; + let nullable_in_out = read_test_pod(nullable_in_out); + assert_eq!( + ( + nullable_in_out.first, + nullable_in_out.second, + nullable_in_out.tag + ), + (11, 22, 15) + ); + + let nullable_null = invoke_test_pod( + update_nullable_pod_in_out as *mut c_void, + MethodSignature::new(&table).add_in_out(Type::nullable_native_struct_pointer(layout)), + &[Value::WinRt(WinRTValue::Null)], + ) + .unwrap(); + assert!(matches!(&nullable_null[0], Value::WinRt(WinRTValue::Null))); + } + + #[test] + fn native_pod_runtime_rejects_wrong_identity_and_size() { + let table = MetadataTable::new(); + let expected = test_pod_layout("ExpectedPod"); + let wrong = test_pod_layout("WrongPod"); + assert!(NativeStructValue::new(expected.clone(), vec![0; expected.size() - 1]).is_err()); + let error = invoke_test_pod( + sum_pod_by_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::native_struct(expected)) + .add_out(Type::winrt(table.u32_type())), + &[Value::NativeStruct(NativeStructValue::zeroed(wrong))], + ) + .unwrap_err(); + assert!(error.message().contains("type mismatch")); + } + + #[test] + fn native_union_runtime_requires_brand_and_active_field() { + let table = MetadataTable::new(); + let layout = test_union_layout(); + let value = + NativeUnionValue::new(layout.clone(), "integer", 42u64.to_ne_bytes().to_vec()).unwrap(); + let output = invoke_test_pod( + read_native_union as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::native_union_pointer(layout.clone())) + .add_out(Type::winrt(table.u64_type())), + &[Value::NativeUnion(value)], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::U64(42))] + )); + assert!(NativeUnionValue::zeroed(layout.clone(), "missing").is_err()); + assert!( + MethodSignature::new(&table) + .add_out(Type::native_union_pointer(layout)) + .build(0) + .unwrap_err() + .message() + .contains("active-field") + ); + } + + #[test] + fn automation_values_roundtrip_through_fake_com_vtables() { + let table = MetadataTable::new(); + + let variant = VariantValue::from_bstr("automation").unwrap(); + let output = invoke_test_pod( + copy_variant_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::variant()) + .add_out(Type::variant()), + &[Value::Variant(variant)], + ) + .unwrap(); + let Value::Variant(output) = &output[0] else { + panic!("expected VARIANT output"); + }; + assert!(matches!( + output.data().unwrap(), + VariantData::Bstr(value) if value == "automation" + )); + + let array = SafeArrayValue::new( + SafeArrayElementType::I32, + vec![SafeArrayBound::new(-1, 2).unwrap()], + vec![ + SafeArrayElementValue::I32(10), + SafeArrayElementValue::I32(20), + ], + ) + .unwrap(); + invoke_test_pod( + observe_aliased_safe_arrays as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::I32)) + .add_in(Type::typed_safe_array(SafeArrayElementType::I32)), + &[ + Value::SafeArray(array.clone()), + Value::SafeArray(array.clone()), + ], + ) + .unwrap(); + let output = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::I32)) + .add_out(Type::typed_safe_array(SafeArrayElementType::I32)), + &[Value::SafeArray(array)], + ) + .unwrap(); + let Value::SafeArray(output) = &output[0] else { + panic!("expected SAFEARRAY output"); + }; + assert_eq!(output.bounds(), &[SafeArrayBound::new(-1, 2).unwrap()]); + assert!(matches!( + output.elements().unwrap().as_slice(), + [ + SafeArrayElementValue::I32(10), + SafeArrayElementValue::I32(20) + ] + )); + + let propvariant = PropVariantValue::from_vector(PropVariantVector::String(vec![ + "first".into(), + "second".into(), + ])) + .unwrap(); + let output = invoke_test_pod( + copy_prop_variant_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::prop_variant()) + .add_out(Type::prop_variant()), + &[Value::PropVariant(propvariant)], + ) + .unwrap(); + let Value::PropVariant(output) = &output[0] else { + panic!("expected PROPVARIANT output"); + }; + assert!(matches!( + output.data().unwrap(), + PropVariantData::Vector(PropVariantVector::String(values)) + if values == ["first", "second"] + )); + } + + #[test] + fn variant_by_value_abi_matches_windows_and_preserves_owned_inputs() { + use windows::Win32::System::Variant::{VARIANT, VARIANT_0, VARIANT_0_0, VARIANT_0_0_0}; + + #[cfg(target_pointer_width = "64")] + { + assert_eq!(size_of::(), 24); + assert_eq!(align_of::(), 8); + } + #[cfg(target_pointer_width = "32")] + { + assert_eq!(size_of::(), 16); + assert_eq!(align_of::(), 8); + } + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::(), size_of::() - 8); + + let ffi = ParameterType::variant_by_value().libffi_type(); + let pointer = libffi::middle::Type::pointer(); + let result = libffi::middle::Type::i32(); + let mut argument_types = [pointer.as_raw_ptr(), ffi.as_raw_ptr()]; + let mut cif = libffi::low::ffi_cif::default(); + #[cfg(all(windows, target_arch = "x86"))] + let abi = libffi_sys::ffi_abi_FFI_STDCALL; + #[cfg(not(all(windows, target_arch = "x86")))] + let abi = libffi::middle::ffi_abi_FFI_DEFAULT_ABI; + unsafe { + libffi::low::prep_cif( + &mut cif, + abi, + argument_types.len(), + result.as_raw_ptr(), + argument_types.as_mut_ptr(), + ) + .unwrap() + }; + let raw = unsafe { &*ffi.as_raw_ptr() }; + assert_eq!(raw.size, size_of::()); + assert_eq!(usize::from(raw.alignment), align_of::()); + + let table = MetadataTable::new(); + let signature = || { + MethodSignature::new(&table) + .add_in(Type::variant_by_value()) + .add_out(Type::winrt(table.u32_type())) + }; + + let scalar = invoke_test_pod( + observe_variant_by_value_i32 as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::variant_by_value()) + .add_out(Type::winrt(table.i32_type())), + &[Value::Variant(VariantValue::from_i32(42))], + ) + .unwrap(); + assert!(matches!( + scalar.as_slice(), + [Value::WinRt(WinRTValue::I32(42))] + )); + + let bstr = VariantValue::from_bstr("by value").unwrap(); + let bstr_result = invoke_test_pod( + observe_variant_by_value_bstr as *mut c_void, + signature(), + &[Value::Variant(bstr.clone())], + ) + .unwrap(); + assert!(matches!( + bstr_result.as_slice(), + [Value::WinRt(WinRTValue::U32(1))] + )); + assert!(matches!( + bstr.data().unwrap(), + VariantData::Bstr(value) if value == "by value" + )); + + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&tracked as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + let interface = VariantValue::from_unknown(Some(borrowed)); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 1); + let interface_result = invoke_test_pod( + observe_variant_by_value_unknown as *mut c_void, + signature(), + &[Value::Variant(interface.clone())], + ) + .unwrap(); + assert!(matches!( + interface_result.as_slice(), + [Value::WinRt(WinRTValue::U32(1))] + )); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + + let error = invoke_test_pod( + mutate_variant_by_value_then_fail as *mut c_void, + MethodSignature::new(&table).add_in(Type::variant_by_value()), + &[Value::Variant(interface.clone())], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 3); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 2); + assert!(matches!( + interface.data().unwrap(), + VariantData::Unknown(Some(_)) + )); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 4); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 3); + + let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _copy = automation::VariantCopyValue::new(&interface).unwrap(); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 5); + panic!("exercise panic-safe VARIANT cleanup"); + })); + assert!(unwind.is_err()); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 4); + + drop(interface); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 5); + + VARIANT_BY_VALUE_DISPATCH_CALLS.store(0, Ordering::Relaxed); + let by_value_signature = || MethodSignature::new(&table).add_in(Type::variant_by_value()); + let error = invoke_test_pod( + count_variant_by_value_dispatch as *mut c_void, + by_value_signature(), + &[Value::WinRt(WinRTValue::I32(1))], + ) + .unwrap_err(); + assert!(error.message().contains("expected by-value VARIANT")); + + let unsupported = VariantValue::from_i32(1); + unsafe { + automation::set_variant_vartype_for_test( + unsupported.raw_mut(), + windows::Win32::System::Variant::VT_DATE.0, + ) + }; + let error = invoke_test_pod( + count_variant_by_value_dispatch as *mut c_void, + by_value_signature(), + &[Value::Variant(unsupported)], + ) + .unwrap_err(); + assert!(error.message().contains("unsupported VARIANT VARTYPE")); + + let byref = VariantValue::from_i32(1); + unsafe { + automation::set_variant_vartype_for_test( + byref.raw_mut(), + windows::Win32::System::Variant::VT_I4.0 + | windows::Win32::System::Variant::VT_BYREF.0, + ) + }; + let error = invoke_test_pod( + count_variant_by_value_dispatch as *mut c_void, + by_value_signature(), + &[Value::Variant(byref)], + ) + .unwrap_err(); + assert!(error.message().contains("VARIANT BYREF")); + assert_eq!(VARIANT_BY_VALUE_DISPATCH_CALLS.load(Ordering::Relaxed), 0); + } + + #[test] + fn dispatch_params_and_optional_invoke_outputs_roundtrip() { + let table = MetadataTable::new(); + let params = DispatchParamsValue::new( + &[ + VariantValue::from_i32(10), + VariantValue::from_i32(20), + VariantValue::from_i32(30), + ], + &[100, 200], + ) + .unwrap(); + let signature = MethodSignature::new(&table) + .add_in(Type::dispatch_params()) + .add_optional_out(Type::variant()) + .add_optional_out(Type::excep_info()) + .add_optional_out(Type::winrt(table.u32_type())); + + DISPATCH_OPTIONAL_NULL_MASK.store(u32::MAX, Ordering::Relaxed); + let output = invoke_test_pod( + inspect_dispatch_params_and_fill_outputs as *mut c_void, + signature.clone(), + &[ + Value::DispatchParams(params.clone()), + Value::WinRt(WinRTValue::Bool(true)), + Value::WinRt(WinRTValue::Bool(true)), + Value::WinRt(WinRTValue::Bool(true)), + ], + ) + .unwrap(); + assert_eq!(DISPATCH_OPTIONAL_NULL_MASK.load(Ordering::Relaxed), 0); + assert_eq!(output.len(), 3); + assert!(matches!( + output[0], + Value::Variant(ref value) + if matches!(value.data().unwrap(), VariantData::I32(30)) + )); + let Value::ExcepInfo(info) = &output[1] else { + panic!("expected EXCEPINFO output"); + }; + assert_eq!(info.code(), 17); + assert_eq!(info.source(), Some("source")); + assert_eq!(info.description(), Some("description")); + assert_eq!(info.help_file(), Some("help.chm")); + assert_eq!(info.help_context(), 91); + assert_eq!(info.scode(), 0x80020009u32 as i32); + assert!(matches!(output[2], Value::WinRt(WinRTValue::U32(2)))); + + let output = invoke_test_pod( + inspect_dispatch_params_and_fill_outputs as *mut c_void, + signature, + &[ + Value::DispatchParams(params), + Value::WinRt(WinRTValue::Bool(false)), + Value::WinRt(WinRTValue::Bool(false)), + Value::WinRt(WinRTValue::Bool(false)), + ], + ) + .unwrap(); + assert_eq!(DISPATCH_OPTIONAL_NULL_MASK.load(Ordering::Relaxed), 0b111); + assert!( + output + .iter() + .all(|value| matches!(value, Value::WinRt(WinRTValue::Null))) + ); + } + + #[test] + fn dispatch_invoke_captures_failure_only_outputs_and_success_result() { + let table = MetadataTable::new(); + + DISPATCH_DEFERRED_SUCCESS_CALLS.store(0, Ordering::Relaxed); + let (method, vtable) = dispatch_method(&table, dispatch_invoke_exception); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let failure = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(true, true, true), + ) + } + .unwrap(); + assert_eq!(failure.hresult(), DISP_E_EXCEPTION); + assert!(failure.result().is_none()); + let info = failure.excep_info().expect("deferred EXCEPINFO"); + assert_eq!(info.code(), 23); + assert_eq!(info.source(), Some("deferred source")); + assert_eq!(info.description(), Some("deferred description")); + assert_eq!(info.help_file(), Some("deferred help")); + assert_eq!(info.help_context(), 42); + assert_eq!(info.scode(), DISP_E_EXCEPTION.0); + assert!(failure.arg_err().is_none()); + assert!(failure.finalization_error().is_none()); + assert_eq!(DISPATCH_DEFERRED_SUCCESS_CALLS.load(Ordering::Relaxed), 1); + + let (method, vtable) = dispatch_method(&table, dispatch_invoke_type_mismatch); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let failure = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(true, true, true), + ) + } + .unwrap(); + assert_eq!(failure.hresult(), DISP_E_TYPEMISMATCH); + assert!(failure.result().is_none()); + assert!(failure.excep_info().is_none()); + assert_eq!(failure.arg_err(), Some(3)); + + let (method, vtable) = dispatch_method(&table, dispatch_invoke_fail); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let failure = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(true, true, true), + ) + } + .unwrap(); + assert_eq!( + failure.hresult(), + windows_core::HRESULT(0x80004005u32 as i32) + ); + assert!(failure.result().is_none()); + assert!(failure.excep_info().is_none()); + assert!(failure.arg_err().is_none()); + + DISPATCH_DEFERRED_SUCCESS_CALLS.store(0, Ordering::Relaxed); + let (method, vtable) = dispatch_method(&table, dispatch_invoke_success); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let success = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(true, true, true), + ) + } + .unwrap(); + assert!(success.hresult().is_ok()); + assert!(matches!( + success.result().unwrap().data().unwrap(), + VariantData::I32(42) + )); + assert!(success.excep_info().is_none()); + assert!(success.arg_err().is_none()); + assert_eq!(DISPATCH_DEFERRED_SUCCESS_CALLS.load(Ordering::Relaxed), 0); + } + + #[test] + fn dispatch_invoke_cleans_failed_result_and_preserves_deferred_failure_cause() { + let table = MetadataTable::new(); + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let (method, vtable) = dispatch_method(&table, dispatch_invoke_partial_result_then_fail); + let mut object = DispatchTrackedCall { + vtable: vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let failure = unsafe { + method.invoke_dispatch( + (&mut object as *mut DispatchTrackedCall).cast(), + &dispatch_invoke_args(true, false, false), + ) + } + .unwrap(); + assert!(failure.hresult().is_err()); + assert!(failure.result().is_none()); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 2); + + DISPATCH_DEFERRED_FAILURE_CALLS.store(0, Ordering::Relaxed); + let (method, vtable) = + dispatch_method(&table, dispatch_invoke_exception_with_failing_deferred); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let failure = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(false, true, false), + ) + } + .unwrap(); + assert_eq!(failure.hresult(), DISP_E_EXCEPTION); + assert!(failure.excep_info().is_none()); + assert!( + failure + .finalization_error() + .unwrap() + .message() + .contains("0x80004005") + ); + assert_eq!(DISPATCH_DEFERRED_FAILURE_CALLS.load(Ordering::Relaxed), 1); + } + + #[test] + fn dispatch_invoke_keeps_disabled_outputs_null_and_fails_closed_elsewhere() { + let table = MetadataTable::new(); + DISPATCH_INVOKE_NULL_MASK.store(0, Ordering::Relaxed); + let (method, vtable) = dispatch_method(&table, dispatch_invoke_disabled_outputs); + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let success = unsafe { + method.invoke_dispatch( + (&mut object as *mut FakeComObject).cast(), + &dispatch_invoke_args(false, false, false), + ) + } + .unwrap(); + assert!(success.hresult().is_ok()); + assert!(success.result().is_none()); + assert!(success.excep_info().is_none()); + assert!(success.arg_err().is_none()); + assert_eq!(DISPATCH_INVOKE_NULL_MASK.load(Ordering::Relaxed), 0b111); + + let not_dispatch = register_interface( + &table, + "Tests.INotDispatch", + GUID::from_u128(0x10000000_0000_0000_0000_000000000010), + InterfaceBase::IUnknown, + ); + let error = not_dispatch + .add_method_at(6, "Invoke", dispatch_invoke_signature(&table)) + .unwrap_err(); + assert!( + error + .message() + .contains("restricted to the exact IDispatch::Invoke") + ); + } + + #[test] + fn excep_info_deferred_fill_runs_once_and_cleans_on_every_failure_path() { + let table = MetadataTable::new(); + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let output = invoke_test_pod( + install_deferred_excep_info as *mut c_void, + MethodSignature::new(&table).add_out(Type::excep_info()), + &[], + ) + .unwrap(); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + let Value::ExcepInfo(info) = &output[0] else { + panic!("expected EXCEPINFO output"); + }; + assert_eq!(info.code(), 23); + assert_eq!(info.source(), Some("deferred source")); + assert_eq!(info.description(), Some("deferred description")); + assert_eq!(info.help_file(), Some("deferred help")); + assert_eq!(info.help_context(), 42); + + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let error = invoke_test_pod( + install_failing_deferred_excep_info as *mut c_void, + MethodSignature::new(&table).add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("0x80004005")); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let error = invoke_test_pod( + install_reinstalling_deferred_excep_info as *mut c_void, + MethodSignature::new(&table).add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("installed another callback")); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + + let error = invoke_test_pod( + write_reserved_excep_info as *mut c_void, + MethodSignature::new(&table).add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("reserved fields")); + + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let error = invoke_test_pod( + install_deferred_excep_info_then_fail as *mut c_void, + MethodSignature::new(&table).add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("0x80004005")); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let error = invoke_test_pod( + write_unsupported_variant_and_deferred_excep_info as *mut c_void, + MethodSignature::new(&table) + .add_out(Type::variant()) + .add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("unsupported VARIANT")); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + + DEFERRED_FILL_CALLS.store(0, Ordering::Relaxed); + let error = invoke_test_pod( + write_unsupported_variant_and_deferred_excep_info_then_fail as *mut c_void, + MethodSignature::new(&table) + .add_out(Type::variant()) + .add_out(Type::excep_info()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("0x80004005")); + assert_eq!(DEFERRED_FILL_CALLS.load(Ordering::Relaxed), 1); + } + + #[test] + fn dispatch_params_variant_copies_release_exactly_once() { + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&tracked as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + let variant = VariantValue::from_unknown(Some(borrowed)); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 1); + + let params = DispatchParamsValue::new(std::slice::from_ref(&variant), &[]).unwrap(); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 2); + assert!(DispatchParamsValue::new(std::slice::from_ref(&variant), &[1, 2]).is_err()); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 2); + + drop(variant); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + drop(params); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 2); + } + + #[test] + fn automation_validation_failure_cleans_other_owned_outputs() { + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let vtable = [write_unsupported_variant_and_object as *mut c_void]; + let mut call = FailingOutCall { + vtable: vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let table = MetadataTable::new(); + let error = MethodSignature::new(&table) + .add_out(Type::variant()) + .add_out(Type::owned_com_pointer()) + .build(0) + .unwrap() + .plan + .invoke_values((&mut call as *mut FailingOutCall).cast(), &[]) + .unwrap_err(); + + assert!(error.message().contains("unsupported VARIANT")); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + + let reversed_tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let reversed_vtable = [write_object_and_unsupported_variant as *mut c_void]; + let mut reversed_call = FailingOutCall { + vtable: reversed_vtable.as_ptr(), + output: (&reversed_tracked as *const TrackedComObject) + .cast_mut() + .cast(), + }; + let error = MethodSignature::new(&table) + .add_out(Type::owned_com_pointer()) + .add_out(Type::variant()) + .build(0) + .unwrap() + .plan + .invoke_values((&mut reversed_call as *mut FailingOutCall).cast(), &[]) + .unwrap_err(); + assert!(error.message().contains("unsupported VARIANT")); + assert_eq!(reversed_tracked.releases.load(Ordering::Relaxed), 1); + + let direct_tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let direct_vtable = [return_object_with_unsupported_variant as *mut c_void]; + let mut direct_call = FailingOutCall { + vtable: direct_vtable.as_ptr(), + output: (&direct_tracked as *const TrackedComObject) + .cast_mut() + .cast(), + }; + let error = MethodSignature::new(&table) + .add_out(Type::variant()) + .returns(Type::owned_com_pointer()) + .build(0) + .unwrap() + .plan + .invoke_values((&mut direct_call as *mut FailingOutCall).cast(), &[]) + .unwrap_err(); + assert!(error.message().contains("unsupported VARIANT")); + assert_eq!(direct_tracked.releases.load(Ordering::Relaxed), 1); + + AUTOMATION_DISPATCH_CALLS.store(0, Ordering::Relaxed); + let preflight_vtable = [count_automation_dispatch as *mut c_void]; + let mut preflight = FakeComObject { + vtable: preflight_vtable.as_ptr(), + }; + let error = call_method( + 0, + (&mut preflight as *mut FakeComObject).cast(), + MethodSignature::new(&table).add_out(Type::variant()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("COM value invocation path")); + assert_eq!(AUTOMATION_DISPATCH_CALLS.load(Ordering::Relaxed), 0); + } + + #[test] + fn automation_interface_elements_addref_and_release_exactly_once_per_owner() { + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&tracked as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + + { + let variant = VariantValue::from_unknown(Some(borrowed)); + let data = variant.data().unwrap(); + assert!(matches!(data, VariantData::Unknown(Some(_)))); + drop(data); + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 1); + } + assert_eq!(tracked.releases.load(Ordering::Relaxed), 2); + + { + let array = SafeArrayValue::new( + SafeArrayElementType::Unknown, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::Unknown(Some(borrowed.clone()))], + ) + .unwrap(); + drop(array.elements().unwrap()); + } + assert_eq!(tracked.addrefs.load(Ordering::Relaxed), 5); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 5); + + let dispatch = TrackedComObject { + vtable: &TRACKED_DISPATCH_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&dispatch as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + { + let variant = VariantValue::from_dispatch(Some(borrowed)).unwrap(); + assert_eq!(dispatch.addrefs.load(Ordering::Relaxed), 1); + let data = variant.data().unwrap(); + assert!(matches!(data, VariantData::Dispatch(Some(_)))); + drop(data); + assert_eq!(dispatch.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(dispatch.releases.load(Ordering::Relaxed), 1); + } + assert_eq!(dispatch.addrefs.load(Ordering::Relaxed), 2); + assert_eq!(dispatch.releases.load(Ordering::Relaxed), 2); + + let typed = TrackedComObject { + vtable: &TRACKED_DISPATCH_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&typed as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + let iid = GUID::from_u128(0x5347ad7b_c355_46f8_aff5_909033582f63); + { + let array = SafeArrayValue::new_interface( + iid, + vec![SafeArrayBound::new(-1, 1).unwrap()], + vec![SafeArrayElementValue::Unknown(Some(borrowed.clone()))], + ) + .unwrap(); + assert_eq!(array.interface_iid(), Some(iid)); + drop(array.elements().unwrap()); } - windows_core::HRESULT(0x80004005u32 as i32) + assert_eq!(typed.addrefs.load(Ordering::Relaxed), 5); + assert_eq!(typed.releases.load(Ordering::Relaxed), 5); + + let mismatched = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&mismatched as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + assert!( + SafeArrayValue::new_interface( + iid, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::Unknown(Some(borrowed.clone()))], + ) + .is_err() + ); + assert_eq!(mismatched.addrefs.load(Ordering::Relaxed), 1); + assert_eq!(mismatched.releases.load(Ordering::Relaxed), 1); } #[test] - fn interface_and_method_handle_are_send_and_sync() { - fn assert_send_sync() {} + fn typed_interface_outputs_validate_generic_descriptor_elements() { + let expected_iid = GUID::from_u128(0x5347ad7b_c355_46f8_aff5_909033582f63); + let table = MetadataTable::new(); - assert_send_sync::(); - assert_send_sync::(); - } + for descriptor_iid in [None, Some(IUnknown::IID)] { + let tracked = TrackedComObject { + vtable: &TRACKED_DISPATCH_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&tracked as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + let bounds = vec![SafeArrayBound::new(-3, 1).unwrap()]; + let elements = vec![SafeArrayElementValue::Unknown(Some(borrowed.clone()))]; + let array = if let Some(iid) = descriptor_iid { + SafeArrayValue::new_interface(iid, bounds, elements).unwrap() + } else { + SafeArrayValue::new(SafeArrayElementType::Unknown, bounds, elements).unwrap() + }; - unsafe extern "system" fn return_u32(_this: *mut c_void) -> u32 { - u32::MAX - } + let mut output = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::Unknown)) + .add_out(Type::typed_interface_safe_array(expected_iid)), + &[Value::SafeArray(array)], + ) + .unwrap(); + let Value::SafeArray(output) = output.pop().unwrap() else { + panic!("expected typed SAFEARRAY output") + }; + assert_eq!(output.interface_iid(), Some(expected_iid)); + assert_eq!(output.bounds(), [SafeArrayBound::new(-3, 1).unwrap()]); + drop(output.elements().unwrap()); + drop(output); + assert_eq!( + tracked.addrefs.load(Ordering::Relaxed), + tracked.releases.load(Ordering::Relaxed) + ); + } - unsafe extern "system" fn return_s_false(_this: *mut c_void) -> windows_core::HRESULT { - windows_core::HRESULT(1) + let mismatched = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let raw = (&mismatched as *const TrackedComObject).cast_mut().cast(); + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) }.unwrap(); + let array = SafeArrayValue::new( + SafeArrayElementType::Unknown, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::Unknown(Some(borrowed.clone()))], + ) + .unwrap(); + let error = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::Unknown)) + .add_out(Type::typed_interface_safe_array(expected_iid)), + &[Value::SafeArray(array)], + ) + .unwrap_err(); + assert!(error.message().contains("does not support expected IID")); + assert_eq!( + mismatched.addrefs.load(Ordering::Relaxed), + mismatched.releases.load(Ordering::Relaxed) + ); } - unsafe extern "system" fn return_failure(_this: *mut c_void) -> windows_core::HRESULT { - windows_core::HRESULT(0x80004005u32 as i32) - } + #[test] + fn automation_in_out_and_typed_array_mismatches_fail_before_dispatch() { + let table = MetadataTable::new(); + assert!( + MethodSignature::new(&table) + .add_out(Type::variant_by_value()) + .build(0) + .unwrap_err() + .message() + .contains("by-value VARIANT is input-only") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::variant_by_value()) + .build(0) + .unwrap_err() + .message() + .contains("by-value VARIANT is input-only") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::variant()) + .build(0) + .unwrap_err() + .message() + .contains("BYREF/InOut") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::safe_array()) + .build(0) + .unwrap_err() + .message() + .contains("BYREF/InOut") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::prop_variant()) + .build(0) + .unwrap_err() + .message() + .contains("BYREF/InOut") + ); + assert!( + MethodSignature::new(&table) + .add_out(Type::dispatch_params()) + .build(0) + .unwrap_err() + .message() + .contains("input-only") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::dispatch_params()) + .build(0) + .unwrap_err() + .message() + .contains("input-only") + ); + assert!( + MethodSignature::new(&table) + .add_in(Type::excep_info()) + .build(0) + .unwrap_err() + .message() + .contains("output-only") + ); + assert!( + MethodSignature::new(&table) + .add_in_out(Type::excep_info()) + .build(0) + .unwrap_err() + .message() + .contains("output-only") + ); + assert!( + MethodSignature::new(&table) + .add_out(Type::excep_info()) + .returns_void() + .build(0) + .unwrap_err() + .message() + .contains("HRESULT") + ); - unsafe extern "system" fn return_hstring( - _this: *mut c_void, - value: *mut *mut c_void, - ) -> windows_core::HRESULT { - unsafe { - *value = std::mem::transmute(HSTRING::from("dynwinrt HSTRING")); - } - windows_core::HRESULT(0) - } + let array = SafeArrayValue::new( + SafeArrayElementType::U32, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::U32(1)], + ) + .unwrap(); + let error = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::I32)) + .add_out(Type::typed_safe_array(SafeArrayElementType::I32)), + &[Value::SafeArray(array)], + ) + .unwrap_err(); + assert!(error.message().contains("element type mismatch")); - static VOID_CALLS: AtomicU32 = AtomicU32::new(0); + let array = SafeArrayValue::new( + SafeArrayElementType::U32, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::U32(1)], + ) + .unwrap(); + let error = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_safe_array(SafeArrayElementType::U32)) + .add_out(Type::typed_safe_array(SafeArrayElementType::I32)), + &[Value::SafeArray(array)], + ) + .unwrap_err(); + assert!(error.message().contains("VARTYPE mismatch")); + + let actual_iid = GUID::from_u128(0x5347ad7b_c355_46f8_aff5_909033582f63); + let other_iid = GUID::from_u128(0xd6dd68d1_86fd_4332_8666_9abedea2d24c); + let array = SafeArrayValue::new_interface( + actual_iid, + vec![SafeArrayBound::new(3, 1).unwrap()], + vec![SafeArrayElementValue::Unknown(None)], + ) + .unwrap(); + let error = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_interface_safe_array(other_iid)) + .add_out(Type::typed_interface_safe_array(other_iid)), + &[Value::SafeArray(array.clone())], + ) + .unwrap_err(); + assert!(error.message().contains("interface IID mismatch")); - unsafe extern "system" fn return_void(_this: *mut c_void) { - VOID_CALLS.fetch_add(1, Ordering::Relaxed); + let error = invoke_test_pod( + copy_safe_array_value as *mut c_void, + MethodSignature::new(&table) + .add_in(Type::typed_interface_safe_array(actual_iid)) + .add_out(Type::typed_interface_safe_array(other_iid)), + &[Value::SafeArray(array)], + ) + .unwrap_err(); + assert!(error.message().contains("interface IID mismatch")); } - unsafe extern "system" fn increment_i32( - _this: *mut c_void, - value: *mut i32, - ) -> windows_core::HRESULT { - unsafe { *value += 1 }; - windows_core::HRESULT(0) - } + #[test] + fn nullable_safearray_output_accepts_only_a_documented_null_contract() { + let table = MetadataTable::new(); + let output = invoke_test_pod( + return_null_safe_array as *mut c_void, + MethodSignature::new(&table) + .add_out(Type::nullable_typed_safe_array(SafeArrayElementType::I32)), + &[], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::Null)] + )); - unsafe extern "system" fn write_native_pointer( - _this: *mut c_void, - value: *mut *mut c_void, - ) -> windows_core::HRESULT { - unsafe { *value = 0x1234usize as *mut c_void }; - windows_core::HRESULT(0) + let error = invoke_test_pod( + return_null_safe_array as *mut c_void, + MethodSignature::new(&table).add_out(Type::typed_safe_array(SafeArrayElementType::I32)), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("owned SAFEARRAY output is null")); + + assert!( + MethodSignature::new(&table) + .add_in(Type::nullable_typed_safe_array(SafeArrayElementType::I32)) + .build(0) + .unwrap_err() + .message() + .contains("exact documented owned output") + ); } - unsafe extern "system" fn write_guid_and_i32( - _this: *mut c_void, - guid: *mut GUID, - value: *mut i32, - ) -> windows_core::HRESULT { - unsafe { - *guid = GUID::from_u128(0x11111111_2222_3333_4444_555555555555); - *value = 42; - } - windows_core::HRESULT(0) + #[test] + fn native_pod_failure_discards_unowned_output_storage() { + let table = MetadataTable::new(); + let error = invoke_test_pod( + write_pod_then_fail as *mut c_void, + MethodSignature::new(&table).add_out(Type::native_struct(test_pod_layout("TestPod"))), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("0x80004005")); } #[test] @@ -742,10 +8327,81 @@ mod tests { )); } + #[test] + fn borrowed_handle_outputs_use_pointer_width_and_never_cleanup() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table).add_out(Type::borrowed_handle_output()); + let registered = signature.clone().build(0).unwrap(); + assert!(matches!( + registered.plan.arguments[0].storage, + ComArgumentStorage::OutputPointer + )); + assert_eq!( + registered.plan.native.output_cleanup(0), + OutputCleanup::None + ); + assert_eq!( + registered.plan.results[0].success.pointer_output_kind(), + PointerOutputKind::None + ); + + let success_vtable = [write_native_pointer as *mut c_void]; + let mut success = FakeComObject { + vtable: success_vtable.as_ptr(), + }; + let values = registered + .plan + .invoke_with_output_kinds((&mut success as *mut FakeComObject).cast(), &[]) + .unwrap(); + assert!(matches!( + values.as_slice(), + [(WinRTValue::RawPtr(ptr), PointerOutputKind::None)] + if *ptr as usize == 0x1234usize + )); + + let null_vtable = [succeed_without_writing_native_pointer as *mut c_void]; + let mut null = FakeComObject { + vtable: null_vtable.as_ptr(), + }; + let values = call_method( + 0, + (&mut null as *mut FakeComObject).cast(), + signature.clone(), + &[], + ) + .unwrap(); + assert!(matches!( + values.as_slice(), + [WinRTValue::RawPtr(ptr)] if ptr.is_null() + )); + + let tracked = TrackedComObject { + vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), + releases: AtomicU32::new(0), + }; + let failure_vtable = [write_object_then_fail as *mut c_void]; + let mut failure = FailingOutCall { + vtable: failure_vtable.as_ptr(), + output: (&tracked as *const TrackedComObject).cast_mut().cast(), + }; + let error = call_method( + 0, + (&mut failure as *mut FailingOutCall).cast(), + signature, + &[], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(tracked.releases.load(Ordering::Relaxed), 0); + assert_eq!(size_of::<*mut c_void>(), size_of::()); + } + #[test] fn failing_hresult_releases_written_interface_output_on_direct_path() { let tracked = TrackedComObject { vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), releases: AtomicU32::new(0), }; let vtable = [write_object_then_fail as *mut c_void]; @@ -771,6 +8427,7 @@ mod tests { fn failing_hresult_releases_written_interface_output_on_libffi_path() { let tracked = TrackedComObject { vtable: &TRACKED_VTABLE, + addrefs: AtomicU32::new(0), releases: AtomicU32::new(0), }; let vtable = [write_object_and_i32_then_fail as *mut c_void]; @@ -816,12 +8473,58 @@ mod tests { ]; for (typ, expected_cleanup, expected_output) in cases { - let registered = MethodSignature::new(&table).add_out(typ).build(0); - assert_eq!(registered.native.output_cleanup(0), expected_cleanup); - assert_eq!(registered.result_kinds, [expected_output]); + let registered = MethodSignature::new(&table).add_out(typ).build(0).unwrap(); + assert_eq!(registered.plan.native.output_cleanup(0), expected_cleanup); + assert_eq!( + registered + .plan + .results + .iter() + .map(|result| result.success.pointer_output_kind()) + .collect::>(), + [expected_output] + ); } } + #[test] + fn immutable_call_plan_preserves_argument_and_result_order() { + let table = MetadataTable::new(); + let registered = MethodSignature::new(&table) + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::owned_com_pointer()) + .add_in_out(Type::winrt(table.i32_type())) + .preserve_hresult() + .build(7) + .unwrap(); + let plan = ®istered.plan; + + assert!(matches!(plan.return_plan, ComReturnPlan::SemanticHResult)); + assert_eq!(plan.arguments.len(), 3); + assert_eq!(plan.arguments[0].input_index, Some(0)); + assert_eq!(plan.arguments[0].output_index, None); + assert_eq!(plan.arguments[1].input_index, None); + assert_eq!(plan.arguments[1].output_index, Some(0)); + assert_eq!(plan.arguments[2].input_index, Some(1)); + assert_eq!(plan.arguments[2].output_index, Some(1)); + assert_eq!( + plan.results + .iter() + .map(|result| result.source) + .collect::>(), + [ + ComResultSource::DirectReturn, + ComResultSource::Parameter(1), + ComResultSource::Parameter(2), + ] + ); + assert_eq!( + plan.results[1].success, + ComSuccessDisposition::OwnedComPointer + ); + assert_eq!(plan.results[1].failure_cleanup, OutputCleanup::ComRelease); + } + #[test] fn multi_output_guid_uses_full_sized_storage() { let table = MetadataTable::new(); @@ -939,11 +8642,13 @@ mod tests { vtable: vtable.as_ptr(), }; - let results = iface - .method(3) - .unwrap() - .invoke_with_output_kinds((&mut object as *mut FakeComObject).cast(), &[]) - .unwrap(); + let results = unsafe { + iface + .method(3) + .unwrap() + .invoke_with_output_kinds((&mut object as *mut FakeComObject).cast(), &[]) + } + .unwrap(); assert!(matches!( results.as_slice(), @@ -1031,11 +8736,13 @@ mod tests { let table = MetadataTable::new(); let iface = shell_link_interface(&table); - iface - .method(15) - .unwrap() - .invoke(shell_link.as_raw(), &[WinRTValue::I32(3)])?; - let result = iface.method(14).unwrap().invoke(shell_link.as_raw(), &[])?; + unsafe { + iface + .method(15) + .unwrap() + .invoke(shell_link.as_raw(), &[WinRTValue::I32(3)])?; + } + let result = unsafe { iface.method(14).unwrap().invoke(shell_link.as_raw(), &[]) }?; assert_eq!(result[0].as_i32().unwrap(), 3); Ok(()) @@ -1047,11 +8754,13 @@ mod tests { let table = MetadataTable::new(); let iface = shell_link_interface(&table); - iface - .method(13) - .unwrap() - .invoke(shell_link.as_raw(), &[WinRTValue::U16(0x0141)])?; - let result = iface.method(12).unwrap().invoke(shell_link.as_raw(), &[])?; + unsafe { + iface + .method(13) + .unwrap() + .invoke(shell_link.as_raw(), &[WinRTValue::U16(0x0141)])?; + } + let result = unsafe { iface.method(12).unwrap().invoke(shell_link.as_raw(), &[]) }?; assert_eq!(result[0].as_i32().unwrap() as u16, 0x0141); Ok(()) @@ -1197,24 +8906,63 @@ mod tests { let table = MetadataTable::new(); let mut buffer = vec![0u8; expected.len()]; - let read = call_method( - 3, + let read_signature = MethodSignature::new(&table) + .add_caller_output_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + false, + )? + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())) + .preserve_hresult(); + let read = read_signature + .clone() + .build(3)? + .plan + .invoke_values(stream.as_raw(), &[borrowed_buffer(&mut buffer, 1)])?; + assert!(matches!( + read.as_slice(), + [Value::WinRt(WinRTValue::HResult(hr)), Value::Buffer(result)] + if hr.0 == 0 + && result.bytes() == Some(expected.as_slice()) + && result.count() == expected.len() + )); + assert_eq!(buffer, expected); + + let position = call_method( + 5, stream.as_raw(), MethodSignature::new(&table) - .add_in(Type::pointer()) + .add_in(Type::winrt(table.i64_type())) .add_in(Type::winrt(table.u32_type())) - .add_out(Type::winrt(table.u32_type())), - &[ - WinRTValue::RawPtr(buffer.as_mut_ptr().cast()), - WinRTValue::U32(buffer.len() as u32), - ], + .add_out(Type::winrt(table.u64_type())), + &[WinRTValue::I64(0), WinRTValue::U32(0)], )?; - assert!( - matches!(read.as_slice(), [WinRTValue::U32(count)] if *count == expected.len() as u32) - ); - assert_eq!(buffer, expected); + assert!(matches!(position.as_slice(), [WinRTValue::U64(0)])); - let position = call_method( + let mut replacement = b"phase8!!".to_vec(); + let write = MethodSignature::new(&table) + .add_input_buffer( + Type::winrt(table.u8_type()), + 1, + Some(2), + BufferCountUnit::Bytes, + )? + .add_in(Type::winrt(table.u32_type())) + .add_out(Type::winrt(table.u32_type())) + .preserve_hresult() + .build(4)? + .plan + .invoke_values(stream.as_raw(), &[borrowed_buffer(&mut replacement, 1)])?; + assert!(matches!( + write.as_slice(), + [Value::WinRt(WinRTValue::HResult(hr)), Value::WinRt(WinRTValue::U32(count))] + if hr.0 == 0 && *count == replacement.len() as u32 + )); + + call_method( 5, stream.as_raw(), MethodSignature::new(&table) @@ -1223,7 +8971,16 @@ mod tests { .add_out(Type::winrt(table.u64_type())), &[WinRTValue::I64(0), WinRTValue::U32(0)], )?; - assert!(matches!(position.as_slice(), [WinRTValue::U64(0)])); + let mut reread = vec![0u8; replacement.len()]; + let read = read_signature + .build(3)? + .plan + .invoke_values(stream.as_raw(), &[borrowed_buffer(&mut reread, 1)])?; + assert!(matches!( + read.as_slice(), + [Value::WinRt(WinRTValue::HResult(hr)), Value::Buffer(result)] + if hr.0 == 0 && result.bytes() == Some(replacement.as_slice()) + )); let cloned = call_method( 13, @@ -1250,11 +9007,13 @@ mod tests { let table = MetadataTable::new(); let iface = shell_link_interface(&table); - iface - .method(15) - .unwrap() - .invoke(adopted.as_raw(), &[WinRTValue::I32(7)])?; - let result = iface.method(14).unwrap().invoke(adopted.as_raw(), &[])?; + unsafe { + iface + .method(15) + .unwrap() + .invoke(adopted.as_raw(), &[WinRTValue::I32(7)])?; + } + let result = unsafe { iface.method(14).unwrap().invoke(adopted.as_raw(), &[]) }?; assert_eq!(result[0].as_i32().unwrap(), 7); Ok(()) @@ -1356,13 +9115,15 @@ mod tests { ); let target_iid = DataTransferManager::IID; - let result = iface.method(3).unwrap().invoke( - interop.as_raw(), - &[ - WinRTValue::RawPtr(hwnd.0 as *mut c_void), - WinRTValue::RawPtr(&target_iid as *const GUID as *mut c_void), - ], - )?; + let result = unsafe { + iface.method(3).unwrap().invoke( + interop.as_raw(), + &[ + WinRTValue::RawPtr(hwnd.0 as *mut c_void), + WinRTValue::RawPtr(&target_iid as *const GUID as *mut c_void), + ], + ) + }?; let manager = result[0].as_object().expect("GetForWindow returned null"); assert!(!manager.as_raw().is_null()); diff --git a/crates/dynwinrt/src/com_automation.rs b/crates/dynwinrt/src/com_automation.rs new file mode 100644 index 00000000..18f54983 --- /dev/null +++ b/crates/dynwinrt/src/com_automation.rs @@ -0,0 +1,2828 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use core::{ffi::c_void, mem::ManuallyDrop}; +use std::{ + cell::UnsafeCell, + sync::{Arc, Mutex, MutexGuard}, +}; + +use windows::{ + Win32::{ + Foundation::{FILETIME, SysAllocStringLen, VARIANT_BOOL}, + System::{ + Com::{ + BLOB, CoTaskMemAlloc, DISPPARAMS, EXCEPINFO, IDispatch, SAFEARRAY, SAFEARRAYBOUND, + StructuredStorage::{ + CABOOL, CAC, CACLSID, CADBL, CAFILETIME, CAFLT, CAH, CAI, CAL, CALPWSTR, CAUB, + CAUH, CAUI, CAUL, PROPVARIANT, PROPVARIANT_0_0, PROPVARIANT_0_0_0, + PropVariantClear, + }, + }, + Ole::{ + SafeArrayAccessData, SafeArrayCopy, SafeArrayCreate, SafeArrayCreateEx, + SafeArrayDestroy, SafeArrayGetDim, SafeArrayGetElemsize, SafeArrayGetIID, + SafeArrayGetLBound, SafeArrayGetUBound, SafeArrayGetVartype, SafeArrayUnaccessData, + }, + Variant::{ + VARENUM, VARIANT, VARIANT_0_0, VARIANT_0_0_0, VT_ARRAY, VT_BLOB, VT_BOOL, VT_BSTR, + VT_BYREF, VT_CLSID, VT_DISPATCH, VT_EMPTY, VT_FILETIME, VT_I1, VT_I2, VT_I4, VT_I8, + VT_INT, VT_LPWSTR, VT_NULL, VT_R4, VT_R8, VT_TYPEMASK, VT_UI1, VT_UI2, VT_UI4, + VT_UI8, VT_UINT, VT_UNKNOWN, VT_VARIANT, VT_VECTOR, VariantClear, VariantCopy, + VariantInit, + }, + }, + }, + core::{BSTR, GUID, IUnknown, Interface, PWSTR}, +}; + +use crate::result; + +const E_INVALIDARG: windows_core::HRESULT = windows_core::HRESULT(0x80070057u32 as i32); +const E_OUTOFMEMORY: windows_core::HRESULT = windows_core::HRESULT(0x8007000Eu32 as i32); +const MAX_SAFEARRAY_RANK: usize = 8; + +fn invalid_argument(message: impl AsRef) -> result::Error { + result::Error::WindowsError(windows_core::Error::new(E_INVALIDARG, message.as_ref())) +} + +fn out_of_memory(message: &'static str) -> result::Error { + result::Error::WindowsError(windows_core::Error::new(E_OUTOFMEMORY, message)) +} + +fn windows_error(error: windows_core::Error) -> result::Error { + result::Error::WindowsError(error) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VariantType { + Empty, + Null, + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + Int, + UInt, + F32, + F64, + Bool, + Bstr, + Unknown, + Dispatch, + SafeArray(SafeArrayElementType), +} + +impl VariantType { + pub const fn vartype(self) -> u16 { + match self { + Self::Empty => VT_EMPTY.0, + Self::Null => VT_NULL.0, + Self::I8 => VT_I1.0, + Self::U8 => VT_UI1.0, + Self::I16 => VT_I2.0, + Self::U16 => VT_UI2.0, + Self::I32 => VT_I4.0, + Self::U32 => VT_UI4.0, + Self::I64 => VT_I8.0, + Self::U64 => VT_UI8.0, + Self::Int => VT_INT.0, + Self::UInt => VT_UINT.0, + Self::F32 => VT_R4.0, + Self::F64 => VT_R8.0, + Self::Bool => VT_BOOL.0, + Self::Bstr => VT_BSTR.0, + Self::Unknown => VT_UNKNOWN.0, + Self::Dispatch => VT_DISPATCH.0, + Self::SafeArray(element) => VT_ARRAY.0 | element.vartype(), + } + } +} + +pub enum VariantData { + Empty, + Null, + I8(i8), + U8(u8), + I16(i16), + U16(u16), + I32(i32), + U32(u32), + I64(i64), + U64(u64), + Int(i32), + UInt(u32), + F32(f32), + F64(f64), + Bool(bool), + Bstr(String), + Unknown(Option), + Dispatch(Option), + SafeArray(SafeArrayValue), +} + +impl std::fmt::Debug for VariantData { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Empty => formatter.write_str("Empty"), + Self::Null => formatter.write_str("Null"), + Self::I8(value) => formatter.debug_tuple("I8").field(value).finish(), + Self::U8(value) => formatter.debug_tuple("U8").field(value).finish(), + Self::I16(value) => formatter.debug_tuple("I16").field(value).finish(), + Self::U16(value) => formatter.debug_tuple("U16").field(value).finish(), + Self::I32(value) => formatter.debug_tuple("I32").field(value).finish(), + Self::U32(value) => formatter.debug_tuple("U32").field(value).finish(), + Self::I64(value) => formatter.debug_tuple("I64").field(value).finish(), + Self::U64(value) => formatter.debug_tuple("U64").field(value).finish(), + Self::Int(value) => formatter.debug_tuple("Int").field(value).finish(), + Self::UInt(value) => formatter.debug_tuple("UInt").field(value).finish(), + Self::F32(value) => formatter.debug_tuple("F32").field(value).finish(), + Self::F64(value) => formatter.debug_tuple("F64").field(value).finish(), + Self::Bool(value) => formatter.debug_tuple("Bool").field(value).finish(), + Self::Bstr(value) => formatter.debug_tuple("Bstr").field(value).finish(), + Self::Unknown(value) => formatter + .debug_tuple("Unknown") + .field(&value.is_some()) + .finish(), + Self::Dispatch(value) => formatter + .debug_tuple("Dispatch") + .field(&value.is_some()) + .finish(), + Self::SafeArray(value) => formatter.debug_tuple("SafeArray").field(value).finish(), + } + } +} + +struct VariantInner { + raw: UnsafeCell, +} + +impl Drop for VariantInner { + fn drop(&mut self) { + let _ = unsafe { VariantClear(self.raw.get()) }; + } +} + +#[derive(Clone)] +pub struct VariantValue { + inner: Arc, +} + +impl std::fmt::Debug for VariantValue { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("VariantValue") + .field("vartype", &self.vartype()) + .finish() + } +} + +impl VariantValue { + fn from_initialized(raw: VARIANT) -> Self { + Self { + inner: Arc::new(VariantInner { + raw: UnsafeCell::new(raw), + }), + } + } + + pub(crate) unsafe fn from_owned_raw(raw: VARIANT) -> result::Result { + validate_raw_variant(&raw)?; + Ok(Self::from_initialized(raw)) + } + + unsafe fn record(&self) -> &VARIANT_0_0 { + unsafe { + &*((&(*self.raw()).Anonymous.Anonymous as *const ManuallyDrop) + .cast::()) + } + } + + unsafe fn record_mut(&self) -> &mut VARIANT_0_0 { + unsafe { + &mut *((&mut (*self.raw_mut()).Anonymous.Anonymous as *mut ManuallyDrop) + .cast::()) + } + } + + unsafe fn payload(&self) -> &VARIANT_0_0_0 { + unsafe { &self.record().Anonymous } + } + + unsafe fn payload_mut(&self) -> &mut VARIANT_0_0_0 { + unsafe { &mut self.record_mut().Anonymous } + } + + pub fn empty() -> Self { + Self::from_initialized(unsafe { VariantInit() }) + } + + pub fn null() -> Self { + let value = Self::empty(); + unsafe { value.set_vartype(VT_NULL) }; + value + } + + pub fn from_i8(value: i8) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I1); + result.payload_mut().cVal = value; + } + result + } + + pub fn from_u8(value: u8) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI1); + result.payload_mut().bVal = value; + } + result + } + + pub fn from_i16(value: i16) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I2); + result.payload_mut().iVal = value; + } + result + } + + pub fn from_u16(value: u16) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI2); + result.payload_mut().uiVal = value; + } + result + } + + pub fn from_i32(value: i32) -> Self { + Self::from_i32_with_type(value, VT_I4) + } + + pub fn from_int(value: i32) -> Self { + Self::from_i32_with_type(value, VT_INT) + } + + fn from_i32_with_type(value: i32, vartype: VARENUM) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(vartype); + if vartype == VT_INT { + result.payload_mut().intVal = value; + } else { + result.payload_mut().lVal = value; + } + } + result + } + + pub fn from_u32(value: u32) -> Self { + Self::from_u32_with_type(value, VT_UI4) + } + + pub fn from_uint(value: u32) -> Self { + Self::from_u32_with_type(value, VT_UINT) + } + + fn from_u32_with_type(value: u32, vartype: VARENUM) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(vartype); + if vartype == VT_UINT { + result.payload_mut().uintVal = value; + } else { + result.payload_mut().ulVal = value; + } + } + result + } + + pub fn from_i64(value: i64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I8); + result.payload_mut().llVal = value; + } + result + } + + pub fn from_u64(value: u64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI8); + result.payload_mut().ullVal = value; + } + result + } + + pub fn from_f32(value: f32) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_R4); + result.payload_mut().fltVal = value; + } + result + } + + pub fn from_f64(value: f64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_R8); + result.payload_mut().dblVal = value; + } + result + } + + pub fn from_bool(value: bool) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_BOOL); + result.payload_mut().boolVal = VARIANT_BOOL(if value { -1 } else { 0 }); + } + result + } + + pub fn from_bstr(value: &str) -> result::Result { + let utf16 = value.encode_utf16().collect::>(); + let bstr = unsafe { SysAllocStringLen(Some(&utf16)) }; + if bstr.is_empty() && !utf16.is_empty() { + return Err(out_of_memory("SysAllocStringLen failed for VARIANT")); + } + let result = Self::empty(); + unsafe { + result.set_vartype(VT_BSTR); + result.payload_mut().bstrVal = ManuallyDrop::new(bstr); + } + Ok(result) + } + + pub fn from_unknown(value: Option<&IUnknown>) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UNKNOWN); + result.payload_mut().punkVal = ManuallyDrop::new(value.cloned()); + } + result + } + + pub fn from_dispatch(value: Option<&IUnknown>) -> result::Result { + let dispatch = value + .map(|value| value.cast::().map_err(windows_error)) + .transpose()?; + let result = Self::empty(); + unsafe { + result.set_vartype(VT_DISPATCH); + result.payload_mut().pdispVal = ManuallyDrop::new(dispatch); + } + Ok(result) + } + + pub fn from_safe_array(value: &SafeArrayValue) -> result::Result { + let native = value.lock_native()?; + let copy = unsafe { SafeArrayCopy(native.as_raw()) }.map_err(windows_error)?; + let result = Self::empty(); + unsafe { + result.set_vartype(VARENUM(VT_ARRAY.0 | value.element_type().vartype())); + result.payload_mut().parray = copy; + } + Ok(result) + } + + pub fn variant_type(&self) -> result::Result { + variant_type(self.vartype()) + } + + pub fn vartype(&self) -> u16 { + unsafe { self.record().vt.0 } + } + + pub fn data(&self) -> result::Result { + let typ = self.variant_type()?; + let payload = unsafe { self.payload() }; + Ok(match typ { + VariantType::Empty => VariantData::Empty, + VariantType::Null => VariantData::Null, + VariantType::I8 => VariantData::I8(unsafe { payload.cVal }), + VariantType::U8 => VariantData::U8(unsafe { payload.bVal }), + VariantType::I16 => VariantData::I16(unsafe { payload.iVal }), + VariantType::U16 => VariantData::U16(unsafe { payload.uiVal }), + VariantType::I32 => VariantData::I32(unsafe { payload.lVal }), + VariantType::U32 => VariantData::U32(unsafe { payload.ulVal }), + VariantType::I64 => VariantData::I64(unsafe { payload.llVal }), + VariantType::U64 => VariantData::U64(unsafe { payload.ullVal }), + VariantType::Int => VariantData::Int(unsafe { payload.intVal }), + VariantType::UInt => VariantData::UInt(unsafe { payload.uintVal }), + VariantType::F32 => VariantData::F32(unsafe { payload.fltVal }), + VariantType::F64 => VariantData::F64(unsafe { payload.dblVal }), + VariantType::Bool => { + let value = unsafe { payload.boolVal.0 }; + if !matches!(value, 0 | -1) { + return Err(invalid_argument(format!( + "VARIANT VT_BOOL payload must be 0 or -1, received {value}" + ))); + } + VariantData::Bool(value == -1) + } + VariantType::Bstr => { + let value = unsafe { &payload.bstrVal }; + VariantData::Bstr(value.to_string()) + } + VariantType::Unknown => { + let value = unsafe { &payload.punkVal }; + VariantData::Unknown(value.as_ref().cloned()) + } + VariantType::Dispatch => { + let value = unsafe { &payload.pdispVal }; + VariantData::Dispatch( + value + .as_ref() + .map(|value| value.cast::().map_err(windows_error)) + .transpose()?, + ) + } + VariantType::SafeArray(element) => { + let array = unsafe { payload.parray }; + let copy = unsafe { SafeArrayCopy(array) }.map_err(windows_error)?; + VariantData::SafeArray(unsafe { + SafeArrayValue::from_owned_raw(copy, Some(element), None)? + }) + } + }) + } + + pub(crate) fn validate_supported(&self) -> result::Result<()> { + self.variant_type().map(|_| ()) + } + + pub(crate) fn copy_raw(&self) -> result::Result { + self.validate_supported()?; + let mut copy = unsafe { VariantInit() }; + if let Err(error) = unsafe { VariantCopy(&mut copy, self.raw()) } { + let _ = unsafe { VariantClear(&mut copy) }; + return Err(windows_error(error)); + } + Ok(copy) + } + + pub(crate) fn raw(&self) -> *const VARIANT { + self.inner.raw.get() + } + + pub(crate) fn raw_mut(&self) -> *mut VARIANT { + self.inner.raw.get() + } + + unsafe fn set_vartype(&self, vartype: VARENUM) { + unsafe { self.record_mut().vt = vartype }; + } +} + +pub(crate) struct VariantCopyValue { + raw: VARIANT, +} + +impl VariantCopyValue { + pub(crate) fn new(value: &VariantValue) -> result::Result { + Ok(Self { + raw: value.copy_raw()?, + }) + } + + pub(crate) fn as_ref(&self) -> &VARIANT { + &self.raw + } +} + +impl Drop for VariantCopyValue { + fn drop(&mut self) { + let _ = unsafe { VariantClear(&mut self.raw) }; + } +} + +pub(crate) struct VariantArrayCopyValue { + raw: Box<[VARIANT]>, +} + +impl VariantArrayCopyValue { + pub(crate) fn new(values: &[VariantValue]) -> result::Result { + let mut raw: Vec = Vec::with_capacity(values.len()); + for value in values { + match value.copy_raw() { + Ok(value) => raw.push(value), + Err(error) => { + for value in &mut raw { + let _ = unsafe { VariantClear(value) }; + } + return Err(error); + } + } + } + Ok(Self { + raw: raw.into_boxed_slice(), + }) + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut VARIANT { + self.raw.as_mut_ptr() + } + + pub(crate) fn len(&self) -> usize { + self.raw.len() + } +} + +impl Drop for VariantArrayCopyValue { + fn drop(&mut self) { + for value in &mut self.raw { + let _ = unsafe { VariantClear(value) }; + } + } +} + +pub(crate) fn variant_size() -> usize { + std::mem::size_of::() +} + +pub(crate) fn variant_alignment() -> usize { + std::mem::align_of::() +} + +pub(crate) unsafe fn initialize_variant_slot(slot: *mut std::ffi::c_void) { + unsafe { slot.cast::().write(VariantInit()) }; +} + +pub(crate) unsafe fn clear_variant_slot(slot: *mut std::ffi::c_void) { + let _ = unsafe { VariantClear(slot.cast::()) }; +} + +pub(crate) unsafe fn validate_variant_slot(slot: *const std::ffi::c_void) -> result::Result<()> { + unsafe { validate_raw_variant(&*slot.cast::()) } +} + +pub(crate) unsafe fn take_variant_slot( + slot: *mut std::ffi::c_void, +) -> result::Result { + let raw = unsafe { slot.cast::().read() }; + unsafe { slot.cast::().write(VariantInit()) }; + unsafe { VariantValue::from_owned_raw(raw) } +} + +fn validate_raw_variant(raw: &VARIANT) -> result::Result<()> { + let record = unsafe { + &*((&raw.Anonymous.Anonymous as *const ManuallyDrop).cast::()) + }; + variant_type(record.vt.0).map(|_| ()) +} + +struct DispatchParamsInner { + raw: UnsafeCell, + arguments: Box<[VARIANT]>, + named_dispids: Box<[i32]>, +} + +impl Drop for DispatchParamsInner { + fn drop(&mut self) { + for argument in &mut self.arguments { + let _ = unsafe { VariantClear(argument) }; + } + } +} + +#[derive(Clone)] +pub struct DispatchParamsValue { + inner: Arc, +} + +impl std::fmt::Debug for DispatchParamsValue { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("DispatchParamsValue") + .field("argument_count", &self.argument_count()) + .field("named_dispids", &self.named_dispids()) + .finish() + } +} + +impl DispatchParamsValue { + pub fn new(arguments: &[VariantValue], named_dispids: &[i32]) -> result::Result { + if named_dispids.len() > arguments.len() { + return Err(invalid_argument(format!( + "DISPPARAMS named DISPID count {} exceeds argument count {}", + named_dispids.len(), + arguments.len() + ))); + } + for argument in arguments { + argument.validate_supported()?; + } + let argument_count = u32::try_from(arguments.len()) + .map_err(|_| invalid_argument("DISPPARAMS argument count exceeds UINT"))?; + let named_count = u32::try_from(named_dispids.len()) + .map_err(|_| invalid_argument("DISPPARAMS named DISPID count exceeds UINT"))?; + + let mut native_arguments = Vec::with_capacity(arguments.len()); + for argument in arguments.iter().rev() { + match argument.copy_raw() { + Ok(argument) => native_arguments.push(argument), + Err(error) => { + for argument in &mut native_arguments { + let _ = unsafe { VariantClear(argument) }; + } + return Err(error); + } + } + } + let mut native_arguments = native_arguments.into_boxed_slice(); + let mut native_named_dispids = named_dispids + .iter() + .rev() + .copied() + .collect::>() + .into_boxed_slice(); + let raw = DISPPARAMS { + rgvarg: if native_arguments.is_empty() { + std::ptr::null_mut() + } else { + native_arguments.as_mut_ptr() + }, + rgdispidNamedArgs: if native_named_dispids.is_empty() { + std::ptr::null_mut() + } else { + native_named_dispids.as_mut_ptr() + }, + cArgs: argument_count, + cNamedArgs: named_count, + }; + Ok(Self { + inner: Arc::new(DispatchParamsInner { + raw: UnsafeCell::new(raw), + arguments: native_arguments, + named_dispids: native_named_dispids, + }), + }) + } + + pub fn argument_count(&self) -> usize { + self.inner.arguments.len() + } + + pub fn named_dispids(&self) -> Vec { + self.inner.named_dispids.iter().rev().copied().collect() + } + + pub(crate) fn raw_mut(&self) -> *mut DISPPARAMS { + self.inner.raw.get() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExcepInfoValue { + code: u16, + source: Option, + description: Option, + help_file: Option, + help_context: u32, + scode: i32, +} + +impl ExcepInfoValue { + pub fn code(&self) -> u16 { + self.code + } + + pub fn source(&self) -> Option<&str> { + self.source.as_deref() + } + + pub fn description(&self) -> Option<&str> { + self.description.as_deref() + } + + pub fn help_file(&self) -> Option<&str> { + self.help_file.as_deref() + } + + pub fn help_context(&self) -> u32 { + self.help_context + } + + pub fn scode(&self) -> i32 { + self.scode + } + + pub(crate) fn is_meaningful(&self) -> bool { + self.code != 0 + || self.source.is_some() + || self.description.is_some() + || self.help_file.is_some() + || self.help_context != 0 + || self.scode != 0 + } +} + +pub(crate) struct ExcepInfoOutput { + raw: EXCEPINFO, + deferred_invoked: bool, +} + +impl ExcepInfoOutput { + pub(crate) fn new() -> Self { + Self { + raw: EXCEPINFO::default(), + deferred_invoked: false, + } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut EXCEPINFO { + &mut self.raw + } + + fn invoke_deferred(&mut self) -> result::Result<()> { + let Some(deferred) = self.raw.pfnDeferredFillIn.take() else { + return Ok(()); + }; + if self.deferred_invoked { + return Err(invalid_argument( + "EXCEPINFO deferred fill callback was installed more than once", + )); + } + self.deferred_invoked = true; + let hr = unsafe { deferred(&mut self.raw) }; + if self.raw.pfnDeferredFillIn.take().is_some() { + return Err(invalid_argument( + "EXCEPINFO deferred fill callback installed another callback", + )); + } + hr.ok().map_err(windows_error) + } + + pub(crate) fn into_value(mut self) -> result::Result { + self.invoke_deferred()?; + if self.raw.wReserved != 0 || !self.raw.pvReserved.is_null() { + return Err(invalid_argument( + "EXCEPINFO reserved fields must be zero/null", + )); + } + let source = take_excep_bstr(&mut self.raw.bstrSource)?; + let description = take_excep_bstr(&mut self.raw.bstrDescription)?; + let help_file = take_excep_bstr(&mut self.raw.bstrHelpFile)?; + Ok(ExcepInfoValue { + code: self.raw.wCode, + source, + description, + help_file, + help_context: self.raw.dwHelpContext, + scode: self.raw.scode, + }) + } +} + +impl Drop for ExcepInfoOutput { + fn drop(&mut self) { + drop_excep_bstr(&mut self.raw.bstrSource); + drop_excep_bstr(&mut self.raw.bstrDescription); + drop_excep_bstr(&mut self.raw.bstrHelpFile); + self.raw.pfnDeferredFillIn = None; + } +} + +fn take_excep_bstr(value: &mut ManuallyDrop) -> result::Result> { + let owned = unsafe { ManuallyDrop::take(value) }; + *value = ManuallyDrop::new(BSTR::new()); + let raw = owned.into_raw(); + if raw.is_null() { + return Ok(None); + } + let owned = unsafe { BSTR::from_raw(raw) }; + String::try_from(&owned) + .map(Some) + .map_err(|_| invalid_argument("EXCEPINFO contains an invalid UTF-16 BSTR")) +} + +fn drop_excep_bstr(value: &mut ManuallyDrop) { + let owned = unsafe { ManuallyDrop::take(value) }; + *value = ManuallyDrop::new(BSTR::new()); + drop(owned); +} + +fn variant_type(vartype: u16) -> result::Result { + if vartype & VT_BYREF.0 != 0 { + return Err(invalid_argument(format!( + "VARIANT BYREF combinations are not supported (VARTYPE 0x{vartype:04x})" + ))); + } + + if vartype & VT_ARRAY.0 != 0 { + if vartype & !(VT_ARRAY.0 | VT_TYPEMASK.0) != 0 { + return Err(invalid_argument(format!( + "unsupported VARIANT array flags in VARTYPE 0x{vartype:04x}" + ))); + } + + return SafeArrayElementType::from_vartype(vartype & VT_TYPEMASK.0) + .map(VariantType::SafeArray); + } + Ok(match vartype { + value if value == VT_EMPTY.0 => VariantType::Empty, + value if value == VT_NULL.0 => VariantType::Null, + value if value == VT_I1.0 => VariantType::I8, + value if value == VT_UI1.0 => VariantType::U8, + value if value == VT_I2.0 => VariantType::I16, + value if value == VT_UI2.0 => VariantType::U16, + value if value == VT_I4.0 => VariantType::I32, + value if value == VT_UI4.0 => VariantType::U32, + value if value == VT_I8.0 => VariantType::I64, + value if value == VT_UI8.0 => VariantType::U64, + value if value == VT_INT.0 => VariantType::Int, + value if value == VT_UINT.0 => VariantType::UInt, + value if value == VT_R4.0 => VariantType::F32, + value if value == VT_R8.0 => VariantType::F64, + value if value == VT_BOOL.0 => VariantType::Bool, + value if value == VT_BSTR.0 => VariantType::Bstr, + value if value == VT_UNKNOWN.0 => VariantType::Unknown, + value if value == VT_DISPATCH.0 => VariantType::Dispatch, + _ => { + return Err(invalid_argument(format!( + "unsupported VARIANT VARTYPE 0x{vartype:04x}" + ))); + } + }) +} + +#[cfg(test)] +pub(super) unsafe fn set_variant_vartype_for_test(raw: *mut VARIANT, vartype: u16) { + let record = unsafe { + &mut *((&mut (*raw).Anonymous.Anonymous as *mut ManuallyDrop) + .cast::()) + }; + record.vt = VARENUM(vartype); +} + +#[cfg(test)] +pub(super) unsafe fn variant_vartype_for_test(raw: *const VARIANT) -> u16 { + let record = unsafe { + &*((&(*raw).Anonymous.Anonymous as *const ManuallyDrop).cast::()) + }; + record.vt.0 +} + +#[cfg(test)] +pub(super) unsafe fn variant_i32_for_test(raw: *const VARIANT) -> i32 { + let record = unsafe { + &*((&(*raw).Anonymous.Anonymous as *const ManuallyDrop).cast::()) + }; + assert_eq!(record.vt, VT_I4); + unsafe { record.Anonymous.lVal } +} + +#[cfg(test)] +pub(super) unsafe fn variant_bstr_for_test(raw: *const VARIANT) -> String { + let record = unsafe { + &*((&(*raw).Anonymous.Anonymous as *const ManuallyDrop).cast::()) + }; + assert_eq!(record.vt, VT_BSTR); + unsafe { record.Anonymous.bstrVal.to_string() } +} + +#[cfg(test)] +pub(super) unsafe fn variant_unknown_is_non_null_for_test(raw: *const VARIANT) -> bool { + let record = unsafe { + &*((&(*raw).Anonymous.Anonymous as *const ManuallyDrop).cast::()) + }; + assert_eq!(record.vt, VT_UNKNOWN); + unsafe { record.Anonymous.punkVal.is_some() } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SafeArrayElementType { + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + Bool, + Bstr, + Unknown, + Dispatch, + Variant, +} + +impl SafeArrayElementType { + pub const fn vartype(self) -> u16 { + match self { + Self::I8 => VT_I1.0, + Self::U8 => VT_UI1.0, + Self::I16 => VT_I2.0, + Self::U16 => VT_UI2.0, + Self::I32 => VT_I4.0, + Self::U32 => VT_UI4.0, + Self::I64 => VT_I8.0, + Self::U64 => VT_UI8.0, + Self::F32 => VT_R4.0, + Self::F64 => VT_R8.0, + Self::Bool => VT_BOOL.0, + Self::Bstr => VT_BSTR.0, + Self::Unknown => VT_UNKNOWN.0, + Self::Dispatch => VT_DISPATCH.0, + Self::Variant => VT_VARIANT.0, + } + } + + fn element_size(self) -> usize { + match self { + Self::I8 | Self::U8 => 1, + Self::I16 | Self::U16 | Self::Bool => 2, + Self::I32 | Self::U32 | Self::F32 => 4, + Self::I64 | Self::U64 | Self::F64 => 8, + Self::Bstr | Self::Unknown | Self::Dispatch => std::mem::size_of::(), + Self::Variant => std::mem::size_of::(), + } + } + + fn element_alignment(self) -> usize { + match self { + Self::I8 | Self::U8 => std::mem::align_of::(), + Self::I16 | Self::U16 | Self::Bool => std::mem::align_of::(), + Self::I32 | Self::U32 | Self::F32 => std::mem::align_of::(), + Self::I64 | Self::U64 | Self::F64 => std::mem::align_of::(), + Self::Bstr | Self::Unknown | Self::Dispatch => std::mem::align_of::(), + Self::Variant => std::mem::align_of::(), + } + } + + fn from_vartype(vartype: u16) -> result::Result { + Ok(match vartype { + value if value == VT_I1.0 => Self::I8, + value if value == VT_UI1.0 => Self::U8, + value if value == VT_I2.0 => Self::I16, + value if value == VT_UI2.0 => Self::U16, + value if value == VT_I4.0 => Self::I32, + value if value == VT_UI4.0 => Self::U32, + value if value == VT_I8.0 => Self::I64, + value if value == VT_UI8.0 => Self::U64, + value if value == VT_R4.0 => Self::F32, + value if value == VT_R8.0 => Self::F64, + value if value == VT_BOOL.0 => Self::Bool, + value if value == VT_BSTR.0 => Self::Bstr, + value if value == VT_UNKNOWN.0 => Self::Unknown, + value if value == VT_DISPATCH.0 => Self::Dispatch, + value if value == VT_VARIANT.0 => Self::Variant, + _ => { + return Err(invalid_argument(format!( + "unsupported SAFEARRAY element VARTYPE 0x{vartype:04x}" + ))); + } + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SafeArrayBound { + lower_bound: i32, + length: u32, +} + +impl SafeArrayBound { + pub fn new(lower_bound: i32, length: u32) -> result::Result { + let exclusive_upper = i64::from(lower_bound) + i64::from(length); + if exclusive_upper > i64::from(i32::MAX) + 1 || (length == 0 && lower_bound == i32::MIN) { + return Err(invalid_argument( + "SAFEARRAY bound cannot be represented by SafeArrayGetUBound", + )); + } + Ok(Self { + lower_bound, + length, + }) + } + + pub const fn lower_bound(self) -> i32 { + self.lower_bound + } + + pub const fn length(self) -> u32 { + self.length + } +} + +#[derive(Clone)] +pub enum SafeArrayElementValue { + I8(i8), + U8(u8), + I16(i16), + U16(u16), + I32(i32), + U32(u32), + I64(i64), + U64(u64), + F32(f32), + F64(f64), + Bool(bool), + Bstr(String), + Unknown(Option), + Dispatch(Option), + Variant(VariantValue), +} + +impl std::fmt::Debug for SafeArrayElementValue { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::I8(value) => formatter.debug_tuple("I8").field(value).finish(), + Self::U8(value) => formatter.debug_tuple("U8").field(value).finish(), + Self::I16(value) => formatter.debug_tuple("I16").field(value).finish(), + Self::U16(value) => formatter.debug_tuple("U16").field(value).finish(), + Self::I32(value) => formatter.debug_tuple("I32").field(value).finish(), + Self::U32(value) => formatter.debug_tuple("U32").field(value).finish(), + Self::I64(value) => formatter.debug_tuple("I64").field(value).finish(), + Self::U64(value) => formatter.debug_tuple("U64").field(value).finish(), + Self::F32(value) => formatter.debug_tuple("F32").field(value).finish(), + Self::F64(value) => formatter.debug_tuple("F64").field(value).finish(), + Self::Bool(value) => formatter.debug_tuple("Bool").field(value).finish(), + Self::Bstr(value) => formatter.debug_tuple("Bstr").field(value).finish(), + Self::Unknown(value) => formatter + .debug_tuple("Unknown") + .field(&value.is_some()) + .finish(), + Self::Dispatch(value) => formatter + .debug_tuple("Dispatch") + .field(&value.is_some()) + .finish(), + Self::Variant(value) => formatter.debug_tuple("Variant").field(value).finish(), + } + } +} + +struct SafeArrayInner { + raw: *mut SAFEARRAY, + element_type: SafeArrayElementType, + interface_iid: Option, + bounds: Vec, + length: usize, + access_lock: Mutex<()>, +} + +pub(crate) struct SafeArrayNativeGuard<'a> { + _guard: MutexGuard<'a, ()>, + raw: *mut SAFEARRAY, +} + +impl SafeArrayNativeGuard<'_> { + pub(crate) fn as_raw(&self) -> *mut SAFEARRAY { + self.raw + } +} + +impl Drop for SafeArrayInner { + fn drop(&mut self) { + if !self.raw.is_null() { + let _ = unsafe { SafeArrayDestroy(self.raw) }; + self.raw = std::ptr::null_mut(); + } + } +} + +#[derive(Clone)] +pub struct SafeArrayValue { + inner: Arc, +} + +impl std::fmt::Debug for SafeArrayValue { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SafeArrayValue") + .field("element_type", &self.element_type()) + .field("bounds", &self.bounds()) + .field("length", &self.len()) + .finish() + } +} + +struct SafeArrayDataGuard { + array: *mut SAFEARRAY, + data: *mut c_void, +} + +impl SafeArrayDataGuard { + unsafe fn new(array: *mut SAFEARRAY) -> result::Result { + let mut data = std::ptr::null_mut(); + unsafe { SafeArrayAccessData(array, &mut data) }.map_err(windows_error)?; + Ok(Self { array, data }) + } + + fn finish(mut self) -> result::Result<()> { + let array = std::mem::replace(&mut self.array, std::ptr::null_mut()); + unsafe { SafeArrayUnaccessData(array) }.map_err(windows_error) + } +} + +impl Drop for SafeArrayDataGuard { + fn drop(&mut self) { + if !self.array.is_null() { + let _ = unsafe { SafeArrayUnaccessData(self.array) }; + self.array = std::ptr::null_mut(); + } + } +} + +pub(crate) struct SafeArrayOutput { + raw: *mut SAFEARRAY, +} + +impl SafeArrayOutput { + pub(crate) fn new() -> Self { + Self { + raw: std::ptr::null_mut(), + } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut *mut SAFEARRAY { + &mut self.raw + } + + pub(crate) fn is_null(&self) -> bool { + self.raw.is_null() + } + + pub(crate) fn into_value( + mut self, + expected: Option, + expected_interface_iid: Option, + ) -> result::Result { + let raw = std::mem::replace(&mut self.raw, std::ptr::null_mut()); + unsafe { SafeArrayValue::from_owned_raw(raw, expected, expected_interface_iid) } + } +} + +impl Drop for SafeArrayOutput { + fn drop(&mut self) { + if !self.raw.is_null() { + let _ = unsafe { SafeArrayDestroy(self.raw) }; + self.raw = std::ptr::null_mut(); + } + } +} + +impl SafeArrayValue { + pub fn new( + element_type: SafeArrayElementType, + bounds: Vec, + elements: Vec, + ) -> result::Result { + Self::new_with_identity(element_type, None, bounds, elements) + } + + pub fn new_interface( + iid: GUID, + bounds: Vec, + elements: Vec, + ) -> result::Result { + if iid == GUID::zeroed() { + return Err(invalid_argument("SAFEARRAY interface IID must not be zero")); + } + let elements = elements + .into_iter() + .map(|element| match element { + SafeArrayElementValue::Unknown(Some(value)) => { + let mut queried = std::ptr::null_mut(); + unsafe { value.query(&iid, &mut queried) } + .ok() + .map_err(windows_error)?; + Ok(SafeArrayElementValue::Unknown(Some(unsafe { + IUnknown::from_raw(queried) + }))) + } + SafeArrayElementValue::Unknown(None) => Ok(SafeArrayElementValue::Unknown(None)), + _ => Err(invalid_argument( + "typed interface SAFEARRAY values require VT_UNKNOWN elements", + )), + }) + .collect::>>()?; + Self::new_with_identity(SafeArrayElementType::Unknown, Some(iid), bounds, elements) + } + + fn new_with_identity( + element_type: SafeArrayElementType, + interface_iid: Option, + bounds: Vec, + elements: Vec, + ) -> result::Result { + if interface_iid.is_some() && element_type != SafeArrayElementType::Unknown { + return Err(invalid_argument( + "exact interface IID is valid only for VT_UNKNOWN SAFEARRAY elements", + )); + } + validate_safearray_bounds(&bounds)?; + let length = bounds.iter().try_fold(1usize, |total, bound| { + total + .checked_mul(bound.length as usize) + .ok_or_else(|| invalid_argument("SAFEARRAY element count overflows")) + })?; + validate_contiguous_size(length, element_type.element_size(), "SAFEARRAY")?; + if elements.len() != length { + return Err(invalid_argument(format!( + "SAFEARRAY bounds require {length} element(s), received {}", + elements.len() + ))); + } + for element in &elements { + if safe_array_element_type(element) != element_type { + return Err(invalid_argument(format!( + "SAFEARRAY element type mismatch: expected {element_type:?}, received {:?}", + safe_array_element_type(element) + ))); + } + } + let native_bounds = bounds + .iter() + .map(|bound| SAFEARRAYBOUND { + cElements: bound.length, + lLbound: bound.lower_bound, + }) + .collect::>(); + let raw = unsafe { + if let Some(iid) = interface_iid.as_ref() { + SafeArrayCreateEx( + VARENUM(element_type.vartype()), + native_bounds.len() as u32, + native_bounds.as_ptr(), + (iid as *const GUID).cast(), + ) + } else { + SafeArrayCreate( + VARENUM(element_type.vartype()), + native_bounds.len() as u32, + native_bounds.as_ptr(), + ) + } + }; + if raw.is_null() { + return Err(out_of_memory("SafeArrayCreate failed")); + } + let output = SafeArrayOutput { raw }; + { + let guard = unsafe { SafeArrayDataGuard::new(raw)? }; + let write_result = write_safe_array_elements(guard.data, element_type, &elements); + let unlock_result = guard.finish(); + write_result?; + unlock_result?; + } + output.into_value(Some(element_type), interface_iid) + } + + pub(crate) unsafe fn from_owned_raw( + raw: *mut SAFEARRAY, + expected: Option, + expected_interface_iid: Option, + ) -> result::Result { + if raw.is_null() { + return Err(invalid_argument("owned SAFEARRAY output is null")); + } + let mut owner = SafeArrayOutput { raw }; + let vartype = unsafe { SafeArrayGetVartype(raw) } + .map_err(windows_error)? + .0; + let element_type = SafeArrayElementType::from_vartype(vartype)?; + if expected.is_some_and(|expected| expected != element_type) { + return Err(invalid_argument(format!( + "SAFEARRAY VARTYPE mismatch: expected {:?}, received {element_type:?}", + expected.unwrap() + ))); + } + if expected_interface_iid.is_some() && element_type != SafeArrayElementType::Unknown { + return Err(invalid_argument( + "exact SAFEARRAY interface IID requires VT_UNKNOWN elements", + )); + } + let descriptor_interface_iid = if element_type == SafeArrayElementType::Unknown { + match unsafe { SafeArrayGetIID(raw) } { + Ok(iid) if iid != GUID::zeroed() => Some(iid), + Ok(_) if expected_interface_iid.is_none() => None, + Err(error) if error.code() == E_INVALIDARG => None, + Err(error) => return Err(windows_error(error)), + Ok(_) => { + return Err(invalid_argument( + "SAFEARRAY descriptor has no exact interface IID", + )); + } + } + } else { + None + }; + if let Some(expected_iid) = expected_interface_iid { + match descriptor_interface_iid { + Some(actual_iid) if actual_iid == expected_iid || actual_iid == IUnknown::IID => {} + None => {} + Some(actual_iid) => { + return Err(invalid_argument(format!( + "SAFEARRAY interface IID mismatch: expected {expected_iid:?}, received {actual_iid:?}" + ))); + } + } + } + let rank = unsafe { SafeArrayGetDim(raw) } as usize; + if rank == 0 || rank > MAX_SAFEARRAY_RANK { + return Err(invalid_argument(format!( + "SAFEARRAY rank {rank} is unsupported; supported ranks are 1 through {MAX_SAFEARRAY_RANK}" + ))); + } + let element_size = unsafe { SafeArrayGetElemsize(raw) } as usize; + if element_size != element_type.element_size() { + return Err(invalid_argument(format!( + "SAFEARRAY element width mismatch: VARTYPE {element_type:?} requires {} bytes, descriptor reports {element_size}", + element_type.element_size() + ))); + } + let mut bounds = Vec::with_capacity(rank); + for dimension in 1..=rank { + let lower = + unsafe { SafeArrayGetLBound(raw, dimension as u32) }.map_err(windows_error)?; + let upper = + unsafe { SafeArrayGetUBound(raw, dimension as u32) }.map_err(windows_error)?; + let length = if upper < lower { + 0 + } else { + u32::try_from(i64::from(upper) - i64::from(lower) + 1) + .map_err(|_| invalid_argument("SAFEARRAY bound length exceeds u32"))? + }; + bounds.push(SafeArrayBound::new(lower, length)?); + } + let length = bounds.iter().try_fold(1usize, |total, bound| { + total + .checked_mul(bound.length as usize) + .ok_or_else(|| invalid_argument("SAFEARRAY element count overflows")) + })?; + validate_contiguous_size(length, element_size, "SAFEARRAY")?; + { + let guard = unsafe { SafeArrayDataGuard::new(raw)? }; + let validation_result = validate_data_pointer( + length, + guard.data, + element_type.element_alignment(), + "SAFEARRAY", + ) + .and_then(|_| { + if let Some(expected_iid) = expected_interface_iid { + validate_safe_array_interface_elements(guard.data, length, expected_iid)?; + } + Ok(()) + }); + let unlock_result = guard.finish(); + validation_result?; + unlock_result?; + } + owner.raw = std::ptr::null_mut(); + Ok(Self { + inner: Arc::new(SafeArrayInner { + raw, + element_type, + interface_iid: expected_interface_iid.or(descriptor_interface_iid), + bounds, + length, + access_lock: Mutex::new(()), + }), + }) + } + + pub fn element_type(&self) -> SafeArrayElementType { + self.inner.element_type + } + + pub fn interface_iid(&self) -> Option { + self.inner.interface_iid + } + + pub fn bounds(&self) -> &[SafeArrayBound] { + &self.inner.bounds + } + + pub fn len(&self) -> usize { + self.inner.length + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn elements(&self) -> result::Result> { + let _access = self + .inner + .access_lock + .lock() + .map_err(|_| invalid_argument("SAFEARRAY access lock is poisoned"))?; + let guard = unsafe { SafeArrayDataGuard::new(self.inner.raw)? }; + let read_result = + read_safe_array_elements(guard.data, self.inner.element_type, self.inner.length); + let unlock_result = guard.finish(); + let values = read_result?; + unlock_result?; + Ok(values) + } + + pub(crate) fn lock_native(&self) -> result::Result> { + let guard = self + .inner + .access_lock + .lock() + .map_err(|_| invalid_argument("SAFEARRAY access lock is poisoned"))?; + Ok(SafeArrayNativeGuard { + _guard: guard, + raw: self.inner.raw, + }) + } + + pub(crate) fn identity(&self) -> usize { + self.inner.raw as usize + } +} + +fn validate_safe_array_interface_elements( + data: *mut c_void, + length: usize, + expected_iid: GUID, +) -> result::Result<()> { + if length == 0 { + return Ok(()); + } + let elements = data.cast::<*mut c_void>(); + for index in 0..length { + let raw = unsafe { *elements.add(index) }; + let Some(value) = (unsafe { IUnknown::from_raw_borrowed(&raw) }) else { + continue; + }; + let mut queried = std::ptr::null_mut(); + let query_result = unsafe { value.query(&expected_iid, &mut queried) }.ok(); + if let Err(error) = query_result { + if !queried.is_null() { + drop(unsafe { IUnknown::from_raw(queried) }); + } + return Err(invalid_argument(format!( + "SAFEARRAY interface element {index} does not support expected IID {expected_iid:?}: {error}" + ))); + } + if queried.is_null() { + return Err(invalid_argument(format!( + "SAFEARRAY interface element {index} returned null for expected IID {expected_iid:?}" + ))); + } + drop(unsafe { IUnknown::from_raw(queried) }); + } + Ok(()) +} + +fn validate_safearray_bounds(bounds: &[SafeArrayBound]) -> result::Result<()> { + if bounds.is_empty() || bounds.len() > MAX_SAFEARRAY_RANK { + return Err(invalid_argument(format!( + "SAFEARRAY ranks must be between 1 and {MAX_SAFEARRAY_RANK}" + ))); + } + Ok(()) +} + +fn safe_array_element_type(value: &SafeArrayElementValue) -> SafeArrayElementType { + match value { + SafeArrayElementValue::I8(_) => SafeArrayElementType::I8, + SafeArrayElementValue::U8(_) => SafeArrayElementType::U8, + SafeArrayElementValue::I16(_) => SafeArrayElementType::I16, + SafeArrayElementValue::U16(_) => SafeArrayElementType::U16, + SafeArrayElementValue::I32(_) => SafeArrayElementType::I32, + SafeArrayElementValue::U32(_) => SafeArrayElementType::U32, + SafeArrayElementValue::I64(_) => SafeArrayElementType::I64, + SafeArrayElementValue::U64(_) => SafeArrayElementType::U64, + SafeArrayElementValue::F32(_) => SafeArrayElementType::F32, + SafeArrayElementValue::F64(_) => SafeArrayElementType::F64, + SafeArrayElementValue::Bool(_) => SafeArrayElementType::Bool, + SafeArrayElementValue::Bstr(_) => SafeArrayElementType::Bstr, + SafeArrayElementValue::Unknown(_) => SafeArrayElementType::Unknown, + SafeArrayElementValue::Dispatch(_) => SafeArrayElementType::Dispatch, + SafeArrayElementValue::Variant(_) => SafeArrayElementType::Variant, + } +} + +fn write_safe_array_elements( + data: *mut c_void, + element_type: SafeArrayElementType, + values: &[SafeArrayElementValue], +) -> result::Result<()> { + if values.is_empty() { + return Ok(()); + } + if data.is_null() { + return Err(invalid_argument( + "SafeArrayAccessData returned null storage for a non-empty array", + )); + } + validate_data_pointer( + values.len(), + data, + element_type.element_alignment(), + "SAFEARRAY", + )?; + unsafe { + macro_rules! write_plain { + ($variant:ident, $native:ty) => {{ + let output = data.cast::<$native>(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::$variant(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + output.add(index).write(*value); + } + }}; + } + match element_type { + SafeArrayElementType::I8 => write_plain!(I8, i8), + SafeArrayElementType::U8 => write_plain!(U8, u8), + SafeArrayElementType::I16 => write_plain!(I16, i16), + SafeArrayElementType::U16 => write_plain!(U16, u16), + SafeArrayElementType::I32 => write_plain!(I32, i32), + SafeArrayElementType::U32 => write_plain!(U32, u32), + SafeArrayElementType::I64 => write_plain!(I64, i64), + SafeArrayElementType::U64 => write_plain!(U64, u64), + SafeArrayElementType::F32 => write_plain!(F32, f32), + SafeArrayElementType::F64 => write_plain!(F64, f64), + SafeArrayElementType::Bool => { + let output = data.cast::(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::Bool(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + output + .add(index) + .write(VARIANT_BOOL(if *value { -1 } else { 0 })); + } + } + SafeArrayElementType::Bstr => { + let output = data.cast::(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::Bstr(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + let utf16 = value.encode_utf16().collect::>(); + let bstr = SysAllocStringLen(Some(&utf16)); + if bstr.is_empty() && !utf16.is_empty() { + return Err(out_of_memory( + "SysAllocStringLen failed for SAFEARRAY element", + )); + } + output.add(index).write(bstr); + } + } + SafeArrayElementType::Unknown => { + let output = data.cast::<*mut c_void>(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::Unknown(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + output.add(index).write( + value + .as_ref() + .map_or(std::ptr::null_mut(), |value| value.clone().into_raw()), + ); + } + } + SafeArrayElementType::Dispatch => { + let output = data.cast::<*mut c_void>(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::Dispatch(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + let dispatch = value + .as_ref() + .map(|value| value.cast::().map_err(windows_error)) + .transpose()?; + output + .add(index) + .write(dispatch.map_or(std::ptr::null_mut(), |value| value.into_raw())); + } + } + SafeArrayElementType::Variant => { + let output = data.cast::(); + for (index, value) in values.iter().enumerate() { + let SafeArrayElementValue::Variant(value) = value else { + unreachable!("validated SAFEARRAY element kind") + }; + output.add(index).write(VariantInit()); + VariantCopy(output.add(index), value.raw()).map_err(windows_error)?; + } + } + } + } + Ok(()) +} + +fn read_safe_array_elements( + data: *mut c_void, + element_type: SafeArrayElementType, + length: usize, +) -> result::Result> { + if length == 0 { + return Ok(Vec::new()); + } + if data.is_null() { + return Err(invalid_argument( + "SafeArrayAccessData returned null storage for a non-empty array", + )); + } + validate_contiguous_size(length, element_type.element_size(), "SAFEARRAY")?; + validate_data_pointer(length, data, element_type.element_alignment(), "SAFEARRAY")?; + let mut values = Vec::with_capacity(length); + unsafe { + for index in 0..length { + values.push(match element_type { + SafeArrayElementType::I8 => { + SafeArrayElementValue::I8(*data.cast::().add(index)) + } + SafeArrayElementType::U8 => { + SafeArrayElementValue::U8(*data.cast::().add(index)) + } + SafeArrayElementType::I16 => { + SafeArrayElementValue::I16(*data.cast::().add(index)) + } + SafeArrayElementType::U16 => { + SafeArrayElementValue::U16(*data.cast::().add(index)) + } + SafeArrayElementType::I32 => { + SafeArrayElementValue::I32(*data.cast::().add(index)) + } + SafeArrayElementType::U32 => { + SafeArrayElementValue::U32(*data.cast::().add(index)) + } + SafeArrayElementType::I64 => { + SafeArrayElementValue::I64(*data.cast::().add(index)) + } + SafeArrayElementType::U64 => { + SafeArrayElementValue::U64(*data.cast::().add(index)) + } + SafeArrayElementType::F32 => { + SafeArrayElementValue::F32(*data.cast::().add(index)) + } + SafeArrayElementType::F64 => { + SafeArrayElementValue::F64(*data.cast::().add(index)) + } + SafeArrayElementType::Bool => { + let value = (*data.cast::().add(index)).0; + if !matches!(value, 0 | -1) { + return Err(invalid_argument(format!( + "SAFEARRAY VT_BOOL element must be 0 or -1, received {value}" + ))); + } + SafeArrayElementValue::Bool(value == -1) + } + SafeArrayElementType::Bstr => { + let value = &*data.cast::().add(index); + SafeArrayElementValue::Bstr(value.to_string()) + } + SafeArrayElementType::Unknown => { + let raw = *data.cast::<*mut c_void>().add(index); + let value = IUnknown::from_raw_borrowed(&raw).cloned(); + SafeArrayElementValue::Unknown(value) + } + SafeArrayElementType::Dispatch => { + let raw = *data.cast::<*mut c_void>().add(index); + let value = IDispatch::from_raw_borrowed(&raw) + .map(|value| value.cast::().map_err(windows_error)) + .transpose()?; + SafeArrayElementValue::Dispatch(value) + } + SafeArrayElementType::Variant => { + let mut copy = VariantInit(); + VariantCopy(&mut copy, data.cast::().add(index)) + .map_err(windows_error)?; + let value = VariantValue::from_initialized(copy); + value.validate_supported()?; + SafeArrayElementValue::Variant(value) + } + }); + } + } + Ok(values) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PropVariantType { + Empty, + Null, + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + Int, + UInt, + F32, + F64, + Bool, + String, + Guid, + FileTime, + Blob, + Vector(PropVariantVectorType), +} + +impl PropVariantType { + pub const fn vartype(self) -> u16 { + match self { + Self::Empty => VT_EMPTY.0, + Self::Null => VT_NULL.0, + Self::I8 => VT_I1.0, + Self::U8 => VT_UI1.0, + Self::I16 => VT_I2.0, + Self::U16 => VT_UI2.0, + Self::I32 => VT_I4.0, + Self::U32 => VT_UI4.0, + Self::I64 => VT_I8.0, + Self::U64 => VT_UI8.0, + Self::Int => VT_INT.0, + Self::UInt => VT_UINT.0, + Self::F32 => VT_R4.0, + Self::F64 => VT_R8.0, + Self::Bool => VT_BOOL.0, + Self::String => VT_LPWSTR.0, + Self::Guid => VT_CLSID.0, + Self::FileTime => VT_FILETIME.0, + Self::Blob => VT_BLOB.0, + Self::Vector(element) => VT_VECTOR.0 | element.vartype(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PropVariantVectorType { + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + Bool, + String, + Guid, + FileTime, +} + +impl PropVariantVectorType { + pub const fn vartype(self) -> u16 { + match self { + Self::I8 => VT_I1.0, + Self::U8 => VT_UI1.0, + Self::I16 => VT_I2.0, + Self::U16 => VT_UI2.0, + Self::I32 => VT_I4.0, + Self::U32 => VT_UI4.0, + Self::I64 => VT_I8.0, + Self::U64 => VT_UI8.0, + Self::F32 => VT_R4.0, + Self::F64 => VT_R8.0, + Self::Bool => VT_BOOL.0, + Self::String => VT_LPWSTR.0, + Self::Guid => VT_CLSID.0, + Self::FileTime => VT_FILETIME.0, + } + } +} + +#[derive(Debug, Clone)] +pub enum PropVariantData { + Empty, + Null, + I8(i8), + U8(u8), + I16(i16), + U16(u16), + I32(i32), + U32(u32), + I64(i64), + U64(u64), + Int(i32), + UInt(u32), + F32(f32), + F64(f64), + Bool(bool), + String(String), + Guid(GUID), + FileTime(u64), + Blob(Vec), + Vector(PropVariantVector), +} + +#[derive(Debug, Clone)] +pub enum PropVariantVector { + I8(Vec), + U8(Vec), + I16(Vec), + U16(Vec), + I32(Vec), + U32(Vec), + I64(Vec), + U64(Vec), + F32(Vec), + F64(Vec), + Bool(Vec), + String(Vec), + Guid(Vec), + FileTime(Vec), +} + +struct PropVariantInner { + raw: UnsafeCell, +} + +// The PROPVARIANT is immutable after publication. Native mutation is limited +// to fresh output storage before the Arc is returned to callers. +unsafe impl Send for PropVariantInner {} +unsafe impl Sync for PropVariantInner {} + +impl Drop for PropVariantInner { + fn drop(&mut self) { + let _ = unsafe { PropVariantClear(self.raw.get()) }; + } +} + +#[derive(Clone)] +pub struct PropVariantValue { + inner: Arc, +} + +impl std::fmt::Debug for PropVariantValue { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("PropVariantValue") + .field("vartype", &self.vartype()) + .finish() + } +} + +impl PropVariantValue { + fn init() -> PROPVARIANT { + // PropVariantInit is an inline Windows SDK helper that zero-initializes + // the complete PROPVARIANT, including VT_EMPTY. + unsafe { std::mem::zeroed() } + } + + fn from_initialized(raw: PROPVARIANT) -> Self { + Self { + inner: Arc::new(PropVariantInner { + raw: UnsafeCell::new(raw), + }), + } + } + + unsafe fn record(&self) -> &PROPVARIANT_0_0 { + unsafe { + &*((&(*self.raw()).Anonymous.Anonymous as *const ManuallyDrop) + .cast::()) + } + } + + unsafe fn record_mut(&self) -> &mut PROPVARIANT_0_0 { + unsafe { + &mut *((&mut (*self.raw_mut()).Anonymous.Anonymous + as *mut ManuallyDrop) + .cast::()) + } + } + + unsafe fn payload(&self) -> &PROPVARIANT_0_0_0 { + unsafe { &self.record().Anonymous } + } + + unsafe fn payload_mut(&self) -> &mut PROPVARIANT_0_0_0 { + unsafe { &mut self.record_mut().Anonymous } + } + + pub fn empty() -> Self { + Self::from_initialized(Self::init()) + } + + pub fn null() -> Self { + let result = Self::empty(); + unsafe { result.set_vartype(VT_NULL) }; + result + } + + pub fn from_i8(value: i8) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I1); + result.payload_mut().cVal = value; + } + result + } + + pub fn from_u8(value: u8) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI1); + result.payload_mut().bVal = value; + } + result + } + + pub fn from_i16(value: i16) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I2); + result.payload_mut().iVal = value; + } + result + } + + pub fn from_u16(value: u16) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI2); + result.payload_mut().uiVal = value; + } + result + } + + pub fn from_i32(value: i32) -> Self { + Self::from_i32_with_type(value, VT_I4) + } + + pub fn from_int(value: i32) -> Self { + Self::from_i32_with_type(value, VT_INT) + } + + fn from_i32_with_type(value: i32, vartype: VARENUM) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(vartype); + if vartype == VT_INT { + result.payload_mut().intVal = value; + } else { + result.payload_mut().lVal = value; + } + } + result + } + + pub fn from_u32(value: u32) -> Self { + Self::from_u32_with_type(value, VT_UI4) + } + + pub fn from_uint(value: u32) -> Self { + Self::from_u32_with_type(value, VT_UINT) + } + + fn from_u32_with_type(value: u32, vartype: VARENUM) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(vartype); + if vartype == VT_UINT { + result.payload_mut().uintVal = value; + } else { + result.payload_mut().ulVal = value; + } + } + result + } + + pub fn from_i64(value: i64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_I8); + result.payload_mut().hVal = value; + } + result + } + + pub fn from_u64(value: u64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_UI8); + result.payload_mut().uhVal = value; + } + result + } + + pub fn from_f32(value: f32) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_R4); + result.payload_mut().fltVal = value; + } + result + } + + pub fn from_f64(value: f64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_R8); + result.payload_mut().dblVal = value; + } + result + } + + pub fn from_bool(value: bool) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_BOOL); + result.payload_mut().boolVal = VARIANT_BOOL(if value { -1 } else { 0 }); + } + result + } + + pub fn from_string(value: &str) -> result::Result { + let string = allocate_cotaskmem_wide(value)?; + let result = Self::empty(); + unsafe { + result.set_vartype(VT_LPWSTR); + result.payload_mut().pwszVal = string; + } + Ok(result) + } + + pub fn from_guid(value: GUID) -> result::Result { + let ptr = unsafe { CoTaskMemAlloc(std::mem::size_of::()) }.cast::(); + if ptr.is_null() { + return Err(out_of_memory("CoTaskMemAlloc failed for PROPVARIANT GUID")); + } + unsafe { ptr.write(value) }; + let result = Self::empty(); + unsafe { + result.set_vartype(VT_CLSID); + result.payload_mut().puuid = ptr; + } + Ok(result) + } + + pub fn from_filetime(value: u64) -> Self { + let result = Self::empty(); + unsafe { + result.set_vartype(VT_FILETIME); + result.payload_mut().filetime = u64_to_filetime(value); + } + result + } + + pub fn from_blob(value: &[u8]) -> result::Result { + let length = u32::try_from(value.len()) + .map_err(|_| invalid_argument("PROPVARIANT blob length exceeds u32"))?; + let ptr = allocate_cotaskmem_bytes(value)?; + let result = Self::empty(); + unsafe { + result.set_vartype(VT_BLOB); + result.payload_mut().blob = BLOB { + cbSize: length, + pBlobData: ptr, + }; + } + Ok(result) + } + + pub fn from_vector(value: PropVariantVector) -> result::Result { + let result = Self::empty(); + write_propvariant_vector(&result, value)?; + Ok(result) + } + + pub fn vartype(&self) -> u16 { + unsafe { self.record().vt.0 } + } + + pub fn propvariant_type(&self) -> result::Result { + propvariant_type(self.vartype()) + } + + pub fn data(&self) -> result::Result { + let typ = self.propvariant_type()?; + let payload = unsafe { self.payload() }; + Ok(match typ { + PropVariantType::Empty => PropVariantData::Empty, + PropVariantType::Null => PropVariantData::Null, + PropVariantType::I8 => PropVariantData::I8(unsafe { payload.cVal }), + PropVariantType::U8 => PropVariantData::U8(unsafe { payload.bVal }), + PropVariantType::I16 => PropVariantData::I16(unsafe { payload.iVal }), + PropVariantType::U16 => PropVariantData::U16(unsafe { payload.uiVal }), + PropVariantType::I32 => PropVariantData::I32(unsafe { payload.lVal }), + PropVariantType::U32 => PropVariantData::U32(unsafe { payload.ulVal }), + PropVariantType::I64 => PropVariantData::I64(unsafe { payload.hVal }), + PropVariantType::U64 => PropVariantData::U64(unsafe { payload.uhVal }), + PropVariantType::Int => PropVariantData::Int(unsafe { payload.intVal }), + PropVariantType::UInt => PropVariantData::UInt(unsafe { payload.uintVal }), + PropVariantType::F32 => PropVariantData::F32(unsafe { payload.fltVal }), + PropVariantType::F64 => PropVariantData::F64(unsafe { payload.dblVal }), + PropVariantType::Bool => { + let value = unsafe { payload.boolVal.0 }; + if !matches!(value, 0 | -1) { + return Err(invalid_argument(format!( + "PROPVARIANT VT_BOOL payload must be 0 or -1, received {value}" + ))); + } + PropVariantData::Bool(value == -1) + } + PropVariantType::String => { + PropVariantData::String(read_wide_string(unsafe { payload.pwszVal })?) + } + PropVariantType::Guid => { + let ptr = unsafe { payload.puuid }; + if ptr.is_null() { + return Err(invalid_argument("PROPVARIANT VT_CLSID pointer is null")); + } + PropVariantData::Guid(unsafe { *ptr }) + } + PropVariantType::FileTime => { + PropVariantData::FileTime(filetime_to_u64(unsafe { payload.filetime })) + } + PropVariantType::Blob => { + let blob = unsafe { payload.blob }; + if blob.cbSize > 0 && blob.pBlobData.is_null() { + return Err(invalid_argument( + "PROPVARIANT VT_BLOB has a null pointer with non-zero length", + )); + } + PropVariantData::Blob(if blob.cbSize == 0 { + Vec::new() + } else { + validate_contiguous_size(blob.cbSize as usize, 1, "PROPVARIANT blob")?; + unsafe { + std::slice::from_raw_parts(blob.pBlobData, blob.cbSize as usize).to_vec() + } + }) + } + PropVariantType::Vector(element) => { + PropVariantData::Vector(read_propvariant_vector(payload, element)?) + } + }) + } + + pub(crate) fn validate_supported(&self) -> result::Result<()> { + self.propvariant_type().map(|_| ()) + } + + pub(crate) fn raw(&self) -> *const PROPVARIANT { + self.inner.raw.get() + } + + pub(crate) fn raw_mut(&self) -> *mut PROPVARIANT { + self.inner.raw.get() + } + + unsafe fn set_vartype(&self, vartype: VARENUM) { + unsafe { self.record_mut().vt = vartype }; + } +} + +fn propvariant_type(vartype: u16) -> result::Result { + if vartype & VT_BYREF.0 != 0 { + return Err(invalid_argument(format!( + "PROPVARIANT BYREF combinations are not supported (VARTYPE 0x{vartype:04x})" + ))); + } + if vartype & VT_VECTOR.0 != 0 { + if vartype & !(VT_VECTOR.0 | VT_TYPEMASK.0) != 0 { + return Err(invalid_argument(format!( + "unsupported PROPVARIANT vector flags in VARTYPE 0x{vartype:04x}" + ))); + } + return propvariant_vector_type(vartype & VT_TYPEMASK.0).map(PropVariantType::Vector); + } + Ok(match vartype { + value if value == VT_EMPTY.0 => PropVariantType::Empty, + value if value == VT_NULL.0 => PropVariantType::Null, + value if value == VT_I1.0 => PropVariantType::I8, + value if value == VT_UI1.0 => PropVariantType::U8, + value if value == VT_I2.0 => PropVariantType::I16, + value if value == VT_UI2.0 => PropVariantType::U16, + value if value == VT_I4.0 => PropVariantType::I32, + value if value == VT_UI4.0 => PropVariantType::U32, + value if value == VT_I8.0 => PropVariantType::I64, + value if value == VT_UI8.0 => PropVariantType::U64, + value if value == VT_INT.0 => PropVariantType::Int, + value if value == VT_UINT.0 => PropVariantType::UInt, + value if value == VT_R4.0 => PropVariantType::F32, + value if value == VT_R8.0 => PropVariantType::F64, + value if value == VT_BOOL.0 => PropVariantType::Bool, + value if value == VT_LPWSTR.0 => PropVariantType::String, + value if value == VT_CLSID.0 => PropVariantType::Guid, + value if value == VT_FILETIME.0 => PropVariantType::FileTime, + value if value == VT_BLOB.0 => PropVariantType::Blob, + _ => { + return Err(invalid_argument(format!( + "unsupported PROPVARIANT VARTYPE 0x{vartype:04x}" + ))); + } + }) +} + +fn propvariant_vector_type(vartype: u16) -> result::Result { + Ok(match vartype { + value if value == VT_I1.0 => PropVariantVectorType::I8, + value if value == VT_UI1.0 => PropVariantVectorType::U8, + value if value == VT_I2.0 => PropVariantVectorType::I16, + value if value == VT_UI2.0 => PropVariantVectorType::U16, + value if value == VT_I4.0 => PropVariantVectorType::I32, + value if value == VT_UI4.0 => PropVariantVectorType::U32, + value if value == VT_I8.0 => PropVariantVectorType::I64, + value if value == VT_UI8.0 => PropVariantVectorType::U64, + value if value == VT_R4.0 => PropVariantVectorType::F32, + value if value == VT_R8.0 => PropVariantVectorType::F64, + value if value == VT_BOOL.0 => PropVariantVectorType::Bool, + value if value == VT_LPWSTR.0 => PropVariantVectorType::String, + value if value == VT_CLSID.0 => PropVariantVectorType::Guid, + value if value == VT_FILETIME.0 => PropVariantVectorType::FileTime, + value if value == VT_VARIANT.0 => { + return Err(invalid_argument( + "nested VT_VECTOR | VT_VARIANT PROPVARIANT values are not supported", + )); + } + _ => { + return Err(invalid_argument(format!( + "unsupported PROPVARIANT vector element VARTYPE 0x{vartype:04x}" + ))); + } + }) +} + +fn write_propvariant_vector( + output: &PropVariantValue, + vector: PropVariantVector, +) -> result::Result<()> { + unsafe { + macro_rules! write_plain_vector { + ($values:expr, $vt:expr, $ca:ident, $native:ty, $container:ident) => {{ + let values = $values; + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::<$native>(values.len())?; + if !ptr.is_null() { + std::ptr::copy_nonoverlapping(values.as_ptr(), ptr, values.len()); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | $vt.0)); + output.payload_mut().$ca = $container { + cElems: count, + pElems: ptr, + }; + }}; + } + match vector { + PropVariantVector::I8(values) => { + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::(values.len())?; + if !ptr.is_null() { + std::ptr::copy_nonoverlapping(values.as_ptr(), ptr, values.len()); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | VT_I1.0)); + output.payload_mut().cac = CAC { + cElems: count, + pElems: windows_core::PSTR(ptr.cast()), + }; + } + PropVariantVector::U8(values) => { + write_plain_vector!(values, VT_UI1, caub, u8, CAUB) + } + PropVariantVector::I16(values) => { + write_plain_vector!(values, VT_I2, cai, i16, CAI) + } + PropVariantVector::U16(values) => { + write_plain_vector!(values, VT_UI2, caui, u16, CAUI) + } + PropVariantVector::I32(values) => { + write_plain_vector!(values, VT_I4, cal, i32, CAL) + } + PropVariantVector::U32(values) => { + write_plain_vector!(values, VT_UI4, caul, u32, CAUL) + } + PropVariantVector::I64(values) => { + write_plain_vector!(values, VT_I8, cah, i64, CAH) + } + PropVariantVector::U64(values) => { + write_plain_vector!(values, VT_UI8, cauh, u64, CAUH) + } + PropVariantVector::F32(values) => { + write_plain_vector!(values, VT_R4, caflt, f32, CAFLT) + } + PropVariantVector::F64(values) => { + write_plain_vector!(values, VT_R8, cadbl, f64, CADBL) + } + PropVariantVector::Bool(values) => { + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::(values.len())?; + for (index, value) in values.iter().enumerate() { + ptr.add(index) + .write(VARIANT_BOOL(if *value { -1 } else { 0 })); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | VT_BOOL.0)); + output.payload_mut().cabool = CABOOL { + cElems: count, + pElems: ptr, + }; + } + PropVariantVector::String(values) => { + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::(values.len())?; + if !ptr.is_null() { + std::ptr::write_bytes(ptr, 0, values.len()); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | VT_LPWSTR.0)); + output.payload_mut().calpwstr = CALPWSTR { + cElems: count, + pElems: ptr, + }; + for (index, value) in values.iter().enumerate() { + ptr.add(index).write(allocate_cotaskmem_wide(value)?); + } + } + PropVariantVector::Guid(values) => { + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::(values.len())?; + if !ptr.is_null() { + std::ptr::copy_nonoverlapping(values.as_ptr(), ptr, values.len()); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | VT_CLSID.0)); + output.payload_mut().cauuid = CACLSID { + cElems: count, + pElems: ptr, + }; + } + PropVariantVector::FileTime(values) => { + let count = u32::try_from(values.len()) + .map_err(|_| invalid_argument("PROPVARIANT vector length exceeds u32"))?; + let ptr = allocate_cotaskmem_slice::(values.len())?; + for (index, value) in values.iter().enumerate() { + ptr.add(index).write(u64_to_filetime(*value)); + } + output.set_vartype(VARENUM(VT_VECTOR.0 | VT_FILETIME.0)); + output.payload_mut().cafiletime = CAFILETIME { + cElems: count, + pElems: ptr, + }; + } + } + } + Ok(()) +} + +fn read_propvariant_vector( + payload: &windows::Win32::System::Com::StructuredStorage::PROPVARIANT_0_0_0, + typ: PropVariantVectorType, +) -> result::Result { + unsafe { + macro_rules! read_plain_vector { + ($ca:ident, $variant:ident, $native:ty) => {{ + let ca = payload.$ca; + let length = validate_vector_pointer(ca.cElems, ca.pElems.cast::<$native>())?; + PropVariantVector::$variant(if length == 0 { + Vec::new() + } else { + std::slice::from_raw_parts(ca.pElems.cast::<$native>(), length).to_vec() + }) + }}; + } + Ok(match typ { + PropVariantVectorType::I8 => { + let ca = payload.cac; + let length = validate_vector_pointer(ca.cElems, ca.pElems.0.cast::())?; + PropVariantVector::I8(if length == 0 { + Vec::new() + } else { + std::slice::from_raw_parts(ca.pElems.0.cast::(), length).to_vec() + }) + } + PropVariantVectorType::U8 => read_plain_vector!(caub, U8, u8), + PropVariantVectorType::I16 => read_plain_vector!(cai, I16, i16), + PropVariantVectorType::U16 => read_plain_vector!(caui, U16, u16), + PropVariantVectorType::I32 => read_plain_vector!(cal, I32, i32), + PropVariantVectorType::U32 => read_plain_vector!(caul, U32, u32), + PropVariantVectorType::I64 => read_plain_vector!(cah, I64, i64), + PropVariantVectorType::U64 => read_plain_vector!(cauh, U64, u64), + PropVariantVectorType::F32 => read_plain_vector!(caflt, F32, f32), + PropVariantVectorType::F64 => read_plain_vector!(cadbl, F64, f64), + PropVariantVectorType::Bool => { + let ca = payload.cabool; + let length = validate_vector_pointer(ca.cElems, ca.pElems)?; + let mut values = Vec::with_capacity(length); + let elements = if length == 0 { + &[] + } else { + std::slice::from_raw_parts(ca.pElems, length) + }; + for value in elements { + if !matches!(value.0, 0 | -1) { + return Err(invalid_argument(format!( + "PROPVARIANT vector VT_BOOL element must be 0 or -1, received {}", + value.0 + ))); + } + values.push(value.0 == -1); + } + PropVariantVector::Bool(values) + } + PropVariantVectorType::String => { + let ca = payload.calpwstr; + let length = validate_vector_pointer(ca.cElems, ca.pElems)?; + let mut values = Vec::with_capacity(length); + let elements = if length == 0 { + &[] + } else { + std::slice::from_raw_parts(ca.pElems, length) + }; + for value in elements { + values.push(read_wide_string(*value)?); + } + PropVariantVector::String(values) + } + PropVariantVectorType::Guid => { + let ca = payload.cauuid; + let length = validate_vector_pointer(ca.cElems, ca.pElems)?; + PropVariantVector::Guid(if length == 0 { + Vec::new() + } else { + std::slice::from_raw_parts(ca.pElems, length).to_vec() + }) + } + PropVariantVectorType::FileTime => { + let ca = payload.cafiletime; + let length = validate_vector_pointer(ca.cElems, ca.pElems)?; + let elements = if length == 0 { + &[] + } else { + std::slice::from_raw_parts(ca.pElems, length) + }; + PropVariantVector::FileTime(elements.iter().copied().map(filetime_to_u64).collect()) + } + }) + } +} + +fn validate_vector_pointer(count: u32, ptr: *const T) -> result::Result { + let length = count as usize; + validate_contiguous_size(length, std::mem::size_of::(), "PROPVARIANT vector")?; + validate_data_pointer( + length, + ptr.cast_mut().cast(), + std::mem::align_of::(), + "PROPVARIANT vector", + )?; + Ok(length) +} + +fn validate_contiguous_size( + length: usize, + element_size: usize, + name: &str, +) -> result::Result { + let byte_length = length + .checked_mul(element_size) + .ok_or_else(|| invalid_argument(format!("{name} byte length overflows")))?; + if byte_length > isize::MAX as usize { + return Err(invalid_argument(format!( + "{name} byte length exceeds the addressable slice limit" + ))); + } + Ok(byte_length) +} + +fn validate_data_pointer( + length: usize, + ptr: *mut c_void, + alignment: usize, + name: &str, +) -> result::Result<()> { + if length == 0 { + return Ok(()); + } + if ptr.is_null() { + return Err(invalid_argument(format!( + "{name} has a null pointer with non-zero length" + ))); + } + if ptr as usize % alignment != 0 { + return Err(invalid_argument(format!( + "{name} pointer does not satisfy {alignment}-byte alignment" + ))); + } + Ok(()) +} + +fn allocate_cotaskmem_wide(value: &str) -> result::Result { + if value.encode_utf16().any(|unit| unit == 0) { + return Err(invalid_argument( + "PROPVARIANT LPWSTR values cannot contain embedded NUL characters", + )); + } + let utf16 = value.encode_utf16().chain(Some(0)).collect::>(); + let bytes = utf16 + .len() + .checked_mul(std::mem::size_of::()) + .ok_or_else(|| invalid_argument("UTF-16 allocation size overflows"))?; + let ptr = unsafe { CoTaskMemAlloc(bytes) }.cast::(); + if ptr.is_null() { + return Err(out_of_memory( + "CoTaskMemAlloc failed for PROPVARIANT string", + )); + } + unsafe { std::ptr::copy_nonoverlapping(utf16.as_ptr(), ptr, utf16.len()) }; + Ok(PWSTR(ptr)) +} + +fn read_wide_string(value: PWSTR) -> result::Result { + if value.is_null() { + return Ok(String::new()); + } + let mut length = 0usize; + unsafe { + while *value.0.add(length) != 0 { + length = length + .checked_add(1) + .ok_or_else(|| invalid_argument("PROPVARIANT string length overflows"))?; + } + String::from_utf16(std::slice::from_raw_parts(value.0, length)) + .map_err(|_| invalid_argument("PROPVARIANT string is not valid UTF-16")) + } +} + +fn allocate_cotaskmem_bytes(value: &[u8]) -> result::Result<*mut u8> { + if value.is_empty() { + return Ok(std::ptr::null_mut()); + } + let ptr = unsafe { CoTaskMemAlloc(value.len()) }.cast::(); + if ptr.is_null() { + return Err(out_of_memory("CoTaskMemAlloc failed for PROPVARIANT blob")); + } + unsafe { std::ptr::copy_nonoverlapping(value.as_ptr(), ptr, value.len()) }; + Ok(ptr) +} + +unsafe fn allocate_cotaskmem_slice(length: usize) -> result::Result<*mut T> { + if length == 0 { + return Ok(std::ptr::null_mut()); + } + let bytes = validate_contiguous_size(length, std::mem::size_of::(), "PROPVARIANT vector")?; + let ptr = unsafe { CoTaskMemAlloc(bytes) }.cast::(); + if ptr.is_null() { + Err(out_of_memory( + "CoTaskMemAlloc failed for PROPVARIANT vector", + )) + } else { + Ok(ptr) + } +} + +fn u64_to_filetime(value: u64) -> FILETIME { + FILETIME { + dwLowDateTime: value as u32, + dwHighDateTime: (value >> 32) as u32, + } +} + +fn filetime_to_u64(value: FILETIME) -> u64 { + u64::from(value.dwLowDateTime) | (u64::from(value.dwHighDateTime) << 32) +} + +pub(crate) fn cleanup_safearray(raw: *mut c_void) { + if !raw.is_null() { + let _ = unsafe { SafeArrayDestroy(raw.cast()) }; + } +} + +pub(crate) fn cleanup_variant(raw: *mut c_void) { + if !raw.is_null() { + let _ = unsafe { VariantClear(raw.cast()) }; + } +} + +pub(crate) fn cleanup_propvariant(raw: *mut c_void) { + if !raw.is_null() { + let _ = unsafe { PropVariantClear(raw.cast()) }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::{align_of, offset_of, size_of}; + + unsafe fn variant_i32(raw: *const VARIANT) -> i32 { + let record = unsafe { + &*((&(*raw).Anonymous.Anonymous as *const ManuallyDrop) + .cast::()) + }; + assert_eq!(record.vt, VT_I4); + unsafe { record.Anonymous.lVal } + } + + #[test] + fn automation_compound_abi_matches_windows_rs() { + assert_eq!(offset_of!(DISPPARAMS, rgvarg), 0); + assert_eq!( + offset_of!(DISPPARAMS, rgdispidNamedArgs), + size_of::() + ); + assert_eq!(offset_of!(DISPPARAMS, cArgs), size_of::() * 2); + assert_eq!( + offset_of!(DISPPARAMS, cNamedArgs), + size_of::() * 2 + 4 + ); + + assert_eq!(offset_of!(EXCEPINFO, wCode), 0); + assert_eq!(offset_of!(EXCEPINFO, wReserved), 2); + assert_eq!(offset_of!(EXCEPINFO, bstrSource), size_of::()); + assert_eq!( + offset_of!(EXCEPINFO, bstrDescription), + size_of::() * 2 + ); + assert_eq!(offset_of!(EXCEPINFO, bstrHelpFile), size_of::() * 3); + assert_eq!(offset_of!(EXCEPINFO, dwHelpContext), size_of::() * 4); + + #[cfg(target_pointer_width = "64")] + { + assert_eq!((size_of::(), align_of::()), (24, 8)); + assert_eq!((size_of::(), align_of::()), (64, 8)); + assert_eq!(offset_of!(EXCEPINFO, pvReserved), 40); + assert_eq!(offset_of!(EXCEPINFO, pfnDeferredFillIn), 48); + assert_eq!(offset_of!(EXCEPINFO, scode), 56); + } + #[cfg(target_pointer_width = "32")] + { + assert_eq!((size_of::(), align_of::()), (16, 4)); + assert_eq!((size_of::(), align_of::()), (32, 4)); + assert_eq!(offset_of!(EXCEPINFO, pvReserved), 20); + assert_eq!(offset_of!(EXCEPINFO, pfnDeferredFillIn), 24); + assert_eq!(offset_of!(EXCEPINFO, scode), 28); + } + } + + #[test] + fn dispatch_params_reverses_arguments_and_named_dispids_in_stable_storage() { + let value = DispatchParamsValue::new( + &[ + VariantValue::from_i32(10), + VariantValue::from_i32(20), + VariantValue::from_i32(30), + ], + &[100, 200], + ) + .unwrap(); + let raw = unsafe { &*value.raw_mut() }; + assert_eq!((raw.cArgs, raw.cNamedArgs), (3, 2)); + assert!(!raw.rgvarg.is_null()); + assert!(!raw.rgdispidNamedArgs.is_null()); + assert_eq!( + unsafe { std::slice::from_raw_parts(raw.rgdispidNamedArgs, raw.cNamedArgs as usize) }, + &[200, 100] + ); + assert_eq!(unsafe { variant_i32(raw.rgvarg) }, 30); + assert_eq!(unsafe { variant_i32(raw.rgvarg.add(1)) }, 20); + assert_eq!(unsafe { variant_i32(raw.rgvarg.add(2)) }, 10); + assert_eq!( + unsafe { raw.rgvarg.add(1).byte_offset_from(raw.rgvarg) }, + size_of::() as isize + ); + + let clone = value.clone(); + assert_eq!(clone.raw_mut(), value.raw_mut()); + assert_eq!(clone.named_dispids(), [100, 200]); + assert!(DispatchParamsValue::new(&[VariantValue::empty()], &[1, 2]).is_err()); + } + + #[test] + fn variant_bool_uses_automation_true() { + let value = VariantValue::from_bool(true); + assert_eq!(value.vartype(), VT_BOOL.0); + assert!(matches!(value.data().unwrap(), VariantData::Bool(true))); + assert_eq!(unsafe { value.payload().boolVal.0 }, -1); + } + + #[test] + fn byref_and_next_unsupported_variant_fail_closed() { + assert!(variant_type(VT_BYREF.0 | VT_I4.0).is_err()); + assert!(variant_type(windows::Win32::System::Variant::VT_DATE.0).is_err()); + } + + #[test] + fn safearray_preserves_bounds_and_typed_elements() { + let array = SafeArrayValue::new( + SafeArrayElementType::I32, + vec![ + SafeArrayBound::new(-2, 2).unwrap(), + SafeArrayBound::new(5, 2).unwrap(), + ], + vec![ + SafeArrayElementValue::I32(1), + SafeArrayElementValue::I32(2), + SafeArrayElementValue::I32(3), + SafeArrayElementValue::I32(4), + ], + ) + .unwrap(); + let native = array.lock_native().unwrap(); + let (mut lower, mut upper) = unsafe { + ( + SafeArrayGetLBound(native.as_raw(), 1).unwrap(), + SafeArrayGetUBound(native.as_raw(), 1).unwrap(), + ) + }; + assert_eq!((lower, upper), (-2, -1)); + (lower, upper) = unsafe { + ( + SafeArrayGetLBound(native.as_raw(), 2).unwrap(), + SafeArrayGetUBound(native.as_raw(), 2).unwrap(), + ) + }; + assert_eq!((lower, upper), (5, 6)); + drop(native); + assert_eq!(array.bounds()[0], SafeArrayBound::new(-2, 2).unwrap()); + assert_eq!(array.bounds()[1], SafeArrayBound::new(5, 2).unwrap()); + assert!(matches!( + array.elements().unwrap().as_slice(), + [ + SafeArrayElementValue::I32(1), + SafeArrayElementValue::I32(2), + SafeArrayElementValue::I32(3), + SafeArrayElementValue::I32(4) + ] + )); + } + + #[test] + fn safearray_rejects_mismatched_elements_and_rank() { + assert!( + SafeArrayValue::new( + SafeArrayElementType::I32, + vec![SafeArrayBound::new(0, 1).unwrap()], + vec![SafeArrayElementValue::U32(1)], + ) + .is_err() + ); + assert!(SafeArrayValue::new(SafeArrayElementType::I32, vec![], vec![],).is_err()); + assert!(SafeArrayBound::new(i32::MAX, 2).is_err()); + assert!(SafeArrayBound::new(i32::MIN, 0).is_err()); + } + + #[test] + fn propvariant_scalar_owned_and_vector_values_roundtrip() { + let string = PropVariantValue::from_string("dynwinrt").unwrap(); + assert!(matches!( + string.data().unwrap(), + PropVariantData::String(value) if value == "dynwinrt" + )); + + let guid = GUID::from_u128(0x11223344_5566_7788_99aa_bbccddeeff00); + let vector = PropVariantValue::from_vector(PropVariantVector::Guid(vec![guid])).unwrap(); + assert!(matches!( + vector.data().unwrap(), + PropVariantData::Vector(PropVariantVector::Guid(values)) if values == vec![guid] + )); + + let bools = PropVariantValue::from_vector(PropVariantVector::Bool(Vec::new())).unwrap(); + assert!(matches!( + bools.data().unwrap(), + PropVariantData::Vector(PropVariantVector::Bool(values)) if values.is_empty() + )); + let strings = PropVariantValue::from_vector(PropVariantVector::String(Vec::new())).unwrap(); + assert!(matches!( + strings.data().unwrap(), + PropVariantData::Vector(PropVariantVector::String(values)) if values.is_empty() + )); + let filetimes = + PropVariantValue::from_vector(PropVariantVector::FileTime(Vec::new())).unwrap(); + assert!(matches!( + filetimes.data().unwrap(), + PropVariantData::Vector(PropVariantVector::FileTime(values)) if values.is_empty() + )); + } + + #[test] + fn propvariant_nested_vector_fails_closed() { + assert!(propvariant_type(VT_VECTOR.0 | VT_VARIANT.0).is_err()); + assert!(propvariant_type(windows::Win32::System::Variant::VT_STREAM.0).is_err()); + } + + #[test] + fn propvariant_strings_reject_embedded_nuls() { + assert!(PropVariantValue::from_string("before\0after").is_err()); + assert!( + PropVariantValue::from_vector(PropVariantVector::String(vec![ + "valid".into(), + "bad\0value".into(), + ])) + .is_err() + ); + } +} diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 2745d2b5..7809dafb 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -229,10 +229,10 @@ impl ValueTypeData { method_index: usize, ) -> windows_core::Result { use crate::call::get_vtable_function_ptr; - use libffi::middle::{Cif, CodePtr, Type, arg}; + use libffi::middle::{CodePtr, Type, arg}; let fptr = get_vtable_function_ptr(obj_raw, method_index); - let cif = Cif::new( + let cif = crate::native_call::system_cif( vec![ Type::pointer(), self.type_handle.libffi_type(), diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index a125092e..10a0da2c 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -15,10 +15,58 @@ use crate::{ value::WinRTValue, }; -#[derive(Debug, Clone)] +pub(crate) fn system_cif(types: Vec, result: libffi::middle::Type) -> Cif { + #[cfg(all(windows, target_arch = "x86"))] + { + Cif::new_with_abi(types.into_iter(), result, libffi_sys::ffi_abi_FFI_STDCALL) + } + #[cfg(not(all(windows, target_arch = "x86")))] + { + Cif::new(types.into_iter(), result) + } +} + +#[derive(Debug)] +pub(crate) enum NativeCallValue { + WinRt(WinRTValue), + NativeStruct(crate::com::NativeStructValue), + Variant(crate::com::VariantValue), + SafeArray(crate::com::SafeArrayValue), + PropVariant(crate::com::PropVariantValue), + ExcepInfo(crate::com::ExcepInfoValue), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct CapturedHResultPlan { + pub(crate) result_output_index: usize, + pub(crate) excep_info_output_index: usize, + pub(crate) arg_err_output_index: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum ParameterType { WinRT(TypeHandle), Pointer, + CoTaskMemWideString, + Bstr { + nullable: bool, + }, + NativeStruct(Arc), + NativeStructPointer { + layout: Arc, + nullable: bool, + }, + NativeUnionPointer(Arc), + Variant, + VariantByValue, + SafeArray { + element: Option, + interface_iid: Option, + nullable: bool, + }, + PropVariant, + DispatchParams, + ExcepInfo, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -28,10 +76,13 @@ pub(crate) enum OutputCleanup { HStringDelete, CoTaskMemFree, BstrFree, + VariantClear, + SafeArrayDestroy, + PropVariantClear, } impl OutputCleanup { - unsafe fn cleanup(self, ptr: *mut std::ffi::c_void) { + pub(crate) unsafe fn cleanup(self, ptr: *mut std::ffi::c_void) { if ptr.is_null() { return; } @@ -46,6 +97,9 @@ impl OutputCleanup { windows::Win32::System::Com::CoTaskMemFree(Some(ptr)); }, Self::BstrFree => drop(unsafe { windows_core::BSTR::from_raw(ptr.cast()) }), + Self::VariantClear => crate::com::automation::cleanup_variant(ptr), + Self::SafeArrayDestroy => crate::com::automation::cleanup_safearray(ptr), + Self::PropVariantClear => crate::com::automation::cleanup_propvariant(ptr), } } } @@ -59,13 +113,180 @@ impl ParameterType { Self::Pointer } + pub(crate) fn co_task_mem_wide_string() -> Self { + Self::CoTaskMemWideString + } + + pub(crate) fn bstr(nullable: bool) -> Self { + Self::Bstr { nullable } + } + + pub(crate) fn native_struct(layout: Arc) -> Self { + Self::NativeStruct(layout) + } + + pub(crate) fn native_struct_pointer( + layout: Arc, + nullable: bool, + ) -> Self { + Self::NativeStructPointer { layout, nullable } + } + + pub(crate) fn native_union_pointer(layout: Arc) -> Self { + Self::NativeUnionPointer(layout) + } + + pub(crate) fn variant() -> Self { + Self::Variant + } + + pub(crate) fn variant_by_value() -> Self { + Self::VariantByValue + } + + pub(crate) fn safe_array(element: Option) -> Self { + Self::SafeArray { + element, + interface_iid: None, + nullable: false, + } + } + + pub(crate) fn interface_safe_array(iid: GUID) -> Self { + Self::SafeArray { + element: Some(crate::com::SafeArrayElementType::Unknown), + interface_iid: Some(iid), + nullable: false, + } + } + + pub(crate) fn nullable_safe_array( + element: crate::com::SafeArrayElementType, + interface_iid: Option, + ) -> Self { + Self::SafeArray { + element: Some(element), + interface_iid, + nullable: true, + } + } + + pub(crate) fn prop_variant() -> Self { + Self::PropVariant + } + + pub(crate) fn dispatch_params() -> Self { + Self::DispatchParams + } + + pub(crate) fn excep_info() -> Self { + Self::ExcepInfo + } + pub(crate) fn as_winrt(&self) -> Option<&TypeHandle> { match self { Self::WinRT(typ) => Some(typ), - Self::Pointer => None, + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStruct(_) + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) + | Self::Variant + | Self::VariantByValue + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => None, + } + } + + pub(crate) fn native_struct_layout(&self) -> Option<&Arc> { + match self { + Self::NativeStruct(layout) | Self::NativeStructPointer { layout, .. } => Some(layout), + Self::WinRT(_) + | Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeUnionPointer(_) + | Self::Variant + | Self::VariantByValue + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => None, + } + } + + pub(crate) fn native_union_layout(&self) -> Option<&Arc> { + match self { + Self::NativeUnionPointer(layout) => Some(layout), + _ => None, + } + } + + pub(crate) fn is_native_struct(&self) -> bool { + matches!(self, Self::NativeStruct(_)) + } + + pub(crate) fn is_native_struct_pointer(&self) -> bool { + matches!(self, Self::NativeStructPointer { .. }) + } + + pub(crate) fn is_nullable_native_struct_pointer(&self) -> bool { + matches!(self, Self::NativeStructPointer { nullable: true, .. }) + } + + pub(crate) fn is_variant(&self) -> bool { + matches!(self, Self::Variant) + } + + pub(crate) fn is_bstr(&self) -> bool { + matches!(self, Self::Bstr { .. }) + } + + pub(crate) fn is_nullable_bstr(&self) -> bool { + matches!(self, Self::Bstr { nullable: true }) + } + + pub(crate) fn is_variant_by_value(&self) -> bool { + matches!(self, Self::VariantByValue) + } + + pub(crate) fn is_safe_array(&self) -> bool { + matches!(self, Self::SafeArray { .. }) + } + + pub(crate) fn safe_array_element(&self) -> Option { + match self { + Self::SafeArray { element, .. } => *element, + _ => None, + } + } + + pub(crate) fn safe_array_interface_iid(&self) -> Option { + match self { + Self::SafeArray { interface_iid, .. } => *interface_iid, + _ => None, } } + pub(crate) fn is_nullable_safe_array(&self) -> bool { + matches!(self, Self::SafeArray { nullable: true, .. }) + } + + pub(crate) fn is_prop_variant(&self) -> bool { + matches!(self, Self::PropVariant) + } + + pub(crate) fn is_dispatch_params(&self) -> bool { + matches!(self, Self::DispatchParams) + } + + pub(crate) fn is_excep_info(&self) -> bool { + matches!(self, Self::ExcepInfo) + } + pub(crate) fn is_array(&self) -> bool { self.as_winrt().is_some_and(TypeHandle::is_array) } @@ -87,67 +308,70 @@ impl ParameterType { } pub(crate) fn supports_in_out(&self) -> bool { - matches!(self, Self::Pointer) - || matches!( - self, - Self::WinRT(typ) - if matches!( - typ.kind(), - TypeKind::Bool - | TypeKind::I8 - | TypeKind::U8 - | TypeKind::I16 - | TypeKind::U16 - | TypeKind::Char16 - | TypeKind::I32 - | TypeKind::U32 - | TypeKind::I64 - | TypeKind::U64 - | TypeKind::F32 - | TypeKind::F64 - | TypeKind::HResult - | TypeKind::Enum(_) - | TypeKind::Struct(_) - ) - ) - } - - pub(crate) fn supports_direct_return(&self) -> bool { - matches!(self, Self::Pointer) - || matches!( - self, - Self::WinRT(typ) - if matches!( - typ.kind(), - TypeKind::Bool - | TypeKind::I8 - | TypeKind::U8 - | TypeKind::I16 - | TypeKind::U16 - | TypeKind::Char16 - | TypeKind::I32 - | TypeKind::U32 - | TypeKind::I64 - | TypeKind::U64 - | TypeKind::F32 - | TypeKind::F64 - | TypeKind::HResult - | TypeKind::Enum(_) - ) - ) + matches!( + self, + Self::Pointer + | Self::Bstr { .. } + | Self::NativeStruct(_) + | Self::NativeStructPointer { .. } + ) || matches!( + self, + Self::WinRT(typ) + if matches!( + typ.kind(), + TypeKind::Bool + | TypeKind::I8 + | TypeKind::U8 + | TypeKind::I16 + | TypeKind::U16 + | TypeKind::Char16 + | TypeKind::I32 + | TypeKind::U32 + | TypeKind::I64 + | TypeKind::U64 + | TypeKind::F32 + | TypeKind::F64 + | TypeKind::HResult + | TypeKind::Enum(_) + | TypeKind::Struct(_) + ) + ) } pub(crate) fn abi_type(&self) -> AbiType { match self { Self::WinRT(typ) => typ.abi_type(), - Self::Pointer => AbiType::Ptr, + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) + | Self::Variant + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => AbiType::Ptr, + Self::NativeStruct(_) | Self::VariantByValue => { + panic!("aggregate values do not have a scalar AbiType") + } } } pub(crate) fn libffi_type(&self) -> libffi::middle::Type { match self { Self::WinRT(typ) => typ.libffi_type(), - Self::Pointer => libffi::middle::Type::pointer(), + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) + | Self::Variant + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => libffi::middle::Type::pointer(), + Self::NativeStruct(layout) => layout.libffi_type(), + Self::VariantByValue => variant_by_value_libffi_type(), } } @@ -167,43 +391,121 @@ impl ParameterType { match self { Self::WinRT(typ) => typ.default_winrt_value(), Self::Pointer => WinRTValue::RawPtr(std::ptr::null_mut()), + Self::CoTaskMemWideString => WinRTValue::RawPtr(std::ptr::null_mut()), + Self::Bstr { .. } => panic!("BSTR storage is allocated by the dynamic executor"), + Self::NativeStruct(_) + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) + | Self::Variant + | Self::VariantByValue + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => { + panic!("native POD storage is allocated by the dynamic executor") + } } } pub(crate) fn from_out(&self, ptr: *mut std::ffi::c_void) -> crate::result::Result { match self { Self::WinRT(typ) => typ.from_out(ptr), - Self::Pointer => Ok(WinRTValue::RawPtr(ptr)), + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) => Ok(WinRTValue::RawPtr(ptr)), + Self::NativeStruct(_) + | Self::Variant + | Self::VariantByValue + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo => { + unreachable!("native POD output conversion uses NativeStructValue") + } } } pub(crate) fn from_out_value(&self, value: &AbiValue) -> crate::result::Result { match (self, value) { (Self::WinRT(typ), value) => typ.from_out_value(value), - (Self::Pointer, AbiValue::Pointer(ptr)) => Ok(WinRTValue::RawPtr(*ptr)), - (Self::Pointer, value) => Err(crate::result::Error::InvalidTypeAbiToWinRT( + ( + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_), + AbiValue::Pointer(ptr), + ) => Ok(WinRTValue::RawPtr(*ptr)), + ( + Self::Pointer + | Self::CoTaskMemWideString + | Self::Bstr { .. } + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_), + value, + ) => Err(crate::result::Error::InvalidTypeAbiToWinRT( TypeKind::Object, value.abi_type(), )), + ( + Self::NativeStruct(_) + | Self::Variant + | Self::VariantByValue + | Self::SafeArray { .. } + | Self::PropVariant + | Self::DispatchParams + | Self::ExcepInfo, + _, + ) => { + unreachable!("native POD output conversion uses NativeStructValue") + } } } - fn default_output_cleanup(&self) -> OutputCleanup { + pub(crate) fn default_output_cleanup(&self) -> OutputCleanup { match self { Self::WinRT(typ) if typ.kind().is_com_pointer() => OutputCleanup::ComRelease, Self::WinRT(typ) if matches!(typ.kind(), TypeKind::HString) => { OutputCleanup::HStringDelete } - Self::WinRT(_) | Self::Pointer => OutputCleanup::None, + Self::Variant => OutputCleanup::VariantClear, + Self::SafeArray { .. } => OutputCleanup::SafeArrayDestroy, + Self::PropVariant => OutputCleanup::PropVariantClear, + Self::ExcepInfo => OutputCleanup::None, + Self::Bstr { .. } => OutputCleanup::BstrFree, + Self::CoTaskMemWideString => OutputCleanup::CoTaskMemFree, + Self::WinRT(_) + | Self::Pointer + | Self::NativeStruct(_) + | Self::NativeStructPointer { .. } + | Self::NativeUnionPointer(_) + | Self::VariantByValue + | Self::DispatchParams => OutputCleanup::None, } } } +fn variant_by_value_libffi_type() -> libffi::middle::Type { + use libffi::middle::Type; + + let mut fields = vec![Type::u16(), Type::u16(), Type::u16(), Type::u16()]; + #[cfg(target_pointer_width = "64")] + fields.extend([Type::u64(), Type::u64()]); + #[cfg(target_pointer_width = "32")] + fields.push(Type::u64()); + Type::structure(fields) +} + /// How a parameter is passed at the ABI level. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ParamKind { In, Out, + /// Optional output pointer. The logical input is a Boolean request flag; + /// the native ABI receives either stable output storage or null. + OptionalOut, InOut, /// FillArray: caller allocates buffer, callee fills it. /// ABI expands to 2 params: (u32 capacity, T* items). @@ -224,13 +526,16 @@ pub struct Parameter { impl Parameter { pub fn is_input(&self) -> bool { - matches!(self.kind, ParamKind::In | ParamKind::InOut) + matches!( + self.kind, + ParamKind::In | ParamKind::OptionalOut | ParamKind::InOut + ) } pub fn is_out(&self) -> bool { matches!( self.kind, - ParamKind::Out | ParamKind::InOut | ParamKind::OutFillArray + ParamKind::Out | ParamKind::OptionalOut | ParamKind::InOut | ParamKind::OutFillArray ) } @@ -238,6 +543,10 @@ impl Parameter { self.kind == ParamKind::InOut } + pub fn is_optional_out(&self) -> bool { + self.kind == ParamKind::OptionalOut + } + pub fn is_fill_array(&self) -> bool { self.kind == ParamKind::OutFillArray } @@ -263,16 +572,24 @@ pub(crate) struct AbiMethodSignature { pub(crate) enum MethodReturn { HResult, SemanticHResult, + PreservedHResult, + CapturedHResult(CapturedHResultPlan), Void, - Value(ParameterType), + Value { + typ: ParameterType, + cleanup: OutputCleanup, + }, } impl MethodReturn { fn libffi_type(&self) -> libffi::middle::Type { match self { - Self::HResult | Self::SemanticHResult => libffi::middle::Type::i32(), + Self::HResult + | Self::SemanticHResult + | Self::PreservedHResult + | Self::CapturedHResult(_) => libffi::middle::Type::i32(), Self::Void => libffi::middle::Type::void(), - Self::Value(typ) => typ.libffi_type(), + Self::Value { typ, .. } => typ.libffi_type(), } } } @@ -324,7 +641,35 @@ impl AbiMethodSignature { self } - pub(crate) fn add_in_out_type(mut self, typ: ParameterType) -> Self { + pub(crate) fn add_optional_out_type_with_cleanup( + mut self, + typ: ParameterType, + output_cleanup: OutputCleanup, + ) -> Self { + let input_index = self.input_count; + self.input_count += 1; + self.parameters.push(Parameter { + kind: ParamKind::OptionalOut, + typ, + output_cleanup, + value_index: self.out_count, + input_index: Some(input_index), + }); + self.out_count += 1; + self + } + + #[cfg(test)] + pub(crate) fn add_in_out_type(self, typ: ParameterType) -> Self { + let cleanup = typ.default_output_cleanup(); + self.add_in_out_type_with_cleanup(typ, cleanup) + } + + pub(crate) fn add_in_out_type_with_cleanup( + mut self, + typ: ParameterType, + output_cleanup: OutputCleanup, + ) -> Self { assert!( typ.supports_in_out(), "in/out currently supports native scalars, pointers, enums, and structs" @@ -334,7 +679,7 @@ impl AbiMethodSignature { self.parameters.push(Parameter { kind: ParamKind::InOut, typ, - output_cleanup: OutputCleanup::None, + output_cleanup, value_index: self.out_count, input_index: Some(input_index), }); @@ -356,25 +701,6 @@ impl AbiMethodSignature { self } - pub(crate) fn returns_type(mut self, typ: ParameterType) -> Self { - assert!( - typ.supports_direct_return(), - "direct native returns currently support scalars, enums, and pointers" - ); - self.return_kind = MethodReturn::Value(typ); - self - } - - pub(crate) fn returns_void(mut self) -> Self { - self.return_kind = MethodReturn::Void; - self - } - - pub(crate) fn preserve_hresult(mut self) -> Self { - self.return_kind = MethodReturn::SemanticHResult; - self - } - pub(crate) fn build(self, index: usize) -> Method { use libffi::middle::Type; let mut types: Vec = Vec::with_capacity(self.parameters.len() + 1); @@ -401,10 +727,22 @@ impl AbiMethodSignature { } } let in_count = self.parameters.iter().filter(|p| p.is_input()).count(); - let has_complex_param = self - .parameters - .iter() - .any(|p| p.typ.is_array() || p.is_fill_array() || p.is_in_out() || p.typ.is_struct()); + let has_complex_param = self.parameters.iter().any(|p| { + p.typ.is_array() + || p.is_fill_array() + || p.is_in_out() + || p.is_optional_out() + || p.typ.is_struct() + || p.typ.native_struct_layout().is_some() + || p.typ.native_union_layout().is_some() + || p.typ.is_variant() + || p.typ.is_bstr() + || p.typ.is_variant_by_value() + || p.typ.is_safe_array() + || p.typ.is_prop_variant() + || p.typ.is_dispatch_params() + || p.typ.is_excep_info() + }); // Check if the single in-param (if any) is a simple non-HString, non-Struct type let simple_in = !has_complex_param && in_count == 1 && { @@ -428,66 +766,64 @@ impl AbiMethodSignature { let scalar_out_count = self.out_count - fill_out_count - array_out_count; let returns_hresult = matches!(self.return_kind, MethodReturn::HResult); - let strategy = if returns_hresult - && !has_complex_param - && in_count == 0 - && self.out_count == 1 - { - CallStrategy::Direct0In1Out - } else if returns_hresult && !has_complex_param && in_count == 0 && self.out_count == 0 { - CallStrategy::Direct0In0Out - } else if returns_hresult && simple_in && self.out_count == 0 { - CallStrategy::Direct1In0Out - } else if returns_hresult && simple_in && self.out_count == 1 { - CallStrategy::Direct1In1Out - // ReceiveArray only: fn(this, *mut u32, *mut *mut c_void) -> HRESULT - } else if returns_hresult - && scalar_in_count == 0 - && array_in_count == 0 - && array_out_count == 1 - && fill_out_count == 0 - && scalar_out_count == 0 - { - CallStrategy::DirectReceiveArray - // PassArray + 1 out: fn(this, u32, *const u8, out) -> HRESULT - } else if returns_hresult - && scalar_in_count == 0 - && array_in_count == 1 - && array_out_count == 0 - && fill_out_count == 0 - && scalar_out_count == 1 - { - CallStrategy::DirectPassArray1Out - // FillArray only: fn(this, u32, *mut u8, *mut u32) -> HRESULT - } else if returns_hresult - && scalar_in_count == 0 - && array_in_count == 0 - && fill_out_count == 1 - && array_out_count == 0 - && scalar_out_count == 0 - { - CallStrategy::DirectFillArray - // 1 scalar in + FillArray: fn(this, val, u32, *mut u8, *mut u32) -> HRESULT - } else if returns_hresult - && scalar_in_count == 1 - && array_in_count == 0 - && fill_out_count == 1 - && array_out_count == 0 - && scalar_out_count == 0 - { - let in_param = self - .parameters - .iter() - .find(|p| p.is_input() && !p.typ.is_array()) - .unwrap(); - if !in_param.typ.is_hstring() && !in_param.typ.is_struct() { - CallStrategy::Direct1InFillArray + let strategy = + if returns_hresult && !has_complex_param && in_count == 0 && self.out_count == 1 { + CallStrategy::Direct0In1Out + } else if returns_hresult && !has_complex_param && in_count == 0 && self.out_count == 0 + { + CallStrategy::Direct0In0Out + } else if returns_hresult && simple_in && self.out_count == 0 { + CallStrategy::Direct1In0Out + } else if returns_hresult && simple_in && self.out_count == 1 { + CallStrategy::Direct1In1Out + // ReceiveArray only: fn(this, *mut u32, *mut *mut c_void) -> HRESULT + } else if returns_hresult + && scalar_in_count == 0 + && array_in_count == 0 + && array_out_count == 1 + && fill_out_count == 0 + && scalar_out_count == 0 + { + CallStrategy::DirectReceiveArray + // PassArray + 1 out: fn(this, u32, *const u8, out) -> HRESULT + } else if returns_hresult + && scalar_in_count == 0 + && array_in_count == 1 + && array_out_count == 0 + && fill_out_count == 0 + && scalar_out_count == 1 + { + CallStrategy::DirectPassArray1Out + // FillArray only: fn(this, u32, *mut u8, *mut u32) -> HRESULT + } else if returns_hresult + && scalar_in_count == 0 + && array_in_count == 0 + && fill_out_count == 1 + && array_out_count == 0 + && scalar_out_count == 0 + { + CallStrategy::DirectFillArray + // 1 scalar in + FillArray: fn(this, val, u32, *mut u8, *mut u32) -> HRESULT + } else if returns_hresult + && scalar_in_count == 1 + && array_in_count == 0 + && fill_out_count == 1 + && array_out_count == 0 + && scalar_out_count == 0 + { + let in_param = self + .parameters + .iter() + .find(|p| p.is_input() && !p.typ.is_array()) + .unwrap(); + if !in_param.typ.is_hstring() && !in_param.typ.is_struct() { + CallStrategy::Direct1InFillArray + } else { + CallStrategy::Libffi(system_cif(types, self.return_kind.libffi_type())) + } } else { - CallStrategy::Libffi(Cif::new(types.into_iter(), self.return_kind.libffi_type())) - } - } else { - CallStrategy::Libffi(Cif::new(types.into_iter(), self.return_kind.libffi_type())) - }; + CallStrategy::Libffi(system_cif(types, self.return_kind.libffi_type())) + }; Method { info: MethodInfo { @@ -502,6 +838,32 @@ impl AbiMethodSignature { } } +pub(crate) fn lower_completed_method( + table: &Arc, + index: usize, + parameters: Vec<(ParamKind, ParameterType, OutputCleanup)>, + return_kind: MethodReturn, +) -> Method { + let mut signature = AbiMethodSignature::new(table); + for (kind, typ, cleanup) in parameters { + signature = match kind { + ParamKind::In => { + assert_eq!(cleanup, OutputCleanup::None); + signature.add_in_type(typ) + } + ParamKind::Out => signature.add_out_type_with_cleanup(typ, cleanup), + ParamKind::OptionalOut => signature.add_optional_out_type_with_cleanup(typ, cleanup), + ParamKind::InOut => signature.add_in_out_type_with_cleanup(typ, cleanup), + ParamKind::OutFillArray => { + assert_eq!(cleanup, OutputCleanup::None); + signature.add_out_fill_type(typ) + } + }; + } + signature.return_kind = return_kind; + signature.build(index) +} + #[derive(Debug)] pub struct MethodInfo { pub index: usize, @@ -868,12 +1230,154 @@ impl call::ArgumentList for InvocationArgs<'_> { } } +struct ComInvocationArgs<'a> { + original: &'a [crate::com::Value], + replacements: Option>>, +} + +impl<'a> ComInvocationArgs<'a> { + fn new(original: &'a [crate::com::Value]) -> Self { + Self { + original, + replacements: None, + } + } + + fn replace(&mut self, index: usize, value: WinRTValue) { + self.replacements.get_or_insert_with(|| { + std::iter::repeat_with(|| None) + .take(self.original.len()) + .collect() + })[index] = Some(value); + } +} + +impl call::ArgumentList for ComInvocationArgs<'_> { + fn get_value(&self, index: usize) -> &WinRTValue { + if let Some(value) = self + .replacements + .as_ref() + .and_then(|values| values[index].as_ref()) + { + return value; + } + match &self.original[index] { + crate::com::Value::WinRt(value) => value, + crate::com::Value::Bstr(_) => { + panic!("BSTR argument requested as a WinRT value") + } + crate::com::Value::NativeStruct(_) => { + panic!("native struct argument requested as a WinRT value") + } + crate::com::Value::NativeUnion(_) + | crate::com::Value::Variant(_) + | crate::com::Value::SafeArray(_) + | crate::com::Value::PropVariant(_) + | crate::com::Value::DispatchParams(_) + | crate::com::Value::ExcepInfo(_) => { + panic!("COM-local argument requested as a WinRT value") + } + crate::com::Value::Buffer(_) => { + panic!("COM buffer reached the private native-call backend") + } + } + } + + fn get_native_struct(&self, index: usize) -> Option<&crate::com::NativeStructValue> { + match &self.original[index] { + crate::com::Value::NativeStruct(value) => Some(value), + _ => None, + } + } + + fn get_bstr(&self, index: usize) -> Option<&crate::com::BstrValue> { + match &self.original[index] { + crate::com::Value::Bstr(value) => Some(value), + _ => None, + } + } + + fn get_native_union(&self, index: usize) -> Option<&crate::com::NativeUnionValue> { + match &self.original[index] { + crate::com::Value::NativeUnion(value) => Some(value), + _ => None, + } + } + + fn get_variant(&self, index: usize) -> Option<&crate::com::VariantValue> { + match &self.original[index] { + crate::com::Value::Variant(value) => Some(value), + _ => None, + } + } + + fn get_safe_array(&self, index: usize) -> Option<&crate::com::SafeArrayValue> { + match &self.original[index] { + crate::com::Value::SafeArray(value) => Some(value), + _ => None, + } + } + + fn get_prop_variant(&self, index: usize) -> Option<&crate::com::PropVariantValue> { + match &self.original[index] { + crate::com::Value::PropVariant(value) => Some(value), + _ => None, + } + } + + fn get_dispatch_params(&self, index: usize) -> Option<&crate::com::DispatchParamsValue> { + match &self.original[index] { + crate::com::Value::DispatchParams(value) => Some(value), + _ => None, + } + } +} + impl Method { - #[cfg(test)] + pub(crate) fn parameter_type(&self, parameter_index: usize) -> &ParameterType { + &self.info.parameters[parameter_index].typ + } + pub(crate) fn output_cleanup(&self, parameter_index: usize) -> OutputCleanup { self.info.parameters[parameter_index].output_cleanup } + pub(crate) fn direct_return_type(&self) -> Option<&ParameterType> { + match &self.info.return_kind { + MethodReturn::Value { typ, .. } => Some(typ), + MethodReturn::HResult + | MethodReturn::SemanticHResult + | MethodReturn::PreservedHResult + | MethodReturn::CapturedHResult(_) + | MethodReturn::Void => None, + } + } + + pub(crate) fn uses_com_value_path(&self) -> bool { + self.info.parameters.iter().any(|parameter| { + parameter.is_optional_out() + || parameter.typ.native_struct_layout().is_some() + || parameter.typ.native_union_layout().is_some() + || parameter.typ.is_variant() + || parameter.typ.is_bstr() + || parameter.typ.is_variant_by_value() + || parameter.typ.is_safe_array() + || parameter.typ.is_prop_variant() + || parameter.typ.is_dispatch_params() + || parameter.typ.is_excep_info() + }) || self.direct_return_type().is_some_and(|typ| { + typ.native_struct_layout().is_some() + || typ.native_union_layout().is_some() + || typ.is_variant() + || typ.is_bstr() + || typ.is_variant_by_value() + || typ.is_safe_array() + || typ.is_prop_variant() + || typ.is_dispatch_params() + || typ.is_excep_info() + }) + } + // --- Fast getter paths: zero Vec/WinRTValue allocation --- /// Getter → i32 (0 in, 1 out). Writes directly to stack i32. @@ -1204,8 +1708,285 @@ impl Method { self.info.out_count, &self.info.return_kind, cif, - ), + ) + .and_then(|values| { + values + .into_iter() + .map(|value| match value { + NativeCallValue::WinRt(value) => Ok(value), + NativeCallValue::NativeStruct(_) => Err(invalid_argument( + "native POD result reached the WinRT invocation path", + )), + NativeCallValue::Variant(_) + | NativeCallValue::SafeArray(_) + | NativeCallValue::PropVariant(_) + | NativeCallValue::ExcepInfo(_) => Err(invalid_argument( + "COM-local result reached the WinRT invocation path", + )), + }) + .collect() + }), + } + } + + fn prepare_com_invocation_args<'a>( + &self, + args: &'a [crate::com::Value], + ) -> windows_core::Result> { + if args.len() != self.info.input_count { + return Err(invalid_argument(&format!( + "Argument count mismatch: expected {}, received {}", + self.info.input_count, + args.len() + ))); } + let mut invocation_args = ComInvocationArgs::new(args); + for parameter in self + .info + .parameters + .iter() + .filter(|parameter| parameter.is_input()) + { + let input_index = parameter.input_index.expect("input parameter index"); + if parameter.is_optional_out() { + if !matches!( + &args[input_index], + crate::com::Value::WinRt(WinRTValue::Bool(_)) + ) { + return Err(invalid_argument( + "Optional COM output request must be a Boolean value", + )); + } + continue; + } + if parameter.typ.is_dispatch_params() { + if !matches!(&args[input_index], crate::com::Value::DispatchParams(_)) { + return Err(invalid_argument( + "Argument type mismatch: expected DISPPARAMS", + )); + } + continue; + } + if parameter.typ.is_excep_info() { + return Err(invalid_argument("EXCEPINFO is output-only")); + } + if let Some(expected_layout) = parameter.typ.native_struct_layout() { + if parameter.typ.is_nullable_native_struct_pointer() + && matches!( + &args[input_index], + crate::com::Value::WinRt(value) if value.is_null_object() + ) + { + continue; + } + let value = match &args[input_index] { + crate::com::Value::NativeStruct(value) => value, + crate::com::Value::WinRt(value) => { + return Err(invalid_argument(&format!( + "Argument type mismatch: expected native struct `{}`, found {:?}", + expected_layout.name(), + value.get_type_kind() + ))); + } + crate::com::Value::Buffer(_) => { + return Err(invalid_argument( + "COM buffer passed to a native struct parameter", + )); + } + _ => { + return Err(invalid_argument( + "COM-local value passed to a native struct parameter", + )); + } + }; + if value.layout() != expected_layout { + return Err(invalid_argument(&format!( + "Native struct type mismatch: expected `{}`, received `{}`", + expected_layout.name(), + value.layout().name() + ))); + } + continue; + } + + if let Some(expected_layout) = parameter.typ.native_union_layout() { + let crate::com::Value::NativeUnion(value) = &args[input_index] else { + return Err(invalid_argument(&format!( + "Argument type mismatch: expected native union `{}`", + expected_layout.name() + ))); + }; + if value.layout() != expected_layout { + return Err(invalid_argument(&format!( + "Native union type mismatch: expected `{}`, received `{}`", + expected_layout.name(), + value.layout().name() + ))); + } + continue; + } + + if parameter.typ.is_variant() { + let crate::com::Value::Variant(value) = &args[input_index] else { + return Err(invalid_argument("Argument type mismatch: expected VARIANT")); + }; + value + .validate_supported() + .map_err(|error| invalid_argument(&error.message()))?; + continue; + } + + if parameter.typ.is_bstr() { + let crate::com::Value::Bstr(value) = &args[input_index] else { + return Err(invalid_argument("Argument type mismatch: expected BSTR")); + }; + if value.as_deref().is_none() && !parameter.typ.is_nullable_bstr() { + return Err(invalid_argument( + "Null BSTR input requires a nullable BSTR contract", + )); + } + continue; + } + + if parameter.typ.is_variant_by_value() { + let crate::com::Value::Variant(value) = &args[input_index] else { + return Err(invalid_argument( + "Argument type mismatch: expected by-value VARIANT", + )); + }; + value + .validate_supported() + .map_err(|error| invalid_argument(&error.message()))?; + continue; + } + + if parameter.typ.is_safe_array() { + let crate::com::Value::SafeArray(value) = &args[input_index] else { + return Err(invalid_argument( + "Argument type mismatch: expected SAFEARRAY", + )); + }; + if parameter + .typ + .safe_array_element() + .is_some_and(|expected| expected != value.element_type()) + { + return Err(invalid_argument(&format!( + "SAFEARRAY element type mismatch: expected {:?}, received {:?}", + parameter.typ.safe_array_element().unwrap(), + value.element_type() + ))); + } + if parameter + .typ + .safe_array_interface_iid() + .is_some_and(|expected| value.interface_iid() != Some(expected)) + { + return Err(invalid_argument(&format!( + "SAFEARRAY interface IID mismatch: expected {:?}, received {:?}", + parameter.typ.safe_array_interface_iid().unwrap(), + value.interface_iid() + ))); + } + continue; + } + + if parameter.typ.is_prop_variant() { + let crate::com::Value::PropVariant(value) = &args[input_index] else { + return Err(invalid_argument( + "Argument type mismatch: expected PROPVARIANT", + )); + }; + value + .validate_supported() + .map_err(|error| invalid_argument(&error.message()))?; + continue; + } + + let crate::com::Value::WinRt(value) = &args[input_index] else { + return Err(invalid_argument( + "COM-local value passed to a scalar or pointer parameter", + )); + }; + let coerced = if let Some(typ) = parameter.typ.as_winrt() { + if typ.is_array() { + coerce_input_array(typ, value)? + } else if expected_object_iid(typ).is_some() { + coerce_input_object(typ, value)? + } else { + coerce_scalar_input(typ, value)? + } + } else { + validate_pointer_input(value)?; + None + }; + if let Some(value) = coerced { + invocation_args.replace(input_index, value); + } + } + Ok(invocation_args) + } + + pub(crate) fn call_com_dynamic( + &self, + obj: *mut std::ffi::c_void, + args: &[crate::com::Value], + ) -> windows_core::Result> { + if matches!(self.info.return_kind, MethodReturn::CapturedHResult(_)) { + return Err(invalid_argument( + "captured HRESULT calls require the dedicated COM invocation path", + )); + } + let invocation_args = self.prepare_com_invocation_args(args)?; + let CallStrategy::Libffi(cif) = &self.strategy else { + return Err(invalid_argument( + "native POD calls must use the prepared libffi plan", + )); + }; + call::call_method_dynamic( + self.info.index, + obj, + &self.info.parameters, + &invocation_args, + self.info.out_count, + &self.info.return_kind, + cif, + ) + .map(|values| { + values + .into_iter() + .map(|value| match value { + NativeCallValue::WinRt(value) => crate::com::Value::WinRt(value), + NativeCallValue::NativeStruct(value) => crate::com::Value::NativeStruct(value), + NativeCallValue::Variant(value) => crate::com::Value::Variant(value), + NativeCallValue::SafeArray(value) => crate::com::Value::SafeArray(value), + NativeCallValue::PropVariant(value) => crate::com::Value::PropVariant(value), + NativeCallValue::ExcepInfo(value) => crate::com::Value::ExcepInfo(value), + }) + .collect() + }) + } + + pub(crate) fn call_com_dynamic_captured( + &self, + obj: *mut std::ffi::c_void, + args: &[crate::com::Value], + ) -> windows_core::Result { + let invocation_args = self.prepare_com_invocation_args(args)?; + let CallStrategy::Libffi(cif) = &self.strategy else { + return Err(invalid_argument( + "captured HRESULT calls must use the prepared libffi plan", + )); + }; + call::call_method_dynamic_captured( + self.info.index, + obj, + &self.info.parameters, + &invocation_args, + self.info.out_count, + &self.info.return_kind, + cif, + ) } } diff --git a/docs/classic-com-support.md b/docs/classic-com-support.md index 6bb38688..f45df502 100644 --- a/docs/classic-com-support.md +++ b/docs/classic-com-support.md @@ -3,11 +3,14 @@ `dynwinrt` supports a deliberately limited subset of Classic COM. It is not a general Automation or native Win32 projection. +For installation and application-facing examples, including GUID/IID/CLSID +and `/com/unsafe`, see [Classic COM JavaScript usage](classic-com-usage.md). + The design keeps the existing WinRT API separate: ```js import { DynWinRtType, DynWinRtValue } from '@microsoft/dynwinrt'; -import { DynCom, DynComMethodSig } from '@microsoft/dynwinrt/com'; +import { DynComVariant, initializeCom } from '@microsoft/dynwinrt/com'; ``` Both entrypoints use the same native N-API binary and private libffi call @@ -71,9 +74,11 @@ codegen/ │ └── python/ └── com/ ├── ir.rs + ├── model/ ├── project/ - │ ├── types.rs - │ └── interop.rs + │ ├── interop.rs + │ ├── legacy_diagnostics.rs + │ └── legacy_types.rs └── javascript/ ├── types.rs └── render.rs @@ -82,8 +87,9 @@ codegen/ The Classic COM flow is: ```text -ComInterfaceMeta - -> COM type projection +raw Windows.Win32 facts + -> validated SemanticComInterface / ComMethodContract + -> COM language projection -> validated ComType / ProjectedComMethod -> JavaScript and declaration renderer ``` @@ -91,16 +97,33 @@ ComInterfaceMeta `ComType` is a closed set of supported ABI semantics: primitives, transparent scalar typedefs, pointer-sized scalars, BOOL/HRESULT, GUID, HSTRING, enums, explicitly classified handle/data/string pointers, BSTR, raw input pointers, -and managed interfaces with resolved IIDs. Parameter direction, return -convention, result ownership, cleanup, string-buffer relationships, -activation, and dynamic-IID behavior are encoded in the projected IR. - -Arrays, parameterized and async interfaces, delegates, unknown layouts, -unclassified pointer typedefs, unresolved IIDs, unknown allocators, and -unsupported ownership transfers fail during projection. The renderer cannot -see `TypeMeta` or metadata attributes and has no default pointer/Buffer -fallback; it only serializes the validated projected IR with exhaustive type -matches. +validated native POD values/pointers, explicitly tagged native-union pointers, +VARIANT pointer contracts, input-only VARIANT-by-value contracts, SAFEARRAY, +PROPVARIANT, and managed interfaces with resolved IIDs. +Typed counted buffers carry their validated element ABI and an explicit +input-count, caller-capacity/actual-length, or callee-allocation relation. +One authoritative element count may also group exactly one borrowed +NUL-terminated UTF-16/ANSI string-pointer input array with one caller-owned +plain scalar/enum output array. Generated JavaScript accepts `string[]`, hides +the count and output storage, and returns a numeric/enum array. +Parameter direction, return convention, result ownership, cleanup, buffer +relationships, activation, and dynamic-IID behavior are encoded in the +projected IR. +Production projection reads those decisions only from the validated semantic +contracts; the shared compatibility metadata supplies names, documentation, +and enum member values, not ABI meaning. +The legacy TypeMeta projector is retained only to reproduce established +unsupported-interface diagnostics and to build synthetic renderer fixtures; +successful production generation discards it entirely. + +General arrays outside that shared-count subset, parameterized and async +interfaces, delegates, unknown +layouts, unclassified pointer typedefs, unresolved IIDs, unknown allocators, +and unsupported ownership transfers fail during projection. Fixed primitive +arrays are accepted only as fields of a completely validated POD layout. The +renderer cannot see `TypeMeta` or metadata attributes and has no default +pointer/Buffer fallback; it only serializes the validated projected IR with +exhaustive type matches. ## Size of Windows.Win32.winmd @@ -239,8 +262,16 @@ There are 2,973 `NativeArrayInfo` parameters. The projection needs: - string termination and encoding; and - partial writes and failure cleanup. -Recognized UTF-16 output-buffer shapes are supported today. General writable -native arrays remain fail closed. +The supported subset includes primitive typed input buffers, caller-owned +outputs with exact capacity/actual-length relationships, byte-counted +`ISequentialStream::Read`/`Write`, exact bounded two-call sizing contracts, and +known-allocator callee outputs. A distinct exact `IEnum*::Next` plan supports +`IEnumGUID` and `IEnumConnectionPoints`: requested capacity and fetched count +remain separate, `S_FALSE` is successful partial completion, and generated +`next(count)` returns only the fetched GUIDs or managed interface wrappers. +Counts are never inferred from names or adjacency. Other owning +BSTR/interface/string-pointer elements and unknown allocators remain fail +closed. ### 4. Ownership and allocator contracts @@ -267,18 +298,31 @@ The ABI/projection needs explicit ownership such as: and nested ownership. Treating either as an opaque pointer is not a complete or safe projection. -Required support: - -- scalar and interface alternatives; -- BSTR and other owned strings; -- nested VARIANT values; -- SAFEARRAY and vector alternatives; -- `VariantInit`/`VariantClear` and `PropVariantClear`; -- language conversion and range checking; and -- DISPPARAMS argument order, named arguments, and EXCEPINFO. - -This unlocks `IDispatch`, XML Automation, Task Scheduler, `IPropertyStore`, and -many scripting/management APIs. +The implemented Automation subset now provides: + +- VARIANT empty/null, signed/unsigned integers, float/double, exact + `VARIANT_BOOL`, BSTR, IUnknown, IDispatch, and supported SAFEARRAY values; +- PROPVARIANT scalar numeric/bool values, LPWSTR, CLSID, FILETIME, blob, and + supported vectors; +- `VariantInit`/`VariantClear` and zero-init/`PropVariantClear`; +- distinct VARIANT pointer and input-only by-value ABI categories. By-value + calls use a call-local `VariantCopy`, pass the real aggregate through + libffi, and clear the copy on every exit path; required aggregates never + fabricate null or `VT_EMPTY`; +- dedicated `DISPPARAMS` input storage that deep-copies and reverses natural + arguments into stable contiguous `VARIANTARG` storage; +- dedicated `EXCEPINFO` output storage with exact BSTR cleanup and one-shot + deferred-fill handling; +- dedicated COM-only JavaScript wrappers and range-checked conversions; and +- fail-closed BYREF/InOut, unknown VARTYPE, and unsupported nested ownership. + +Complete inherited `IDispatch` now projects from real metadata. +`GetIDsOfNames` retains its natural shared-count array surface, and `Invoke` +takes `DynComDispatchParams` plus explicit LCID, flags, IID, and optional-output +request options. XML Automation, Task Scheduler, and `IPropertyStore` still +stop at their own unsupported BYREF/InOut, nested ownership, or `PROPERTYKEY` +contracts; support for `IDispatch` inheritance does not imply those derived +interfaces are complete. ### 6. SAFEARRAY @@ -286,8 +330,11 @@ many scripting/management APIs. array. It carries rank, bounds, element type, locks, ownership, and potentially non-blittable elements. -Required support includes multidimensional bounds, lower bounds, element -cleanup, interface/BSTR/VARIANT elements, and safe lock/unlock behavior. +The runtime supports ranks 1 through 8, signed/non-zero lower bounds, typed +scalar/VARIANT_BOOL/BSTR/IUnknown/IDispatch/VARIANT elements, overflow and +length validation, and exact element cleanup. It uses SafeArrayCreate, +SafeArrayCopy, SafeArrayGetVartype/dimension/bounds/element-size APIs, and +SafeArrayAccessData/UnaccessData; descriptor bytes are never reinterpreted. ### 7. Interface in/out and callback implementations @@ -342,7 +389,7 @@ conventions, `GetLastError`, callbacks, and handle cleanup. ### Recommended implementation order -1. General native struct/union layout. +1. Extend validated POD layout to unions, bitfields, and owned/non-POD fields. 2. Pointer-depth plus counted-buffer contracts. 3. Explicit allocator/ownership metadata. 4. VARIANT/PROPVARIANT and semantic HRESULT handling. @@ -363,37 +410,53 @@ not be described as solving every problem in the map above. | WinRT/Classic COM separation | Separate COM metadata/codegen path and `@microsoft/dynwinrt/com` public entrypoint. The WinRT generator and root runtime API remain unchanged. | | Interface root and vtable layout | Distinguishes `IUnknown` slot 3 from `IInspectable` slot 6 and walks inherited Classic COM interfaces before assigning slots. | | Method return conventions | Supports normal HRESULT methods, semantic HRESULT values marked with `CanReturnMultipleSuccessValuesAttribute`, native direct scalar, direct pointer at the runtime layer, and direct `void` returns. | -| Basic parameter direction | Supports input, output, and scalar in/out parameters without reducing in/out to out-only. | +| Basic parameter direction | Supports input, output, scalar in/out, and documented Automation BSTR replacement parameters without reducing in/out to out-only. | | Primitive ABI types | Signed/unsigned integers, floats, BOOL, HRESULT, GUID, enums, and `char16`. | | Pointer-sized values | `ISize`/`USize` select the correct x86/x64 ABI width and JavaScript uses `bigint`. | +| Validated native POD layout | Architecture-specific sequential layouts and authoritative non-overlapping explicit layouts support primitive, enum, GUID, pointer-sized, nested POD, and fixed primitive-array fields. Layout computation checks packing, alignment, bounds, overflow, overlap, and recursive cycles for x86, x64, and ARM64. JavaScript uses branded native-struct objects exposing a copied `.bytes` Buffer; qualified identity and exact size are checked before calls. | +| Native unions | Architecture-specific overlapping fields are validated at offset zero. Only scalar/GUID/pointer/nested POD struct fields are accepted. JavaScript uses branded `DynComNativeUnion` values whose constructor requires an explicit active field. Union pointer inputs are supported; by-value unions, outputs without a discriminant contract, nested unions, bitfields, flexible arrays, and nested owned fields fail closed. | +| VARIANT | Dedicated `DynComVariant` values support VT_EMPTY, VT_NULL, I1/UI1/I2/UI2/I4/UI4/I8/UI8/INT/UINT, R4/R8, exact VARIANT_BOOL, BSTR, UNKNOWN, DISPATCH, and supported `VT_ARRAY` values. Pointer-shaped input/output contracts retain their existing path. Required input-only `VARIANT`/`VARIANTARG` values may also lower by value: windows-rs establishes size/alignment 24/8 on x64 and 16/8 on i686, libffi receives an aggregate rather than a pointer, and a call-local `VariantCopy` protects shared storage and balances nested BSTR/interface ownership. Optional by-value metadata, output/InOut, BYREF, and unknown flags/tags fail before dispatch. | +| SAFEARRAY | Dedicated `DynComSafeArray` values support ranks 1–8, explicit signed lower bounds, typed scalar/bool/BSTR/interface/VARIANT elements, exact length/overflow/VARTYPE/element-width validation, lock/unlock, copy, and destruction. JavaScript preserves bounds rather than silently forcing zero-based arrays. | +| PROPVARIANT | Dedicated `DynComPropVariant` values support empty/null, scalar integer/float/bool, LPWSTR, CLSID, FILETIME, BLOB, and vectors of numeric/bool/string/GUID/FILETIME values. Storage is zero-initialized and cleared exactly once with `PropVariantClear`; nested VT_VECTOR\|VT_VARIANT and unknown combinations fail closed. | +| DISPPARAMS | Dedicated `DynComDispatchParams` owns deep-copied VARIANTARG values, reverses natural argument order for `IDispatch`, preserves named DISPIDs, and keeps descriptor/array pointers stable through the call. | +| EXCEPINFO | Dedicated output storage is zero-initialized, invokes `pfnDeferredFillIn` at most once, validates reserved fields, extracts source/description/help-file/context/scode, and frees every BSTR on all success and failure paths. | | GUID ABI | Full 16-byte GUID output storage plus GUID value and REFIID/REFGUID pointer patterns. | | Unsigned enum values | COM-local enum metadata preserves unsigned values, including 32-bit high-bit flags and 64-bit `bigint` literals. | | Standard COM references | `CoCreateInstance`, QueryInterface, and typed interface outputs carry an owned `+1` reference and release automatically. | | Ownership provenance | Borrowed numeric/TypedArray pointers cannot be re-adopted as a second COM owner. Native owned outputs are consumed once. | | Backing-storage lifetime | Buffer/TypedArray owners are retained and detached ArrayBuffers are rejected before native use. | -| Common string ownership | Scalar BSTR output uses `SysFreeString`; supported `PWSTR`/`PSTR` allocations use `CoTaskMemFree`. | +| Common string ownership | By-value BSTR input is a caller-owned call-local allocation borrowed by the callee; scalar BSTR output and final BSTR replacement results are caller-owned and use `SysFreeString`. Supported `PWSTR`/`PSTR` allocations use `CoTaskMemFree`. | | HSTRING ownership | Classic COM methods that explicitly use HSTRING project strings through owning HSTRING values; outputs release with `WindowsDeleteString`. | | External interface metadata | Interface parameters require a resolvable IID. Missing referenced metadata fails generation with a `--ref` diagnostic instead of degrading an owned interface to a raw pointer. | | WinRT runtime-class references | A resolved runtime class lowers through its default interface IID and remains a managed COM value. Missing defaults fail closed. | | Common interop pattern | Supports HWND + REFIID + `void**` bridges and adopts the returned interface reference. | -| Explicit COM initialization | Activation no longer silently chooses MTA; callers select STA or MTA with `DynCom.initialize()`. | -| Fail-closed generation | Unsupported structs, arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | +| Explicit COM initialization | Activation no longer silently chooses MTA; callers select STA or MTA with `initializeCom()`. Generated implementation files use the isolated unsafe runtime internally. | +| Fail-closed generation | Unknown/unsafe layouts, untagged/by-value/output unions, bitfields, flexible arrays, nested owned fields, unsupported VARTYPE/BYREF/SAFEARRAY/PROPVARIANT combinations, unsupported arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | | Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. Mixed and incremental generation preserve the WinRT-only root barrel; COM-only output retains its legacy root entrypoint. | | Explicit vtable registration | Every generated method is registered with `.addMethodAt(vtableIndex, name, signature)`, keyed by its actual metadata-derived vtable slot. Methods are never deduplicated by name, so same-name overloads at different slots both register correctly. | | Same-name overload projection | Overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) are grouped once during projection (not by renderer heuristics). A single public JS method dispatches to a private per-slot implementation using only a validated, mutually-distinguishable arity/shape key (`typeof`-based: boolean/number/bigint/string/object); ambiguous groups fail generation closed with a diagnostic naming the interface, method, and reason. The `.d.ts` emits one TypeScript overload signature per branch, contiguously. | -| Lifecycle ergonomics | Every generated class declares a private constructor (`private constructor(obj: unknown);`) and a public, idempotent `release()` that delegates to the managed native value. Generated `create()` JSDoc reminds callers that `DynCom.initialize()` must run first. | +| Lifecycle ergonomics | Generated interface wrappers declare a protected constructor (`protected constructor(obj: unknown);`) so only generated coclasses can subclass them. Coclasses expose a public zero-argument constructor, and every wrapper provides an idempotent `release()` that delegates to the managed native value. Factory-activated interop wrappers retain `static create()` with JSDoc reminding callers to initialize COM first. | | Doc-link rendering | When win32metadata attaches a `DocumentationAttribute` (a `learn.microsoft.com` URL) to a method, the generator renders it as an `@see {@link ...}` comment in both `.js` and `.d.ts`. No raw metadata is imported into the renderer — the URL is threaded through `ProjectedComMethod.doc`, populated once during projection. | | Acronym-aware parameter casing | Parameter names are lowered using the same acronym-run-aware rule as method names, so a Hungarian-prefixed trailing acronym like `hwndMDI` projects as `mdi` (not the previous naive `mDI`). | | Wide/ANSI string pointer split | `PointerAliasKind::StringPointer` now carries a `StringEncoding` (`Wide`/`Ansi`). Generated wrappers call the semantically distinct `DynCom.wideStringPointer(value)` / `DynCom.ansiStringPointer(value)` constructors instead of one unqualified pointer helper; the renderer never infers encoding — it only renders the encoding decision already made during projection. | -| Output ownership provenance | Signature expressions for pointer-shaped `[out]` values are chosen from `ProjectedComResult` ownership/conversion facts, not from type names: `DynCom.ownedComPointerType()` for dynamic-IID `+1` COM outputs, `DynCom.coTaskMemPointerType()` for `CoTaskMem` `PWSTR`/`PSTR` outputs, `DynCom.bstrPointerType()` for BSTR outputs, and plain `pointerType()` (never consumable as an owned value) for everything unclassified/borrowed. | +| Output ownership provenance | Signature expressions for pointer-shaped `[out]` values are chosen from `ProjectedComResult` ownership/conversion facts, not from type names: `DynCom.ownedComPointerType()` for dynamic-IID `+1` COM outputs, `DynCom.coTaskMemPointerType()` for `CoTaskMem` `PWSTR`/`PSTR` outputs, dedicated `DynCom.bstrType()` for BSTR outputs/replacements, and plain `pointerType()` (never consumable as an owned value) for everything unclassified/borrowed. | | Invocation validation | The completed native-call plan validates the exact argument count and ABI-compatible value shape before selecting a direct or libffi path. Native pointers reject scalar/object values, mismatched widths fail before dispatch, and established WinRT JS aliases (`I32` projected as `i8`/`u8`/`char16`) are range-checked and converted to exact ABI storage. | -| Failure-path cleanup | Each output parameter carries an explicit cleanup plan. If a callee writes an owned value and then returns a failing HRESULT, interface references are released, HSTRING/BSTR values are deleted with their matching APIs, and CoTaskMem outputs are freed on both direct and libffi paths. Unconsumed successful outputs retain the same allocator-specific ownership until converted, adopted, released, or garbage-collected. | -| Authoritative count-param detection | String-buffer/count relationships are read solely from the metadata's own `NativeArrayInfo(CountParamIndex)`. The previous `pfd`/`finddata` substring/adjacency heuristic has been removed entirely; unsupported writable native arrays fail closed instead of guessing a direction from parameter names. | +| Failure-path cleanup | Each output parameter carries an explicit cleanup plan. If a callee writes an owned value and then returns a failing HRESULT, interface references are released, HSTRING/BSTR values are deleted with their matching APIs, and CoTaskMem outputs are freed on both direct and libffi paths. BSTR InOut uses one boxed call-local slot, so unchanged, replaced, and nulled values remain safely cleanable on success and failure without exposing shared storage. Unconsumed successful outputs retain the same allocator-specific ownership until converted, adopted, released, or garbage-collected. | +| Typed counted buffers | COM-local plans support `[in] T* + count`, caller-owned `T* + capacity`, separate or in/out actual lengths, bounded exact two-call sizing, and known-allocator `T** + count` output. Generated JavaScript derives hidden ABI counts, accepts `Buffer`/TypedArray storage, and returns only initialized bytes. | +| Exact fixed-capacity byte output | `IMFAttributes::GetBlob` is registered by declaring IID, qualified interface, slot, and complete parameter/return signature. Generated `getBlob(guidKey, capacity)` allocates exclusive zeroed runtime storage, hides `pBuf`/`cbBufSize`/`pcbBlobSize`, bounds the allocation, and returns only the successful actual byte range. | +| Enumerator partial arrays | Exact IID/name/slot/type registries validate standard `IEnum*::Next(ULONG, T*, ULONG*)`. Runtime storage is exclusive, aligned, stable, bounded, and zeroed. `fetched > capacity` is rejected without an out-of-bounds read. Interface slots transfer each fetched `+1` reference once; failed HRESULTs, conversion errors, overflow, and unused initialized capacity release every remaining non-null slot. Exact canonical IUnknown elements use `DynWinRtValue[]` directly without generating an `IUnknown.js` wrapper. Generated `next(count: number): T[]` rejects zero, fractions, and values above `u32::MAX`; `pceltFetched` is hidden and omitted only where exact metadata permits it for `count == 1`. | +| Exact borrowed HWND outputs | Twenty-two Microsoft-documented declarations are registered by namespace, interface IID, method, slot, parameter count/index/name, and full native shape. Runtime storage is zeroed and pointer-sized, successful null is `0n`, and neither success nor failure calls `Release`, `DestroyWindow`, or another cleanup routine. | +| Shared caller-sized arrays | One authoritative input count may group a borrowed NUL-terminated string-pointer input array with one caller-owned plain scalar/enum output array. Runtime-owned encoded strings and pointer tables remain stable through dispatch; aligned output storage is zeroed, count agreement is checked before dispatch, and failed HRESULTs return no array. | +| Buffer backing safety | Node backing storage is retained and revalidated before invocation. Detached, moved, resized, width-mismatched, non-integral-length, or misaligned storage is rejected; caller output storage is zeroed before the call. Failed HRESULTs never return a partial success-shaped buffer result. | +| Failure-time stream progress | `ISequentialStream` may write a partial count before returning failure. The runtime cleans initialized owned elements exactly, but generated wrappers throw and deliberately discard failure-time partial data rather than returning a success-shaped buffer. | +| Authoritative count-param detection | Relationships come solely from `NativeArrayInfo(CountParamIndex)` or an exact cited override registry. Documented overrides cover `ISequentialStream::Read`/`Write`, `IDiscRecorder::GetRecorderGUID`, `IOpcSignatureCustomObject::GetXml`, and the fixed-capacity/actual-byte `IMFAttributes::GetBlob` contract. The previous substring/adjacency heuristic remains removed. | +| Private-data ownership guard | Actual metadata contains seven declaring `GetPrivateData(REFGUID, UINT*, void*)` interfaces. Their documentation permits returning an AddRef'd interface set by `SetPrivateDataInterface`; Direct3D 10 also documents destructive NULL behavior, and DXGI does not mark the data pointer optional. They remain exact, cited fail-closed hazards rather than being projected as leaking `Buffer` methods. | | Atomic multi-interface writes | When a single `generate` invocation projects several COM interfaces, every interface is projected into memory first; files (and the `com/` index/package barrel) are only written once the whole batch has projected successfully. A later interface's projection failure no longer leaves an earlier interface's files partially written to disk. | | Coclass projection | GUID-bearing Classic COM coclasses such as `TaskbarList`, `FileOperation`, and `FileOpenDialog` generate as independently constructible JS classes (`new TaskbarList()`). Interface wrappers remain non-publicly constructible and expose an IID descriptor plus `_fromNative` for runtime QueryInterface views. | | Interface views | Generated coclasses expose `as(InterfaceClass)`, `tryAs(InterfaceClass)`, and `supports(InterfaceClass)`. These execute real QueryInterface calls; `tryAs` returns `null` only for `E_NOINTERFACE`, while other errors remain visible. | | Conservative primary interface | Windows.Win32 coclass TypeDefs do not carry `InterfaceImpl`/`DefaultAttribute` rows. The generator associates only exact metadata naming candidates, constructs the real interface inheritance graph, and selects a primary only when there is one unique most-derived leaf. Multiple unrelated leaves fail closed rather than choosing by numeric suffix. | | CommonJS and ESM | COM implementation files use the same CommonJS format as generated WinRT files. `com/index.js` is the CommonJS barrel, while `com/index.mjs` is the ESM facade. Package exports provide explicit `require` and `import` conditions for the COM barrel and deep imports. | +| Explicit raw opt-in | Manual ABI declarations and caller-supplied COM pointers are isolated under `@microsoft/dynwinrt/com/unsafe`. The default COM facade exports only initialization and managed value/layout wrappers—not `DynCom`, signatures, interfaces, native types, or `DynComUnsafe`; generated safe bindings continue to fail closed. | ### Generated package layout @@ -451,14 +514,64 @@ used `#winapp/bindings/InterfaceName` for COM should switch to the `com/` path. Standalone COM-only packages continue to expose their legacy package-name deep imports. +### Explicit unsafe/raw opt-in + +APIs that cannot be proven from metadata remain absent from generated safe +bindings. A caller that independently knows the complete native contract may +opt in through the separate `@microsoft/dynwinrt/com/unsafe` entrypoint: + +```js +import { + DynCom, + DynComMethodSig, + DynComUnsafe, + WinGuid, +} from '@microsoft/dynwinrt/com/unsafe'; + +const iid = WinGuid.parse('00000000-0000-0000-c000-000000000046'); +const raw = DynComUnsafe.registerIUnknownInterface('Example.IRaw', iid) + .addMethodAt( + 3, + 'ReadPointer', + new DynComMethodSig() + .addIn(DynCom.u32Type()) + .addOut(DynComUnsafe.coTaskMemOutputType()), + ); +``` + +The signature must explicitly declare every ABI type, direction, vtable slot, +count/capacity/actual relationship, return convention, and output cleanup; +the runtime applies the architecture-correct COM system calling convention. +Available raw output choices deliberately distinguish unclassified borrowed +pointer bits, borrowed handles, `Release`-owned COM pointers, +`CoTaskMemFree` allocations, and `SysFreeString` BSTRs. An unclassified +pointer output is never automatically adopted. + +`DynComUnsafe.borrowComPointer(bits, iid)` treats the supplied pointer as +borrowed and obtains a new managed `+1` reference through `QueryInterface`. +`DynComUnsafe.adoptOwnedComPointer(bits, iid)` instead consumes exactly one +caller-supplied `+1` reference, including on IID-validation failure. Both +accept only explicit numeric pointer bits; Buffer backing addresses are +rejected to avoid contents-versus-address ambiguity. + +This surface is intentionally unsafe: an invalid pointer, IID, slot, calling +convention, layout, direction, count relation, or ownership declaration can +crash the process or corrupt memory. It does not add inference or a fallback +to the default generator, and it remains outside both `@microsoft/dynwinrt` +and `@microsoft/dynwinrt/com`. + ### Partially implemented | Problem family | Supported subset | Remaining gap | |---|---|---| -| Native pointers | Pointer width, depth preservation, borrowed pointers, handles, REFIID, and known interface outputs | General nullable/required semantics, arbitrary pointee storage, and all allocator contracts | -| Counted buffers | Recognized caller-owned UTF-16 output buffers and input Buffer pointers | General byte/element output arrays, two-call sizing, actual-length returns, ANSI output decoding | -| Native layout | Primitives, GUID, enum, handle-shaped typedefs, and manually described runtime structs | General metadata-driven struct/union/packing/bitfield layout | -| Allocator ownership | COM Release, BSTR, CoTaskMem, boxed GUID, retained JS buffers | LocalFree, custom allocators, allocator interfaces, unknown ownership | +| Native pointers | Pointer width, depth preservation, borrowed pointers, handles, REFIID, known interface outputs, and 22 exact documented borrowed `HWND*` outputs | General nullable/required semantics, arbitrary pointee storage, unregistered HWND outputs, and all allocator contracts | +| Counted buffers | Plain primitive/GUID/enum/POD elements plus exact owning COM-interface, BSTR, VARIANT, and `IEnumString` PWSTR elements with authoritative relations; input, caller output, actual/fetched length, generated fixed-capacity bytes, exact bounded two-call sizing, and exact CoTaskMem callee output | PROPVARIANT/SAFEARRAY/unknown pointer/resource elements, nested-owning POD, owning callee-allocated outer arrays without exact allocators, undocumented sizing loops, and ANSI output decoding | +| Native layout | Metadata-driven POD structs plus tagged pointer-input unions with exact x86/x64/ARM64 layout; union fields overlap at offset zero and may contain only safe POD fields | By-value/output/nested unions without discriminant contracts, non-default or unknown packing, bitfields, flexible arrays, non-authoritative explicit offsets, and nested BSTR/interface/resource ownership | +| VARIANT | Empty/null, scalar integer/float/bool, BSTR, UNKNOWN, DISPATCH, supported SAFEARRAY values, and authoritative counted input/output arrays with exact `VariantCopy`/`VariantClear` ownership | Optional aggregate defaults, bare aggregate output/InOut, BYREF, DECIMAL/DATE/CY/ERROR/RECORD and other VARTYPEs, Automation replacement, and arrays without exact count/ownership contracts | +| DISPPARAMS / EXCEPINFO | Exact `IDispatch::Invoke` input/output contracts, dedicated JS wrappers, optional null outputs, deferred fill, and failure cleanup | Output/InOut DISPPARAMS, input/InOut EXCEPINFO, nested occurrences, and arbitrary deferred/function-pointer contracts | +| SAFEARRAY | Rank 1–8, signed bounds, typed scalar/bool/BSTR/interface/VARIANT elements, SafeArray API validation and cleanup | Unsupported element VARTYPEs, rank > 8, untyped arrays whose VARTYPE cannot be proven, and Automation InOut replacement | +| PROPVARIANT | Scalar numeric/bool, LPWSTR, CLSID, FILETIME, blob, and supported vectors with PropVariantClear | Nested VARIANT vectors, streams/interfaces, arrays, clipboard/storage types, BYREF, and unknown VARTYPEs | +| Allocator ownership | COM Release, BSTR output/replacement and array elements, VARIANT clear, CoTaskMem buffers/PWSTR elements, boxed GUID, retained JS buffers | LocalFree, custom allocators, allocator interfaces, unknown ownership | | Interface pointers | Typed input/output interfaces, QueryInterface, dynamic IID output | Interface in/out replacement and arbitrary implemented sink interfaces | | Apartments | Explicit initialization and same-thread invocation | Cross-apartment marshaling, GIT/agility handling, callback dispatch | | Activation | In-process `CoCreateInstance` | `CoGetClassObject`, aggregation, arbitrary CLSCTX, and non-CoCreate factory functions | @@ -466,10 +579,15 @@ package-name deep imports. ### Not implemented -- general struct/union native layout; -- VARIANT, VARIANTARG, DISPPARAMS, and EXCEPINFO; -- PROPVARIANT and the Property System value model; -- SAFEARRAY; +- by-value/output/nested unions without an explicit discriminant and ownership contract; +- optional or output/InOut aggregate VARIANT, unsupported VARIANT alternatives, + BYREF/InOut replacement, and arrays without authoritative count/ownership; +- DISPPARAMS/EXCEPINFO directions, nesting, or callback shapes outside the + exact supported `IDispatch::Invoke` contract; +- unsupported PROPVARIANT alternatives and nested ownership; +- unsupported SAFEARRAY element types/ranks and InOut replacement; +- BSTR pointer nesting, scalar input `BSTR*`, callee-allocated outer arrays + without exact allocators, and unknown/custom BSTR allocation contracts; - FORMATETC and STGMEDIUM; - arbitrary COM event/callback sink generation; - cross-thread/apartment marshaling; and @@ -485,31 +603,45 @@ package-name deep imports. | Native `void` returns | Supported | Used by interfaces such as `IMalloc`. | | Direct scalar returns | Supported | Includes signed/unsigned integers, floating point values, and enums. | | Direct pointer returns | Runtime supported; codegen partial | The runtime can describe a pointer return explicitly. Metadata codegen currently fails closed for interfaces such as `IMalloc` because it does not preserve the raw-pointer return kind. | -| `[in]`, `[out]`, and scalar `[in, out]` parameters | Supported | Unsupported composite in/out types fail generation. | +| `[in]`, `[out]`, and `[in, out]` parameters | Supported for modeled types | Scalars and validated native POD storage are supported. Other composite in/out types fail generation. | | Primitive integer and floating-point types | Supported | `i8` through `u64`, `f32`, `f64`, `BOOL`, and `HRESULT`. | | `ISize` / `USize` | Supported | Projected with the target pointer width; verified by an i686 compile check. | | GUID values and `REFIID`/`REFGUID` pointers | Supported | GUID out storage uses the full 16-byte layout. | | Signed and unsigned enums/flags | Supported | Values up to unsigned 64-bit are preserved; 64-bit JavaScript values use `bigint`. | +| Validated native POD structs | Supported subset | Exact x86/x64/ARM64 layouts; primitive, enum, GUID, pointer-sized, nested POD, and fixed primitive-array fields; by-value, pointer input, output, and in/out calls. Generated values are branded `DynComNativeStruct` objects, and output storage is zero-initialized. | +| Validated native unions | Supported subset | Pointer inputs only, with exact architecture layout and an explicit active-field-branded `DynComNativeUnion`. Output/by-value/nested ownership shapes fail closed. | +| VARIANT | Supported subset | Dedicated `DynComVariant`; supported tags are VT_EMPTY, VT_NULL, I1/UI1/I2/UI2/I4/UI4/I8/UI8/INT/UINT, R4/R8, BOOL, BSTR, UNKNOWN, DISPATCH, and arrays of supported SAFEARRAY elements. Pointer contracts remain distinct from required input-only by-value aggregates. | +| SAFEARRAY | Supported subset | `DynComSafeArray` preserves rank/bounds and validates VARTYPE and element width through SafeArray APIs. Supported elements are the scalar integer/float family, VARIANT_BOOL, BSTR, IUnknown, IDispatch, and VARIANT. | +| PROPVARIANT | Supported subset | `DynComPropVariant` supports the scalar family, LPWSTR, CLSID, FILETIME, BLOB, and vectors of numeric/bool/string/GUID/FILETIME elements. | +| DISPPARAMS / EXCEPINFO | Supported for `IDispatch::Invoke` | `DynComDispatchParams` accepts natural-order `DynComVariant[]` plus optional named DISPIDs. `DynComExcepInfo` exposes code/source/description/helpFile/helpContext/scode. Optional Invoke outputs pass native null when not requested. | | Typed interface parameters and outputs | Supported | Interface outputs carry an owned COM reference. | | Opaque pointers and handle-shaped typedefs | Supported with limits | They are pointer values, not COM objects. Cleanup remains type-specific. | +| Borrowed HWND outputs | Supported only for exact registered declarations | Qualified `HWND* Out` metadata and Microsoft lifetime evidence must match exactly. JavaScript returns the natural numeric handle alias; runtime output storage is pointer-sized and has no cleanup. | | NUL-terminated string pointer inputs | Supported | Callers pass a NUL-terminated `Buffer` or a borrowed numeric pointer. | | Caller-owned UTF-16 output buffers | Supported for recognized shapes | The generator allocates and decodes the buffer when metadata identifies the count parameter. | +| Typed counted input buffers | Supported for validated plain elements | Generated wrappers accept `Buffer` or TypedArray storage and derive byte/element counts from its exact backing length. | +| Caller-owned typed output buffers | Supported for validated plain elements | Capacity is derived from supplied backing storage; separate or in/out actual lengths trim the returned `Buffer` to the initialized range. | +| Generated fixed-capacity byte output | Supported only for registered documented shapes | `IMFAttributes::GetBlob(guidKey, capacity)` allocates exclusive storage in the runtime; capacity is bounded to the projected Buffer limit and native counts remain hidden. | +| Exact two-call sizing | Supported only for registered documented shapes | Generated wrappers start with the documented null/zero query and retry at most twice. Continued size races fail explicitly. | +| Callee-allocated typed buffers | Supported for plain elements with known CoTaskMem ownership | The runtime copies the exact count, calls `CoTaskMemFree` once, and returns an owned Node `Buffer`. | | Callee-allocated `PWSTR` / `PSTR` outputs | Supported | Generated code decodes and frees `CoTaskMem` storage. | +| By-value `[in] BSTR` | Supported | Generated JavaScript accepts `string` (or `null` only for metadata-proven optional input). The runtime creates a uniquely owned call-local `SysAllocStringLen` allocation, preserving embedded NUL and exact UTF-16 length; the callee only borrows it. | | Scalar `[out] BSTR*` | Supported | Generated code converts the BSTR and releases it with `SysFreeString`. | +| Required scalar `[in, out] BSTR*` replacement | Supported | Generated JavaScript accepts and returns `string`. A boxed call-local slot owns the current BSTR; the original JavaScript string is immutable, and the final unchanged/replaced/null slot is cleaned or transferred exactly once on every HRESULT path. | +| Counted BSTR arrays | Supported subset | Exact input and caller-output count/capacity/actual contracts project as `string[]`; call-local input elements and every initialized output slot use `SysFreeString` exactly once. Callee-allocated outer arrays, unsupported pointer nesting, and unknown allocators fail closed. | | HSTRING inputs and scalar outputs | Supported | JavaScript strings are converted to owning HSTRING values; returned HSTRING values are decoded and released automatically. | | Referenced interface types | Supported when IID metadata is loaded | Missing external definitions fail closed and direct callers to pass the defining winmd with `--ref`. | -| Dynamic-IID `void**` outputs | Supported for explicit REFIID shapes | The IID argument must be a pointer-shaped `iid`/`riid` parameter. A GUID passed by value is not REFIID and cannot trigger interface adoption. | -| Explicit apartment initialization | Supported | `DynCom.initialize()` never silently chooses an apartment for the caller. | +| Dynamic-IID `void**` outputs | Supported for explicit required REFIID shapes | The method must return ordinary HRESULT and contain exactly one required const `GUID*` named `iid`/`riid` plus one required mutable `void**`/Object** output with +1 COM ownership. Their explicit parameter indices may be non-adjacent/non-terminal. Optional, duplicate, array, FreeWith, InOut, by-value/mutable/deeper GUID, and wrong-depth output shapes fail closed. | +| Explicit apartment initialization | Supported | `initializeCom()` never silently chooses an apartment for the caller. | -The runtime can manually describe some ABI shapes that the generator rejects. -For example, a carefully defined native struct can be called from Rust, but the -generator does not emit a struct until its native layout is known to be -correct. +The generator emits native POD storage only after every architecture-specific +layout fact has been validated. A `Buffer` in this path represents the struct's +backing bytes/address; it is not interpreted as pointer-width handle bits. -Parameterized and async interfaces, delegates, and native arrays remain -fail-closed until the COM projection can compute their complete IID, callback, -count, and element-ownership contracts. They must never fall back to -`bigint | Buffer`. +Parameterized and async interfaces, delegates, and native arrays outside the +explicit count and element-ownership models remain fail-closed until the COM +projection can compute their complete IID, callback, count, and ownership +contracts. They must never fall back to `bigint | Buffer`. ## Unsupported types and shapes @@ -524,27 +656,529 @@ of every type in the 24 MB metadata file. | Type or shape | Affected common APIs | Why it is unsupported | Basis | |---|---|---|---| -| `VARIANT` / `VARIANTARG` | `IDispatch::Invoke`, Automation APIs | Requires a discriminated union with ownership rules for BSTR, interfaces, arrays, decimals, and nested values. | Win32 winmd signature | -| `DISPPARAMS` / `EXCEPINFO` | `IDispatch::Invoke` | Contains VARIANT arrays, BSTR fields, and nested pointer ownership. | Win32 winmd signature | -| `PROPVARIANT` | `IPropertyStore`, Windows Property System | Larger discriminated union with vector, string, stream, and interface ownership. | Win32 winmd signature | -| `PROPERTYKEY` and arbitrary native structs | `IPropertyStore::GetAt` | Native struct layout, alignment, and architecture must be modeled explicitly. | Win32 winmd + codegen diagnostic | -| `SAFEARRAY` | Automation and Office-style COM APIs | Requires rank, bounds, element type, locking, and element cleanup semantics. | Win32 winmd Automation signatures | +| Unsupported `VARIANT` alternatives, aggregate directions, and BYREF/InOut | Automation APIs | Required input-only by-value VARIANT is supported. Optional aggregate defaults, bare aggregate output/InOut, DATE, DECIMAL, CY, ERROR, RECORD, unsupported flags, and every BYREF/InOut combination fail closed until their lifetime/replacement contracts are proven. | Runtime validation + Win32 winmd signatures | +| Unsupported `DISPPARAMS` / `EXCEPINFO` shapes | Automation APIs outside exact `IDispatch::Invoke` | Output/InOut DISPPARAMS, input/InOut EXCEPINFO, nested compounds, reinstalled deferred callbacks, and unrelated function-pointer contracts fail closed. | Runtime validation + Win32 winmd signature | +| Unsupported `PROPVARIANT` alternatives | Property System | Streams/interfaces, arrays, clipboard/storage alternatives, nested VT_VECTOR\|VT_VARIANT, BYREF, and unknown combinations are rejected. | Runtime validation + Win32 winmd signature | +| `PROPERTYKEY` and native structs outside the POD subset | `IPropertyStore::GetAt` | Every architecture-specific layout and nested field contract must reach the validated POD model; full `IPropertyStore` still fails closed before a complete interface can be emitted even though scalar PROPVARIANT storage is implemented. | Win32 winmd + codegen diagnostic | +| Unsupported `SAFEARRAY` shapes | Automation and Office-style COM APIs | Exact declaration-registry entries support documented `VT_I4`, `VT_UI1`, `VT_UI4`, `VT_R8`, `VT_BSTR`, `VT_VARIANT`, and `VT_UNKNOWN` plus an exact interface IID. Unknown VARTYPE, signature drift, input `SAFEARRAY**`, InOut replacement, unsupported records/dispatch contracts, rank > 8, inconsistent bounds/length/element width, and unproven nullable outputs are rejected. | Exact Microsoft citations + SafeArray API validation + Win32 winmd signatures | | `FORMATETC` / `STGMEDIUM` | `IDataObject`, clipboard, drag-and-drop | `STGMEDIUM` is a union of handles and interfaces with type-specific release behavior. | Win32 winmd + codegen diagnostic | -| Arbitrary unions, bitfields, and nested pointer-rich structs | `D3D11_COUNTER_INFO`, `STATSTG`, `STRRET`, `POINTL`, `BIND_OPTS`, audio/media formats | The current generator has no general native C layout engine. | Win32 winmd + codegen diagnostics | -| `WIN32_FIND_DATAA`/`WIN32_FIND_DATAW` writable out-params | `IShellLinkW::GetPath` (`pfd`) | Multi-field struct with no recognized native layout; there is no safe way to size or write into it from the caller side. Generation fails closed for the whole interface. The COM E2E suite therefore exercises `IPersistFile` through direct Shell Link activation instead of generating `IShellLinkW`. | Win32 winmd + codegen diagnostic | -| Writable caller-sized native arrays | `IDispatch::GetIDsOfNames`, counted byte/element output buffers | A scalar pointee is not sufficient storage. These are rejected unless a supported string-buffer projection applies. | Win32 winmd `NativeArrayInfo` + codegen diagnostic | -| `BSTR**` arrays and BSTR in/out arrays | Automation collection APIs | Each element has independent allocation and release semantics. | Win32 winmd signature + ownership analysis | +| Untagged/by-value/output/nested unions, bitfields, flexible arrays, and nested owned-resource structs | `STGMEDIUM`, `STRRET`, `BINDPTR`, audio/media formats | Tagged pointer-input unions support only safely POD fields. Missing discriminants, nested unions, BSTR/interfaces/resources, bitfields, and flexible tails fail closed. | Win32 winmd + codegen diagnostics | +| Unknown packing or non-authoritative explicit offsets | Explicit/packed native records | Exact x86/x64/ARM64 size, alignment, and field offsets are mandatory. Missing facts fail closed rather than assuming the host compiler's defaults. | Layout validation policy | +| Writable caller-sized native arrays outside the modeled subset | Owning, pointer-element, native-POD, or incompletely described arrays | `IDispatch::GetIDsOfNames` is supported in the complete interface when one metadata count unambiguously groups borrowed string pointers with plain scalar output. Missing count direction, element layout/ownership, or an unambiguous group still fails closed. | Win32 winmd `NativeArrayInfo` + semantic validation | +| Unsupported BSTR pointer nesting, replacement arrays, or callee-allocated outer arrays | Automation collection APIs | Exact counted input/caller-output BSTR arrays are supported; deeper/replacement shapes still require authoritative outer allocation and per-element contracts. | Win32 winmd signature + ownership analysis | | Caller-owned ANSI output buffers | `PSTR` output-buffer APIs | Safe sizing and decoding are not yet projected. | Win32 winmd signature + projection limitation | -| Untyped output pointers without allocator/ownership | `IDXGIFactory::GetPrivateData`, `IAudioClient::IsFormatSupported` | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. | Win32 winmd + codegen diagnostics | +| Private-data bytes or interface pointer | `IDXGIObject`, `ID3D10DeviceChild`, `ID3D10Device`, `ID3D11DeviceChild`, `ID3D11Device`, `ID3D12Object`, and `IDMLObject` `GetPrivateData` | The same GUID-keyed method may return ordinary bytes or an AddRef'd interface pointer. A `Buffer` projection would lose the interface ownership transfer; Direct3D 10 NULL calls are destructive, and DXGI's data parameter is required. | Exact Win32 winmd identities + Microsoft method documentation | +| Untyped output pointers without allocator/ownership | `IAudioClient::IsFormatSupported` and unrelated `void*` outputs | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. | Win32 winmd + codegen diagnostics | | Interface `[in, out]` ownership | `IWbemServices::OpenNamespace` | Replacing an existing interface pointer requires explicit release/AddRef transfer semantics. | Win32 winmd + codegen diagnostic | | Arbitrary COM sink/interface implementation | Connection points and event sinks | `Advise` requires implementing a caller-defined COM interface, not only invoking one. | Runtime/public-API boundary | | COM aggregation | `IClassFactory::CreateInstance` with `pUnkOuter` | The public activation helper always creates a non-aggregated in-process object. | Runtime/public-API boundary | -| General out-of-process activation controls | Custom `CLSCTX` scenarios | `DynCom.coCreateInstance()` currently uses `CLSCTX_INPROC_SERVER`. | Runtime/public-API boundary | +| General out-of-process activation controls | Custom `CLSCTX` scenarios | The unsafe runtime's `DynCom.coCreateInstance()` currently uses `CLSCTX_INPROC_SERVER`. | Runtime/public-API boundary | | Flat Win32 DLL exports | `CreateFile`, registry functions, GDI, etc. | These are not COM interfaces and need a separate DLL-export/handle model. | Architecture boundary | -Consequently, `IDispatch`, `IPropertyStore`, and `IDataObject` are important -and widely encountered interfaces, but they are not currently supported as -complete generated bindings. +Consequently, `IPropertyStore` and `IDataObject` remain important, +widely encountered interfaces that are not currently supported as complete +generated bindings. `IDispatch` itself is complete; derived Automation +interfaces still validate all of their additional methods independently. + +## Complete-interface census after by-value VARIANT + +A temporary full census against +`Microsoft.Windows.SDK.Win32Metadata` **71.0.14-preview** parsed 7,944 +interfaces. The temporary census code and generated output are not retained in +the repository. + +| Result | Before | After | Delta | +|---|---:|---:|---:| +| Complete interfaces | 4,773 | 5,188 | **+415** | +| Incomplete interfaces | 3,171 | 2,756 | **-415** | + +All 415 interfaces whose first blocker was a bare required input VARIANT +became complete; no previously complete interface regressed. The remaining +first-blocker categories are: + +| Category | Interfaces | +|---|---:| +| Ownership/cleanup | 1,113 | +| Arrays/buffers | 666 | +| Native layout | 437 | +| Other validated contracts | 252 | +| SAFEARRAY | 146 | +| Pointer semantics | 142 | + +The largest exact first blockers are the cited `GetPrivateData` ownership +hazards: `ID3D12Object` (82), `ID3D11DeviceChild` (58), `IDXGIObject` (39), +and `ID3D10DeviceChild` (24), followed by PROPVARIANT InOut `GetItem` +contracts (19). + +Automation remains intentionally partial. Across incomplete interfaces, 143 +first fail on an unsupported SAFEARRAY element and 54 first fail on +VARIANT/PROPVARIANT/SAFEARRAY BYREF/InOut replacement. Eleven first fail on a +bare VARIANT aggregate in a non-input direction, twelve on the analogous +PROPVARIANT shape, and `IEnumVARIANT::Next` remains one caller-sized VARIANT +array blocker. Existing supported pointer-shaped VARIANT inputs and owned +outputs are unchanged. + +Real metadata regressions lock two representative APIs: + +```ts +IAccessible.accSelect(flagsSelect: number, varChild: DynComVariant): void; +IUIAutomation.createPropertyCondition( + propertyId: UIA_PROPERTY_ID, + value: DynComVariant +): DynWinRtValue; +``` + +`IAccessible` (IID `618736e0-3c3d-11cf-810c-00aa00389b71`) now generates +completely, including `accSelect` at slot 21. +`IUIAutomation::CreatePropertyCondition` (IID +`30cbe57d-d9d0-452a-ab13-7ac5ac4825ee`) projects in isolation at slot 23; +the complete interface now passes its exact runtime-ID SAFEARRAY methods and +stops later at `ElementFromPoint.pt` because `POINT` has not reached the +validated native-layout projection. + +## Complete-interface census after safe dynamic-IID generalization + +The same temporary census against +`Microsoft.Windows.SDK.Win32Metadata` **71.0.14-preview** parsed 7,944 +interfaces. The temporary census code and generated output are not retained. + +| Result | Staged baseline | Generalized | Net delta | +|---|---:|---:|---:| +| Complete interfaces | 5,188 | 5,200 | **+12** | +| Incomplete interfaces | 2,756 | 2,744 | **-12** | + +Thirteen interfaces became complete because a required `iid`/`riid` and its +owned `void**` result may now be non-adjacent or non-terminal: + +`IDCompositionSurface`, `IDCompositionTexture`, `IXpsDocumentConsumer`, +`IAMGraphStreams`, `IPSFactoryBuffer`, `IClassFactory2`, +`IRemoteSystemAdditionalInfoProvider`, `ISearchLanguageSupport`, +`ICompositionDrawingSurfaceInterop`, `ICompositionDrawingSurfaceInterop2`, +`ICompositionTextureInterop`, `ISurfaceImageSourceNativeWithD2D`, and +`ICustomDestinationList`. + +`INetCfg` intentionally moved from complete to incomplete: +`QueryNetCfgClass.ppvObject` is optional in metadata, so it no longer receives +owned-COM adoption. No required-output interface regressed. + +The remaining first-blocker categories are: + +| Category | Interfaces | +|---|---:| +| Ownership/cleanup | 1,101 | +| Arrays/buffers | 666 | +| Native layout | 436 | +| Other validated contracts | 253 | +| SAFEARRAY | 146 | +| Pointer semantics | 142 | + +The top exact blockers remain the cited `GetPrivateData` ownership hazards: +`ID3D12Object` (82), `ID3D11DeviceChild` (58), `IDXGIObject` (39), and +`ID3D10DeviceChild` (24), followed by PROPVARIANT InOut `GetItem` contracts +(19). + +Forty-three interfaces (67 methods) now contain an ambiguous +dynamic-IID-like shape: +31 contain InOut/interface-array contracts, nine use optional `void**` +outputs, two combine the otherwise valid pair with hidden counted buffers, +and one (`IEnumObjects::Next`) marks the interface output with +`NativeArrayInfo`. `IDxcResult::GetOutput`, +`IDirectManipulationViewport2::GetTag`, and +`INetCfg::QueryNetCfgClass` are representative optional-output blockers; +`IMFTopologyServiceLookup::LookupService` remains blocked by its InOut +multi-interface count. + +## Complete-interface census after BSTR normalization and replacement + +The executable BSTR census used +`Microsoft.Windows.SDK.Win32Metadata` **71.0.14-preview** and selected 7,930 +currently eligible interfaces (IUnknown-rooted interfaces plus the existing +`*Interop` selection). This is deliberately narrower than the 7,944 raw +interfaces reported by older census sections; before/after counts below use +the same 7,930-interface selector. Temporary census code and output are not +retained. + +The deduplicated declared BSTR shapes were: + +| Raw metadata shape | Occurrences | +|---|---:| +| Required by-value input | 4,201 | +| Optional by-value input | 27 | +| Scalar `BSTR*` input | 3 | +| Input BSTR array | 7 | +| Required scalar `BSTR*` InOut | 323 | +| Optional scalar `BSTR*` InOut | 4 | +| `BSTR**` InOut | 2 | +| Invalid by-value Out | 5 | +| Required scalar `BSTR*` Out | 3,099 | +| Out BSTR array | 5 | +| Optional scalar `BSTR*` Out | 27 | +| `BSTR**` Out | 6 | +| `BSTR**` Out array | 1 | + +The four optional metadata-InOut occurrences are documentation-defined Out +parameters: `IPhotoAcquireDeviceSelectionDialog::DoModal.pbstrDeviceId` and +the three `IDiscRecorder::GetDisplayNames` strings. The exact Microsoft API +declarations are cited in the semantic override registry. No nullable generic +BSTR replacement contract is inferred. + +Before this phase, 120 interfaces first failed on a scalar BSTR replacement +method; 38 were inherited descendants. The complete-interface result is: + +| Result | Before | After | Net delta | +|---|---:|---:|---:| +| Complete interfaces | 5,188 | 5,289 | **+101** | +| Incomplete interfaces | 2,742 | 2,641 | **-101** | + +The simulated bucket was larger because 18 replacement candidates expose another +unsupported contract after BSTR replacement becomes valid. +`IPhotoAcquireDeviceSelectionDialog` is one example: its BSTR is correctly +normalized to Out, but `pnDeviceType` remains an optional scalar InOut +contract without a safe nullable lowering. `IDiscRecorder` becomes complete +and returns its three display-name strings deterministically. +Separately, `IFileSearchBand` deliberately moves from complete to incomplete: +its scalar input `BSTR*` had previously degraded to a raw pointer even though +the pointee allocation/borrow contract is not proven. + +The largest remaining exact first-error labels in this selector are +`unsupported COM semantic` (215), `invalid COM contract` (52), +PROPVARIANT `GetItem.pValue` (19), `GetWindow.phwnd` (14), +`MovedReferences` (11), and `GetKernelConnectionOptions` (9). + +The supported ownership proof follows the Automation rules documented by +[Memory Management Rules](https://learn.microsoft.com/windows/win32/com/memory-management-rules) +and +[SysAllocStringLen](https://learn.microsoft.com/windows/win32/api/oleauto/nf-oleauto-sysallocstringlen): + +- by-value input: the caller allocates/frees; the callee borrows; +- Out: the callee allocates; the caller owns and frees the result; +- InOut: the caller supplies the initial BSTR, the callee may free/replace it, + and the caller frees the valid final slot; +- on failure, the InOut slot must remain unchanged or contain another safely + cleanable value (including null). + +Runtime storage is a boxed, uniquely owned call-local BSTR slot. Allocation +uses explicit UTF-16 lengths, never NUL-terminated inference. On success the +final slot transfers once to `takeBstr`; on failure RAII frees the valid final +slot. Fake-vtable tests cover embedded NUL input/output, unchanged/replaced/null +success and failure, original-string immutability, and exact allocation/free +counts. + +At the end of that scalar-BSTR phase, before counted owning elements were +implemented, the following remained excluded: + +- three scalar input `BSTR*` contracts (`IFileSearchBand::SetSearchParameters` + and the two VSS `SaveAsXML` methods); +- all 13 native BSTR pointer-array occurrences because initialized-range + element cleanup is incomplete; these are distinct from exact + `SAFEARRAY(BSTR)` declarations, which are covered by the registry below; +- all nine `BSTR**` occurrences because pointer nesting/array ownership is not + proven; +- five invalid by-value Out occurrences; and +- unknown/custom allocators or any BSTR shape not paired with exact Automation + ownership evidence. + +## Complete-interface census after exact SAFEARRAY subtype evidence + +The executable census used +`Microsoft.Windows.SDK.Win32Metadata` **71.0.14-preview** and the same 7,930 +eligible-interface selector as the BSTR phase. It deduplicated declarations at +their declaring interface, so inherited methods were not counted repeatedly. +Temporary census code and output are not retained. + +The metadata contains 239 directly declared `SAFEARRAY` parameters. The exact +registry covers 209 declarations and leaves 30 direct declarations +unsupported. Every registry row keys the declaring namespace, interface IID, +method name, vtable slot, parameter index/name, and complete raw method shape. +Each row also records element VARTYPE, exact element IID when applicable, +borrowed-input or owned-output semantics, a reason, and a Microsoft citation. +An identity or raw-shape mismatch is a contract error, not a generic fallback. + +| Documented element VARTYPE | Registry entries | +|---|---:| +| `VT_I4` | 25 | +| `VT_UI1` | 25 | +| `VT_UI4` | 3 | +| `VT_R8` | 3 | +| `VT_BSTR` | 40 | +| `VT_VARIANT` | 85 | +| `VT_UNKNOWN` plus exact interface IID | 28 | +| **Total** | **209** | + +Of these entries, 69 are borrowed inputs and 140 are owned outputs. Major +families include UI Automation (61), File Server Resource Manager (50), +Mobile Broadband (25), IMAPI (25), Performance Logs and Alerts (20), +Component Services (9), Remote Desktop (8), tuner APIs (5), WMI (3), and +Camera UI (1). + +Representative evidence: + +- UI Automation runtime IDs are documented `SAFEARRAY(int)` (`VT_I4`); + text selection/visible ranges are + [`ITextRangeProvider*`](https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextprovider-getselection) + arrays with IID `5347ad7b-c355-46f8-aff5-909033582f63`. +- Connected-client snapshots are documented + [`IUIAutomationClientInfo*`](https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iuiautomationclientinfosource-getconnectedclients) + arrays with IID `b2e8a3f1-4c5d-4e7a-8f6b-3d2e1c9a0b8f`. +- PLA BSTR properties use the exact method sections in + [MS-PLA](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/); + this covers alert thresholds, API tracing filters, configuration files and + queries, collector-set keywords, and performance counters. +- `ITraceDataProvider::FilterData` is a documented + [byte array](https://learn.microsoft.com/windows/win32/api/pla/nf-pla-itracedataprovider-get_filterdata) + (`VT_UI1`). +- Registered workspace extensions and Camera UI selected-item paths are + documented BSTR arrays by + [`GetRegisteredFileExtensions`](https://learn.microsoft.com/windows/win32/api/workspaceax/nf-workspaceax-iworkspacerestyperegistry-getregisteredfileextensions) + and + [`GetSelectedItems`](https://learn.microsoft.com/windows/win32/api/camerauicontrol/nf-camerauicontrol-icamerauicontrol-getselecteditems). + +`ITextProvider::GetSelection` and +[`IRawElementProviderFragment::GetEmbeddedFragmentRoots`](https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderfragment-getembeddedfragmentroots) +have separate exact evidence that a successful output may be null. Both +project as `DynComSafeArray | null`; `GetVisibleRanges` and all other +registered outputs remain required. + +The complete-interface result is: + +| Result | Before | After | Net delta | +|---|---:|---:|---:| +| Complete interfaces | 5,289 | 5,399 | **+110** | +| Incomplete interfaces | 2,641 | 2,531 | **-110** | +| SAFEARRAY first blockers | 147 | 17 | **-130** | + +The first-blocker decrease is larger than the complete-interface gain because +20 interfaces advance to another unsupported contract. The remaining 17 +SAFEARRAY first blockers are: + +- Mobile Broadband provisioned-context/device-service arrays (2); +- WinHTTP input `SAFEARRAY**` event data (1); +- Component Services module/query arrays, including inherited catalog + amplification (3); +- IIS provider configuration records (1); +- Task Scheduler and Transaction Server metadata-InOut arrays (2); +- IME InOut arrays (1); +- Tablet PC nested/interface arrays (2); +- XAML Diagnostics record arrays inherited through three interfaces (3); and +- MSHTML event-listener and document-write arrays whose exact Automation + VARTYPE contracts are not consistently documented (2). + +Generated JavaScript keeps every supported result as `DynComSafeArray`, not a +natural array, so VARTYPE, exact interface IID, rank, and signed lower bounds +remain observable. Generated signatures use +`DynCom.safeArrayType(kind, iid?, nullable?)`; +owned results transfer through `DynCom.takeSafeArray` or, for the two proven +nullable methods, `DynCom.takeNullableSafeArray`. `DynComSafeArray.interface` +creates `VT_UNKNOWN` arrays with `SafeArrayCreateEx`; its `interfaceIid`, +`bounds`, `elementType`, and conversion methods preserve identity and shape. + +Input descriptors are borrowed for the native call under a per-array lock and +remain owned by the caller. Output `SAFEARRAY**` storage starts null, adopts +the callee result once, validates VARTYPE, rank, bounds, element width, data +alignment, and every non-null typed-interface element with `QueryInterface`, +and calls `SafeArrayDestroy` on every mismatch or failed conversion. An exact +descriptor IID is accepted only when it matches the documented IID. A +descriptor carrying `IID_IUnknown`, or no `FADF_HAVEIID` identity at all, is +accepted only after every element passes that exact query; this is required by +stock UI Automation providers such as +[Microsoft Terminal](https://github.com/microsoft/terminal/blob/main/src/types/ScreenInfoUiaProviderBase.cpp), +which creates its documented text-range results with +`SafeArrayCreateVector(VT_UNKNOWN, ...)`. +[`SafeArrayGetIID`](https://learn.microsoft.com/windows/win32/api/oleauto/nf-oleauto-safearraygetiid) +documents the missing-`FADF_HAVEIID` `E_INVALIDARG` result. The wrapper records +the proven semantic IID after validation. Typed interface inputs are +QueryInterface-validated before creation; SafeArray element +insertion/removal provides the corresponding AddRef/Release behavior. There is +no second dispatch backend. + +## Counted arrays with owning elements + +An executable census against `Microsoft.Windows.SDK.Win32Metadata` +**71.0.14-preview** deduplicated declarations at their declaring interface. +It found 13 BSTR arrays (7 input, 5 caller output, 1 callee allocated), +262 interface arrays (113 input, 142 caller output, 7 callee allocated), and +13 VARIANT arrays (3 input, 10 caller output). The caller-output totals include +in/out count contracts. Exact `IEnum*::Next` shapes occur at slots 3, 4, and +8; inherited declarations are not counted again. + +Supported generated surfaces use `string[]`, `DynComVariant[]`, or nominal +generated interface-wrapper arrays. Input storage is call-local: BSTR uses +`SysAllocStringLen`, including embedded NULs; VARIANT uses contiguous +`VariantCopy` storage; interface values are queried for the exact element IID +and borrowed while those wrappers remain alive. Shared authoritative counts +may describe parallel input/output arrays, and signed count ABIs are accepted +only through checked non-negative conversions. + +Caller output storage is zeroed across the full capacity; VARIANT slots are +additionally `VariantInit`-initialized. Successful calls validate +`actual/fetched <= capacity`, transfer only that initialized range, and clean +unused slots. Failed HRESULTs return no partial values and scan the bounded +capacity. Interface slots release each remaining non-null `+1`; BSTR slots use +`SysFreeString`; VARIANT slots use `VariantClear`; `IEnumString` PWSTR slots +use `CoTaskMemFree`. Validation and conversion are transactional, including +null interface holes and unsupported/BYREF VARIANT tags. + +`IEnumVARIANT` (IID `00020404-0000-0000-c000-000000000046`) and +`IEnumString` (IID `00000101-0000-0000-c000-000000000046`) follow their exact +element ABIs and preserve `S_OK`/`S_FALSE`. `pceltFetched` is nullable only +where the exact standard metadata contract permits it and only for a request +of one element. Incomplete element interfaces receive an opaque nominal +wrapper containing no projected methods, rather than weakening the owning +array API or projecting unsafe members. + +Enumerator projection is keyed by exact namespace, interface IID, and element +type; an `IEnum*` name is not ownership evidence. The exact registry also +covers `IEnumUnknown`, `IEnumVdsObject`, `IEnumEventObject`, and +`IEnumITfCompositionView`. Likewise, only NUL-terminated `*STR` aliases are +automatic strings. `PWCHAR`, `PCWCHAR`, `LPWCH`, `LPCWCH`, `LPCH`, and +`LPCCH` require an explicit counted-character contract. + +The complete-interface census moved from 5,399 to **5,531** of 7,930 eligible +interfaces: **+132 complete** and **-132 incomplete**. Seven owning-array first +blockers remain, all with unknown element semantics: XML issuer pointer lists, +DirectWrite target-family pointer lists, two debugger handle arrays, Shell +PIDL arrays, Text Services category arrays, and Text Services property arrays. +The broader top blockers remain untyped `GetPrivateData` ownership contracts, +PROPVARIANT replacement/InOut contracts, incomplete native layouts, and +unknown pointer/allocator semantics. + +Excluded shapes remain fail closed: owning callee-allocated outer arrays +without an exact outer allocator and per-element contract; BSTR/COM +`T**`/`T***` arrays without exact allocation evidence; unknown pointer, handle, +PIDL, or nested-owning elements; unsupported VARIANT tags/BYREF; and any +count/capacity/actual/fetched relationship that cannot be proven. + +## Borrowed HWND outputs and the final complete-interface census + +The final safety phase used `Microsoft.Windows.SDK.Win32Metadata` +**71.0.14-preview**. The literal generator census contains 7,929 externally +addressable Classic COM interface identities. This is one fewer than older +7,930-interface census sections because the final selector excludes the +IID-less `Windows.Win32.UI.Controls.RichEdit.ITextHost2`; its HWND declaration +is still included in the raw audit below. + +An HWND output is never accepted merely because its native type is `HWND`. +Each supported output must match an exact evidence-registry entry by declaring +namespace/interface/IID, method, absolute vtable slot, parameter count, +parameter index/name, and optionality. The raw contract must also be an +ordinary HRESULT method with a required mutable `[out]` qualified +`Windows.Win32.Foundation.HWND*`, pointer depth one, and no `FreeWith`, +array, SAFEARRAY, or InOut semantics. Any registry or signature drift fails +before generic projection. + +The 22 accepted declarations are: + +| Declaration | IID | Slot / parameter | Microsoft ownership evidence | +|---|---|---|---| +| `IWiaAppErrorHandler::GetWindow` | `6c16186c-d0a6-400c-80f4-d26986a0e734` | 3 / `0: phwnd` | [Returns the existing WIA error-handler dialog HWND](https://learn.microsoft.com/previous-versions/windows/desktop/wia/-wia-iwiaapperrorhandler-getwindow); it may be null and remains owned by the handler. | +| `IPhotoProgressDialog::GetWindow` | `00f246f9-0750-4f08-9381-2cd8e906a4ae` | 4 / `0: phwndProgressDialog` | [Retrieves the progress dialog box handle](https://learn.microsoft.com/windows/win32/api/photoacquire/nf-photoacquire-iphotoprogressdialog-getwindow); it does not create or transfer the dialog. | +| `IOverlay::GetWindowHandle` | `56a868a1-0ad4-11ce-b03a-0020af0ba770` | 8 / `0: pHwnd` | [Retrieves the existing clipping window associated with the overlay](https://learn.microsoft.com/windows/win32/api/strmif/nf-strmif-ioverlay-getwindowhandle). | +| `IMSVidCtl::get_Window` | `b0edf162-910a-11d2-b632-00c04f79498e` | 15 / `0: phwnd` | [Retrieves the existing video control window](https://learn.microsoft.com/windows/win32/api/msvidctl/nf-msvidctl-imsvidctl-get_window). | +| `IMSVidRect::get_HWnd` | `7f5000a6-a440-47ca-8acc-c0e75531a2c2` | 15 / `0: HWndVal` | [Retrieves the window represented by the existing video rectangle](https://learn.microsoft.com/windows/win32/api/segment/nf-segment-imsvidrect-get_hwnd). | +| `IMFPMediaPlayer::GetVideoWindow` | `a714590a-58af-430a-85bf-44f5ec838d85` | 31 / `0: phwndVideo` | [Retrieves the media player's current video window](https://learn.microsoft.com/windows/win32/api/mfplay/nf-mfplay-imfpmediaplayer-getvideowindow). | +| `IMFVideoDisplayControl::GetVideoWindow` | `a490b1e4-ab84-4d31-a1b2-181e03b1077a` | 10 / `0: phwndVideo` | [Retrieves the video window previously set on the display control](https://learn.microsoft.com/windows/win32/api/evr/nf-evr-imfvideodisplaycontrol-getvideowindow). | +| `IConsole::GetMainWindow` | `43136eb1-d36c-11cf-adbc-00aa00a80033` | 12 / `0: phwnd` | [Retrieves MMC's existing main frame window](https://learn.microsoft.com/windows/win32/api/mmc/nf-mmc-iconsole-getmainwindow). | +| `IOleWindow::GetWindow` | `00000114-0000-0000-c000-000000000046` | 3 / `0: phwnd` | [Retrieves an existing participant window](https://learn.microsoft.com/windows/win32/api/oleidl/nf-oleidl-iolewindow-getwindow); ownership remains with the participant that created it. | +| `ICoreWindowInterop::get_WindowHandle` | `45d64a29-a63e-4cb6-b498-5781d298cb4f` | 3 / `0: hwnd` | [Gets the HWND of the existing CoreWindow](https://learn.microsoft.com/windows/win32/api/corewindow/nf-corewindow-icorewindowinterop-get_windowhandle). | +| `IShareWindowCommandEventArgsInterop::GetWindow` | `6571a721-643d-43d4-aca4-6b6f5f30f1ad` | 3 / `0: value` | [Gets the window carried by the event arguments](https://learn.microsoft.com/windows/win32/api/sharewindowcommandsourceinterop/nf-sharewindowcommandsourceinterop-isharewindowcommandeventargsinterop-getwindow). | +| `IDesktopWindowXamlSourceNative::get_WindowHandle` | `3cbcf1bf-2f76-4e9c-96ab-e84b37972554` | 4 / `0: hWnd` | [Gets the existing parent UI-element HWND](https://learn.microsoft.com/windows/win32/api/windows.ui.xaml.hosting.desktopwindowxamlsource/nf-windows-ui-xaml-hosting-desktopwindowxamlsource-idesktopwindowxamlsourcenative-get_windowhandle). | +| `IUpdateInstaller::get_ParentHwnd` | `7b929c68-ccdc-4226-96b1-8724600b54c2` | 11 / `0: retval` | [Retrieves the existing configured parent window](https://learn.microsoft.com/windows/win32/api/wuapi/nf-wuapi-iupdateinstaller-get_parenthwnd). | +| `IUIAutomationElement::get_CachedNativeWindowHandle` | `d22108aa-8ac5-49a5-837b-37bbb3d7591e` | 68 / `0: retVal` | [Retrieves the cached native window handle of the existing element](https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_cachednativewindowhandle). | +| `IUIAutomationElement::get_CurrentNativeWindowHandle` | `d22108aa-8ac5-49a5-837b-37bbb3d7591e` | 36 / `0: retVal` | [Retrieves the current native window handle of the existing element](https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentnativewindowhandle). | +| `ICredentialProviderCredentialEvents::OnCreatingWindow` | `fa6fa76b-66b7-4b11-95f1-86171118e816` | 12 / `0: phwndOwner` | [Returns the Credential UI or Logon UI parent HWND](https://learn.microsoft.com/windows/win32/api/credentialprovider/nf-credentialprovider-icredentialprovidercredentialevents-oncreatingwindow), which providers borrow when parenting dialogs. | +| `ILaunchSourceViewSizePreference::GetSourceViewToPosition` | `e5aa01f7-1fb8-4830-8720-4e6734cbd5f3` | 3 / `0: hwnd` | [Gets the existing source application window](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ilaunchsourceviewsizepreference-getsourceviewtoposition). | +| `IFileIsInUse::GetSwitchToHWND` | `64a1cbf0-3a1a-4461-9158-376969693950` | 6 / `0: phwnd` | [Retrieves the existing application window to switch to](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifileisinuse-getswitchtohwnd). | +| `IPreviewHandler::QueryFocus` | `8895b1c6-b41f-4c1c-a562-0d564250836f` | 8 / `0: phwnd` | [Returns the HWND observed by GetFocus](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ipreviewhandler-queryfocus). | +| `ITextInputPanel::get_AttachedEditWindow` | `6b6a65a5-6af3-46c2-b6ea-56cd1f80df71` | 3 / `0: AttachedEditWindow` | [Retrieves the edit window already attached to the text input panel](https://learn.microsoft.com/windows/win32/api/peninputpanel/nf-peninputpanel-itextinputpanel-get_attachededitwindow). | +| `ITfContextOwner::GetWnd` | `aa80e80c-2021-11d2-93e0-0060b067b86e` | 7 / `0: phwnd` | [Retrieves the existing owner window associated with the text context](https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextowner-getwnd). | +| `ITfContextView::GetWnd` | `2433bf8e-0f9b-435c-ba2c-180611978c30` | 6 / `0: phwnd` | [Retrieves the existing window represented by the text context view](https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextview-getwnd). | + +At runtime, a borrowed HWND result uses zeroed pointer-width output storage and +`PointerOutputKind::None`, with no `Release`, `DestroyWindow`, or other cleanup +on success or failure. JavaScript converts the pointer bits with +`DynCom.asPointerBigint()` and exposes the existing natural +`HWND = bigint | number` alias; null is `0n`. It never exposes a Buffer whose +contents could be confused with its address. + +Exact canonical `IUnknown` (`00000000-0000-0000-c000-000000000046`) elements +in owning counted/enumerator arrays now project directly as +`DynWinRtValue[]`. The runtime's existing per-element `+1` adoption and +`Release` cleanup are unchanged; only wrapper rendering changes. No +`IUnknown.js` file or import is generated, and unresolved non-IUnknown +interfaces remain nominal and fail closed as before. Real metadata regressions +cover `IEnumUnknown`, `IEnumVdsObject`, and `IEnumEventObject`. + +### Complete HWND declaration audit + +The raw metadata census found 58 unique declaring HWND-output parameters. +The 22 entries above are the only ones admitted to the borrowed registry. +Every other declaration remains excluded, even where documentation suggests +an observed/borrowed handle, because the final target was already met or the +complete method/interface contains another unmodeled contract. + +| Declaration (IID) | Slot / parameter / shape | Documentation | Classification | +|---|---|---|---| +| `IDirectDrawClipper::GetHWnd` (`6c14db85-a733-11ce-a521-0020af0be560`) | 4 / `0: param0` / `HWND* InOut` | [Microsoft](https://learn.microsoft.com/windows/win32/api/ddraw/nf-ddraw-idirectdrawclipper-gethwnd) | Getter-like, but metadata is InOut; excluded before borrowed-output projection. | +| `IDXGIFactory::GetWindowAssociation` (`7b7166ec-21c7-44ae-b21a-c9ae321ae369`) | 9 / `0: pWindowHandle` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/dxgi/nf-dxgi-idxgifactory-getwindowassociation) | Documented borrowed identity; not registered because inherited DXGI interfaces remain blocked by `GetPrivateData` ownership. | +| `IDXGISwapChain1::GetHwnd` (`790a45f7-0d42-4876-983a-0a55cfe6f4aa`) | 20 / `0: pHwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgiswapchain1-gethwnd) | Documented borrowed identity; not registered because the complete DXGI interface remains blocked elsewhere. | +| `IAMDirectSound::GetFocusWindow` (`546f4260-d53e-11cf-b3f0-00aa003761c5`) | 10 / `0: param0` / `HWND* InOut` | [Microsoft](https://learn.microsoft.com/windows/win32/api/amaudio/nf-amaudio-iamdirectsound-getfocuswindow) | InOut contract; excluded. | +| `IFullScreenVideo::GetMessageDrain` (`dd1d7110-7836-11cf-bf47-00aa0055595a`) | 12 / `0: hwnd` / `HWND* Out` | No attached Microsoft documentation | Ownership/lifetime not proven; excluded. | +| `IFullScreenVideoEx::GetAcceleratorTable` (`53479470-f1dd-11cf-bc42-00aa00ac74f6`) | 21 / `0: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/amvideo/nf-amvideo-ifullscreenvideoex-getacceleratortable) | HWND is observed, but the method also returns an accelerator-table resource; excluded pending its complete ownership model. | +| `IOverlay::GetWindowHandle` (`56a868a1-0ad4-11ce-b03a-0020af0ba770`) | 8 / `0: pHwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/strmif/nf-strmif-ioverlay-getwindowhandle) | Registered exact borrowed identity; another interface contract still blocks completeness, so this row adds no complete interface. | +| `IMSVidCtl::get_Window` (`b0edf162-910a-11d2-b632-00c04f79498e`) | 15 / `0: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/msvidctl/nf-msvidctl-imsvidctl-get_window) | Registered exact borrowed property; completes `IMSVidCtl`. | +| `IMSVidRect::get_HWnd` (`7f5000a6-a440-47ca-8acc-c0e75531a2c2`) | 15 / `0: HWndVal` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/segment/nf-segment-imsvidrect-get_hwnd) | Registered exact borrowed property; completes `IMSVidRect`. | +| `IMSVidVRGraphSegment::get_Owner` (`dd47de3f-9874-4f7b-8b22-7cb2688461e7`) | 21 / `0: Window` / `HWND* Out` | No attached Microsoft documentation | Ownership/lifetime not proven; excluded. | +| `IMFPMediaPlayer::GetVideoWindow` (`a714590a-58af-430a-85bf-44f5ec838d85`) | 31 / `0: phwndVideo` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/mfplay/nf-mfplay-imfpmediaplayer-getvideowindow) | Registered exact borrowed video window; completes `IMFPMediaPlayer`. | +| `IMFVideoDisplayControl::GetVideoWindow` (`a490b1e4-ab84-4d31-a1b2-181e03b1077a`) | 10 / `0: phwndVideo` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/evr/nf-evr-imfvideodisplaycontrol-getvideowindow) | Registered exact borrowed video window; another interface contract still blocks completeness, so this row adds no complete interface. | +| `IWMPPluginUI::Create` (`4c5e8f9f-ad3e-4bf9-9753-fcd30d6d38dd`) | 4 / `1: phwndWindow` / `HWND* InOut` | [Microsoft](https://learn.microsoft.com/windows/win32/api/wmpplug/nf-wmpplug-iwmppluginui-create) | Creates a plug-in window and is InOut; lifecycle-owned/destroyable, excluded. | +| `IPhotoAcquireOptionsDialog::Create` (`00f2b3ee-bf64-47ee-89f4-4dedd79643f2`) | 4 / `1: phWndDialog` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/photoacquire/nf-photoacquire-iphotoacquireoptionsdialog-create) | Creates a dialog with a separate lifecycle; excluded. | +| `ISpThreadControl::StartThread` (`a6be4d73-4403-4358-b22d-0346e23b1764`) | 4 / `1: phwnd` / `HWND* Out` | No attached Microsoft documentation | Starts a thread/window lifecycle paired with stop behavior; not a generic borrowed getter. | +| `IAuthenticate::Authenticate` (`79eac9d0-baf9-11ce-8c82-00aa004ba90b`) | 3 / `0: phwnd` / `HWND* Out` | No attached Microsoft documentation | Parent-window ownership contract not proven from attached evidence; excluded. | +| `IAuthenticateEx::AuthenticateEx` (`2ad1edaf-d83d-48b5-9adf-03dbe19f53bd`) | 4 / `0: phwnd` / `HWND* Out` | No attached Microsoft documentation | Parent-window ownership contract not proven from attached evidence; excluded. | +| `IInternetSecurityMgrSite::GetWindow` (`79eac9ed-baf9-11ce-8c82-00aa004ba90b`) | 3 / `0: phwnd` / `HWND* Out` | No attached Microsoft documentation | Site-window lifetime not proven from attached evidence; excluded. | +| `IWindowForBindingUI::GetWindow` (`79eac9d5-bafa-11ce-8c82-00aa004ba90b`) | 3 / `1: phwnd` / `HWND* Out` | No attached Microsoft documentation | Binding-UI parent lifetime not proven from attached evidence; excluded. | +| `IActiveScriptSiteWindow::GetWindow` (`d10f6761-83e9-11cf-8f20-00805f2cd064`) | 3 / `0: phwnd` / `HWND* Out` | No attached Microsoft documentation | Site-window lifetime not proven from attached evidence; excluded. | +| `IWebApplicationHost::get_HWND` (`cecbd2c3-a3a5-4749-9681-20e9161c6794`) | 3 / `0: hwnd` / `HWND* InOut` | [Microsoft](https://learn.microsoft.com/windows/win32/api/webapplication/nf-webapplication-iwebapplicationhost-get_hwnd) | InOut metadata; excluded. | +| `IDataSourceLocator::get_hWnd` (`2206ccb2-19c1-11d1-89e0-00c04fd7a829`) | 7 / `0: phwndParent` / `HWND* Out` | No attached Microsoft documentation | Parent-window lifetime not proven; excluded. | +| `IUpdateInstaller::get_ParentHwnd` (`7b929c68-ccdc-4226-96b1-8724600b54c2`) | 11 / `0: retval` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/wuapi/nf-wuapi-iupdateinstaller-get_parenthwnd) | Registered exact borrowed configured-parent property; completes the four-member `IUpdateInstaller` family. | +| `IDesktopWindowTargetInterop::get_Hwnd` (`35dbf59e-e3f9-45b0-81e7-fe75f4145dc9`) | 3 / `0: value` / `HWND* Out` | No attached Microsoft documentation | Target-window lifetime not proven from attached evidence; excluded. | +| `IWindowGraphicsCaptureItemInterop::GetWindow` (`38e4c48b-94e6-4c44-9cfa-968193316c0c`) | 3 / `0: window` / `HWND* InOut` | No attached Microsoft documentation | InOut metadata; excluded. | +| `IIsolatedEnvironmentInterop::GetHostHwndInterop` (`85713c2e-8e62-46c5-8de2-c647e1d54636`) | 3 / `1: hostHwnd` / `HWND* Out` | No attached Microsoft documentation | Host-window lifetime not proven; excluded. | +| `IAccPropServices::DecomposeHwndIdentityString` (`6e26e776-04f0-495d-80e4-3330352e3169`) | 11 / `2: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/oleacc/nf-oleacc-iaccpropservices-decomposehwndidentitystring) | Decoded borrowed identity, but the multi-output contract was not needed for final coverage. | +| `IUIAutomationElement::get_CachedNativeWindowHandle` (`d22108aa-8ac5-49a5-837b-37bbb3d7591e`) | 68 / `0: retVal` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_cachednativewindowhandle) | Registered exact borrowed cached identity; together with the current-value row completes the nine-member `IUIAutomationElement` family. | +| `IUIAutomationElement::get_CurrentNativeWindowHandle` (`d22108aa-8ac5-49a5-837b-37bbb3d7591e`) | 36 / `0: retVal` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentnativewindowhandle) | Registered exact borrowed current identity; together with the cached-value row completes the nine-member `IUIAutomationElement` family. | +| `ITextHost2::TxGetWindow` (IID absent) | 43 / `0: phwnd` / `HWND* InOut` | [Microsoft](https://learn.microsoft.com/windows/win32/api/textserv/nf-textserv-itexthost2-txgetwindow) | IID-less callback declaration plus InOut metadata; excluded from projection and the final denominator. | +| `IActiveIMMApp::GetDefaultIMEWnd` (`08c0e040-62d1-11d1-9326-0060b067b86e`) | 26 / `1: phDefWnd` / `HWND* Out` | No attached Microsoft documentation | Lifetime not proven; excluded. | +| `IActiveIMMIME::CreateSoftKeyboard` (`08c03411-f96b-11d0-a475-00aa006bcc59`) | 73 / `4: phSoftKbdWnd` / `HWND* Out` | No attached Microsoft documentation | Creates a soft-keyboard window with a separate destroy lifecycle; excluded. | +| `IActiveIMMIME::GetDefaultIMEWnd` (`08c03411-f96b-11d0-a475-00aa006bcc59`) | 26 / `1: phDefWnd` / `HWND* Out` | No attached Microsoft documentation | Lifetime not proven; excluded. | +| `IBrowserService2::CreateViewWindow` (`68bd21cc-438b-11d2-a560-00a0c92dbfe8`) | 45 / `3: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shdeprecated/nf-shdeprecated-ibrowserservice2-createviewwindow) | Creates a view window with explicit lifecycle; excluded. | +| `IBrowserService2::GetViewWindow` (`68bd21cc-438b-11d2-a560-00a0c92dbfe8`) | 47 / `0: phwndView` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shdeprecated/nf-shdeprecated-ibrowserservice2-getviewwindow) | Borrowed existing view window; not needed for final coverage. | +| `IBrowserService2::v_MayGetNextToolbarFocus` (`68bd21cc-438b-11d2-a560-00a0c92dbfe8`) | 88 / `4: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shdeprecated/nf-shdeprecated-ibrowserservice2-v_maygetnexttoolbarfocus) | Borrowed focus target, but deprecated multi-parameter semantics remain outside the registry. | +| `IFileIsInUse::GetSwitchToHWND` (`64a1cbf0-3a1a-4461-9158-376969693950`) | 6 / `0: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifileisinuse-getswitchtohwnd) | Registered exact borrowed application window; another interface contract still blocks completeness, so this row adds no complete interface. | +| `IFolderFilter::GetEnumFlags` (`9cc22886-dc8e-11d2-b1d0-00c04f8eeb3e`) | 4 / `2: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifolderfilter-getenumflags) | Borrowed owner identity in a multi-output contract; not needed for final coverage. | +| `IShellBrowser::GetControlWindow` (`000214e2-0000-0000-c000-000000000046`) | 13 / `1: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellbrowser-getcontrolwindow) | Borrowed existing control window; not needed for final coverage. | +| `IShellMenu::GetMenu` (`ee1f7637-e138-11d1-8379-00c04fd918d0`) | 8 / `1: phwnd` / optional `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellmenu-getmenu) | Borrowed identity, but optional output is outside the required-output registry. | +| `IShellView::CreateViewWindow` (`000214e3-0000-0000-c000-000000000046`) | 9 / `4: phWnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellview-createviewwindow) | Creates a view window paired with `DestroyViewWindow`; excluded. | +| `IShellView3::CreateViewWindow3` (`ec39fa88-f8af-41c5-8421-38bed28f4673`) | 20 / `8: phwndView` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/shobjidl/nf-shobjidl-ishellview3-createviewwindow3) | Creates a view window paired with view destruction; excluded. | +| `ITextInputPanel::get_AttachedEditWindow` (`6b6a65a5-6af3-46c2-b6ea-56cd1f80df71`) | 3 / `0: AttachedEditWindow` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/peninputpanel/nf-peninputpanel-itextinputpanel-get_attachededitwindow) | Registered exact borrowed attached edit window; completes `ITextInputPanel`. | +| `ITextStoreACP::GetWnd` (`28888fe3-c2a0-483a-a3ea-8cb1ce51ff3d`) | 28 / `1: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/textstor/nf-textstor-itextstoreacp-getwnd) | Borrowed owner window; not needed for final coverage. | +| `ITextStoreAnchor::GetWnd` (`9b2077b0-5f18-4dec-bee9-3cc722f5dfe0`) | 26 / `1: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/textstor/nf-textstor-itextstoreanchor-getwnd) | Borrowed owner window; not needed for final coverage. | +| `ITfContextOwner::GetWnd` (`aa80e80c-2021-11d2-93e0-0060b067b86e`) | 7 / `0: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextowner-getwnd) | Registered exact borrowed owner window; completes `ITfContextOwner`. | +| `ITfContextView::GetWnd` (`2433bf8e-0f9b-435c-ba2c-180611978c30`) | 6 / `0: phwnd` / `HWND* Out` | [Microsoft](https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextview-getwnd) | Registered exact borrowed view window; completes `ITfContextView`. | +| `IEnumManagerFrames::Next` (`3caa826a-9b1f-4a79-bc81-f0430ded1648`) | 3 / `1: ppWindows` / `HWND** Out` | No attached Microsoft documentation | Ambiguous pointer-to-pointer array/ownership contract; excluded. | + +The 22 registry declarations make 45 complete HWND-bearing interface +projections after inheritance. The 12 additions above recover 19 complete +interfaces: nine in the `IUIAutomationElement` family, four in the +`IUpdateInstaller` family, and six individual interfaces. `IOverlay`, +`IMFVideoDisplayControl`, and `IFileIsInUse` remain incomplete for unrelated +contracts and therefore add no complete-interface census entries. After +removing enum-name ownership inference, requiring distinct actual-length +parameters to be exact Out values, and separating counted character pointers +from terminated strings, the exact final literal census is +**5,558 / 7,929 = 70.097112%**. The result remains above the 70% target without +admitting any creator-owned, destroyable, InOut, undocumented, optional, or +`HWND**` shape. ## Public-code frequency snapshot @@ -589,62 +1223,63 @@ against the resolved namespace. | Rank | Interface/search token | `.cpp` hits | Repos / first 100 | In Win32 winmd | Current codegen | |---:|---|---:|---:|---|---| -| 1 | `ID3D11Device` | 27,552 | 87 | Yes | Fail closed: native `D3D11_COUNTER_INFO` layout | +| 1 | `ID3D11Device` | 27,552 | 87 | Yes | Fail closed: untyped output ownership | | 2 | `IDXGIFactory` | 17,432 | 83 | Yes | Fail closed: untyped output ownership | -| 3 | `IDataObject` | 10,648 | 44 | Yes | Fail closed: `STGMEDIUM`/union layout | +| 3 | `IDataObject` | 10,648 | 44 | Yes | Fail closed: `STGMEDIUM` has unmodeled discriminant/resource ownership | | 4 | `IMalloc` | 10,624 | 56 | Yes | Fail closed: direct raw-pointer return mapping; runtime tested | | 5 | `IClassFactory` | 6,712 | 70 | Yes | Generates; acquisition helper and live test still needed | -| 6 | `IDispatch` via `IID_IDispatch` | 6,408 | 46 | Yes | Fail closed: counted arrays, VARIANT-family ABI | +| 6 | `IDispatch` via `IID_IDispatch` | 6,408 | 46 | Yes | Complete inherited interface generates; `Invoke` uses dedicated DISPPARAMS/EXCEPINFO and explicit optional-output requests | | 7 | `IPersistFile` | 5,996 | 97 | Yes | Generates and live-tested | | 8 | `IConnectionPoint` | 5,832 | 51 | Yes | Generates; implementing event sinks is not supported | | 9 | `IWbemServices` | 5,680 | 76 | Yes | Fail closed: interface in/out ownership | | 10 | `IWICImagingFactory` | 4,536 | 83 | Yes | Generates and live-tested | -| 11 | `IDropTarget` | 4,368 | 57 | Yes | Fail closed: native `POINTL` layout | -| 12 | `IShellFolder` | 4,056 | 33 | Yes | Fail closed: native `STRRET` union layout | +| 11 | `IDropTarget` | 4,368 | 57 | Yes | Generates with by-value POD `POINTL`; implementing a drop target is not supported | +| 12 | `IShellFolder` | 4,056 | 33 | Yes | Fail closed: untyped PIDL output ownership (and later `STRRET` union ABI) | | 13 | `IFileDialog` | 4,048 | 98 | Yes | Generates; inherited methods tested through `IFileOpenDialog` | -| 14 | `IXMLDOMDocument` | 3,784 | 46 | Yes | Fail closed: inherits Automation/VARIANT ABI | +| 14 | `IXMLDOMDocument` | 3,784 | 46 | Yes | Fail closed: inherited unsupported Automation shapes beyond scalar VARIANT | | 15 | `ID2D1Factory` | 3,752 | 92 | Yes | Generates; requires flat factory acquisition and native input structs | | 16 | `IDWriteFactory` | 3,712 | 76 | Yes | Generates; requires flat factory acquisition | | 17 | `IStream` via `IID_IStream` | 3,560 | 41 | Yes | Fail closed on `STATSTG`; safe runtime subset is live-tested | -| 18 | `IPropertyStore` | 3,400 | 77 | Yes | Fail closed: `PROPERTYKEY` and `PROPVARIANT` | +| 18 | `IPropertyStore` | 3,400 | 77 | Yes | Fail closed: `PROPERTYKEY`; PROPVARIANT runtime subset exists | | 19 | `IShellItem` | 3,028 | 76 | Yes | Generates; acquisition/live test still needed | | 20 | `IMMDeviceEnumerator` | 2,932 | 83 | Yes | Generates; live result depends on audio services/devices | -| 21 | `IBindCtx` | 2,660 | 42 | Yes | Fail closed: native `BIND_OPTS` layout | +| 21 | `IBindCtx` | 2,660 | 42 | Yes | Fails closed until `BIND_OPTS.cbStruct` initialization is modeled | | 22 | `IFileOpenDialog` | 2,536 | 92 | Yes | Generates and live-tested without showing UI | -| 23 | `IRunningObjectTable` | 2,532 | 50 | Yes | Fail closed: native `FILETIME` layout | +| 23 | `IRunningObjectTable` | 2,532 | 50 | Yes | Generates with POD `FILETIME`; acquisition/live test still needed | | 24 | `IAudioClient` | 2,500 | 82 | Yes | Fail closed: format pointer/output ownership | -| 25 | `IShellLinkW` | 2,128 | 67 | Yes | Fail closed: writable `WIN32_FIND_DATAW` layout | +| 25 | `IShellLinkW` | 2,128 | 67 | Yes | Generates and is live-tested with nested/fixed-array POD `WIN32_FIND_DATAW` | | 26 | `ITaskbarList3` / `TaskbarList` | 1,672 | 87 | Yes | Interface and newable coclass generate and are live-tested | | 27 | `ICoreWebView2` | 1,608 | 35 | **No** | Defined in WebView2 metadata, not Windows.Win32.winmd | | 28 | `IFileSaveDialog` | 1,188 | 96 | Yes | Generates; live test still needed | | 29 | `IFileOperation` | 768 | 79 | Yes | Generates and live-tested | -| 30 | `ITaskService` | 461 | 72 | Yes | Fail closed: inherits Automation/VARIANT ABI | +| 30 | `ITaskService` | 461 | 72 | Yes | Fail closed: inherited unsupported Automation shapes | ### What the snapshot shows - **29 of 30** candidates are defined as `IUnknown`-rooted interfaces in Windows.Win32.winmd. `ICoreWebView2` is the only external-metadata case. -- **14 of 29** Win32-metadata candidates pass complete codegen validation. - **15 of 29** fail closed on an unsupported ABI or ownership shape. +- **19 of 29** Win32-metadata candidates pass complete codegen validation. + **10 of 29** fail closed on an unsupported ABI or ownership shape. - Among the **top 10** by `.cpp` hits, only `IClassFactory`, - `IPersistFile`, `IConnectionPoint`, and `IWICImagingFactory` pass complete - codegen. `IMalloc` has a tested runtime path but not a complete generated - interface. + `IDispatch`, `IPersistFile`, `IConnectionPoint`, and `IWICImagingFactory` + pass complete codegen. `IMalloc` has a tested runtime path but not a complete + generated interface. - The largest unsupported demand clusters are: - - native structs/unions and layout (`D3D11`, `IDataObject`, Shell, streams); - - Automation types (`IDispatch`, XML, Task Scheduler); + - discriminated resource unions and non-POD layout (`IDataObject`, parts of Shell and streams); + - Automation contracts beyond the exact supported `IDispatch` compounds + (XML and Task Scheduler BYREF/InOut and nested ownership); - explicit output ownership (`DXGI`, audio); - interface in/out semantics (WMI); and - - Property System types (`PROPERTYKEY`, `PROPVARIANT`). + - remaining Property System types (`PROPERTYKEY` and unsupported PROPVARIANT alternatives). - Six frequency-survey candidates have generated live coverage: `IPersistFile`, `IWICImagingFactory`, `IFileDialog` through - `FileOpenDialog`, `TaskbarList`, and `FileOperation`. `IShellLinkW`, - `IMalloc`, and `IStream` add runtime-only live coverage. + `FileOpenDialog`, `TaskbarList`, `FileOperation`, and `IShellLinkW`. + `IMalloc` and `IStream` add runtime-only live coverage. This means the current ten-interface suite provides useful ABI breadth, but it does **not** cover every high-frequency interface. In particular, -`IDataObject`, `IDispatch`, `IPropertyStore`, graphics interfaces, WMI, and -audio remain material gaps. +`IDataObject`, `IPropertyStore`, graphics interfaces, WMI, audio, and live +real-object `IDispatch::Invoke` coverage remain material gaps. ## Engineering priority map @@ -654,10 +1289,12 @@ hardware, and whether it adds a distinct ABI shape. | Interface | Typical use | Current status | |---|---|---| -| `IStream` | OLE streams, imaging, shell, serialization | Core live test covers counted buffers, seek, and interface output. | +| `ISequentialStream` / `IStream` | OLE streams, imaging, shell, serialization | Generated `Read`/`Write` wrappers use documented byte contracts; the core live memory-stream test covers typed input/output buffers, actual lengths, seek, and interface output. | +| `IOpcSignatureCustomObject` | OPC signature custom XML | `GetXml` generates as a CoTaskMem-owned callee byte buffer; acquisition is application-specific. | +| `IDiscRecorder` | Legacy IMAPI recorder | Complete generation now includes the exact `GetRecorderGUID` two-call method and documentation-correct `getDisplayNames(): [string, string, string]` BSTR outputs. | | `IMalloc` | COM task allocator | Core live test covers direct pointer, pointer-sized, scalar, and void returns. | | `IPersistFile` | Loading and saving persistent COM objects | Core tests query it from `IShellLinkW`; Node activates the Shell Link coclass directly as `IPersistFile` and verifies `GetClassID`. | -| `IShellLinkW` | Shortcut creation and inspection | Core runtime tests cover strings, `u16`, enums, and scalar outputs; metadata codegen fails closed on `WIN32_FIND_DATAW`. | +| `IShellLinkW` | Shortcut creation and inspection | Core runtime tests cover strings, `u16`, enums, and scalar outputs; generated Node coverage round-trips `GetPath` with nested `FILETIME` and fixed WCHAR-array `WIN32_FIND_DATAW` POD storage. | | `FileOpenDialog` | Desktop file selection | Node test covers coclass construction and option round-trip without showing UI. | | `FileOperation` | Shell copy/move/delete operations | Node test covers coclass construction, unsigned flags, and state without modifying files. | | `IWICImagingFactory` | Windows Imaging Component | Node test activates WIC and creates an interface-valued stream. | @@ -665,28 +1302,61 @@ hardware, and whether it adds a distinct ABI shape. | `IDataTransferManagerInterop` | HWND-to-WinRT data-transfer bridge | Core and Node tests cover `IUnknown`-rooted interop and interface output. | | `ISystemMediaTransportControlsInterop` | HWND-to-WinRT media controls | Node test covers `IInspectable`-rooted interop and use of the returned WinRT object. | | `IClassFactory` | Low-level COM activation | High-value next test; needs a public `CoGetClassObject` acquisition path. | -| `IBindCtx` / `IRunningObjectTable` | Monikers and object binding | High-value next test; needs acquisition helpers and validated native structs. | +| `IBindCtx` / `IRunningObjectTable` | Monikers and object binding | `IRunningObjectTable` generates with validated `FILETIME`; `IBindCtx` fails closed because zero-initialized `BIND_OPTS.cbStruct` is invalid. | | `ICreateErrorInfo` / `IErrorInfo` | COM rich error information | Good next test for GUID, wide strings, BSTR, and thread-local error state. | | `IMMDeviceEnumerator` | Audio endpoint discovery | Generates today, but live behavior depends on available audio endpoints. | | `IAudioClient` | Low-level audio streaming | Fails closed because its format and output-pointer shapes are not fully modeled. | -| `IDispatch` | Automation and scripting | Unsupported until VARIANT-family marshaling exists. | -| `IPropertyStore` | Shell/property metadata | Unsupported until PROPERTYKEY and PROPVARIANT are modeled. | +| `IDispatch` | Automation and scripting | Complete inherited real-metadata generation passes. `GetIDsOfNames` projects as `string[] -> number[]`; `Invoke` accepts `DynComDispatchParams` and explicit result/excepInfo/argErr request options, returning dedicated owning wrappers. Derived Automation interfaces remain independently validated. | +| `IPropertyStore` | Shell/property metadata | The PROPVARIANT runtime subset is implemented; complete generation remains blocked by PROPERTYKEY projection and full-interface validation. | | `IDataObject` | Clipboard and drag-and-drop | Unsupported until FORMATETC and STGMEDIUM are modeled. | ## Automated coverage -Ten unique Classic COM interfaces are currently exercised. +Eleven unique Classic COM interfaces are currently exercised. Core live tests are in -[`crates/dynwinrt/src/com.rs`](../crates/dynwinrt/src/com.rs). The nine Node -runners are in [`tests/runners/com`](../tests/runners/com) and are generated +[`crates/dynwinrt/src/com.rs`](../crates/dynwinrt/src/com.rs). The eleven Node +runners plus the counted-buffer runner (twelve total) are in +[`tests/runners/com`](../tests/runners/com) and are generated and executed by [`tests/e2e_test.ps1`](../tests/e2e_test.ps1). +Automation coverage remains scoped to proven contracts rather than claimed as +general interface support. Local fake COM vtables copy pointer-shaped VARIANT, +SAFEARRAY, and PROPVARIANT inputs to owned outputs and verify conversion, +failure cleanup, typed-array rejection, interface AddRef/Release balance, and +native-union active-field validation. SAFEARRAY tests additionally cover +signed multidimensional bounds, typed scalar/bool/BSTR/VARIANT values, exact +interface IID creation/inspection/mismatch cleanup, generic-descriptor +per-element validation, nullable output, and descriptor VARTYPE/width/rank +validation. Dedicated BSTR fake-vtable tests pass +embedded-NUL input and output values and exercise unchanged, replaced, and +nulled InOut slots on both successful and failed HRESULT paths with exact +allocation/free counters. Separate x64 and i686 fake-vtable tests pass scalar, +BSTR, and interface VARIANT values by value and verify windows-rs layout, +libffi aggregate classification, deep-copy isolation, HRESULT failure cleanup, +panic-safe drop, wrong argument shape, unsupported tags, BYREF rejection, and +output/InOut signature rejection. Real Windows.Win32 metadata regressions +inspect `ITargetNotify2`, inherited `IExecAction2`, `IDiscRecorder`, +`IPhotoAcquireDeviceSelectionDialog`, BSTR arrays/double pointers/custom +cleanup, `IAccessible::accSelect`, +`IUIAutomation::CreatePropertyCondition`, IPropertyBag VARIANT pointer/InOut, +exact SAFEARRAY families across UI Automation, WMI, FSRM, PLA, Remote Desktop, +Camera UI, tuner, and Mobile Broadband APIs, IPropertyStore PROPVARIANT output, +and ITypeComp BINDPTR union facts. Complete interfaces still stop at their next +unrelated or unproven contract. + +The exact `IDispatch::Invoke` contract uses a COM-local captured-HRESULT plan. +Successful calls expose only an optional `result` VARIANT. Failed calls discard +and clear `pVarResult`, finalize requested `EXCEPINFO` storage once, preserve a +meaningful `argErr`, and generate an `Error` with `hresult` plus optional +`excepInfo`, `argErr`, and deferred-fill `cause` fields. + | Interface | Test layer | Representative coverage | |---|---|---| -| `IShellLinkW` | Core | Manual ABI coverage for activation, wide strings, hotkeys, and show command; codegen intentionally fails closed. | +| `IShellLinkW` | Core + Node E2E | Generated activation through its IID, wide strings, hotkeys/show command, and `GetPath` with zeroed 592-byte `WIN32_FIND_DATAW` POD storage. | | `IPersistFile` | Core + Node E2E | `QueryInterface`/direct IID activation, owned returned reference, GUID output, and deterministic release. | | `IMalloc` | Core | Direct pointer return, `usize` return, direct `i32`, direct `void`, allocation cleanup. | -| `IStream` | Core | Counted byte buffer, `u32` output, `i64` seek, `u64` output, and `IStream**` clone. | +| `IStream` | Core | Typed counted byte input/output buffers, actual `u32` lengths, `i64` seek, `u64` output, and `IStream**` clone. | +| `ISequentialStream` | Node E2E | Generated caller-owned `Read` byte buffer, hidden capacity, actual-length slicing, and preserved semantic HRESULT against a stock WIC memory stream. | | `TaskbarList` / `ITaskbarList3` | Node E2E | Coclass construction, inherited slots, runtime QI views, HWND, BOOL, enum, and `u64`. | | `FileOperation` | Node E2E | Coclass construction, unsigned flags, and state query. | | `FileOpenDialog` | Node E2E | STA coclass construction and get/set options without user interaction. | @@ -694,19 +1364,46 @@ and executed by [`tests/e2e_test.ps1`](../tests/e2e_test.ps1). | `IDataTransferManagerInterop` | Core + Node E2E | `IUnknown` base, HWND, REFIID, and WinRT interface output. | | `ISystemMediaTransportControlsInterop` | Node E2E | `IInspectable` base and meaningful use of the returned WinRT projection. | -`IShellLinkW` is deliberately excluded from generated E2E coverage because -`GetPath` contains a writable `WIN32_FIND_DATAW*` without a modeled native -layout. The core runtime retains manual ABI coverage, while the Node E2E uses -the same Shell Link coclass through the safely generated `IPersistFile` -interface. - Additional regression tests cover: +- a test-only windows-rs ABI oracle for selected stable interfaces and native + layouts: interface IIDs, host-target size/alignment, and field offsets for + `RECT`, `THUMBBUTTON`, `WIN32_FIND_DATAW`, `DISPPARAMS`, and `EXCEPINFO`; + windows-rs is not a production dispatch backend and does not replace + semantic validation; - rejection of duplicate ownership through exported pointer bits; - detached TypedArray backing storage; -- BSTR and `CoTaskMem` cleanup; +- BSTR exact-length allocation, replacement, null/failure cleanup, and + `CoTaskMem` cleanup; +- exact SAFEARRAY registry identity/raw-shape drift, VARTYPE constants, + windows-rs UI Automation IIDs, signed bounds, typed-interface descriptor and + per-element QI validation, BSTR/scalar/interface cleanup, nullable output, + and nearest unsupported input-`SAFEARRAY**`, InOut, and record-array shapes; - x86 pointer width; -- unsupported native arrays and native struct layouts; +- x86/x64/ARM64 POD layout computation, nested structs, fixed arrays, and all + value/pointer/out/in-out storage shapes; +- typed buffer zero initialization, actual-length slicing, bounded sizing, + CoTaskMem transfer, failure suppression, detached backing, width, length, + and alignment validation; +- exact fixed-capacity `IMFAttributes::GetBlob` metadata, natural GUID/capacity + rendering, runtime-owned zeroed storage, successful actual-length slicing, + capacity overflow, short-buffer failure, and ordinary HRESULT failure; +- exact cited rejection of all seven declaring `GetPrivateData` families whose + payload may carry an AddRef'd interface, including mutation tests for IID, + method/slot, REFGUID depth/constness, count direction/type, buffer + direction/depth/optionality, actual count, and HRESULT return; +- deterministic fake-vtable `IEnum*::Next` partial-success, optional-fetched, + fetched-overflow, interface transfer, unused-capacity, and failed-HRESULT + cleanup, plus complete real-metadata generation of `IEnumGUID` and + `IEnumConnectionPoints` (including the `IConnectionPoint` dependency); +- borrowed UTF-16/ANSI string-pointer arrays, stable pointer tables, shared + count agreement, aligned zeroed scalar output arrays, and complete real + `IDispatch` generation; +- fake-vtable DISPPARAMS reversal/named-ID/contiguous-storage checks and + EXCEPINFO immediate/deferred success, callback failure, HRESULT failure, + optional-null output, and conversion-failure cleanup; +- unsupported unions, bitfields, flexible arrays, unknown layouts, and nested + owned fields; - required parameter preservation; - unsigned enum values; - mixed, COM-only, and order-independent incremental package generation; and @@ -731,9 +1428,17 @@ COM interface references and Win32 handles must not be treated the same. | Interface passed as `[in]` | Borrowed for the duration of the call | No ownership transfer unless the callee explicitly retains it with `AddRef`. | | Numeric raw pointer | Borrowed | Never automatically released or freed. | | Buffer/TypedArray pointer | Borrowed and owner-backed | Backing storage is retained and revalidated; it cannot be adopted as a COM owner. | +| Caller-owned counted output | Borrowed during the call; returned bytes are an owned exact-range copy | Native storage is zeroed first. Failed HRESULTs return no copied result. | +| `IEnum*::Next` interface element | Each non-null initialized slot is an owned `+1` reference | Fetched slots move once into managed values; slots are nulled on transfer. Failure, overflow, conversion error, and unused initialized capacity release remaining slots within the requested bound. | +| Callee-allocated counted `CoTaskMem` output | Allocation transfers once to the COM buffer plan | Exact bytes are copied and the original allocation is freed once with `CoTaskMemFree`. | | `adoptComPointer()` input | Must be a native output carrying an existing `+1` reference | Ownership transfers to the returned wrapper. | | Callee-allocated `CoTaskMem` string | Owned allocation | Generated conversion frees it with `CoTaskMemFree`. | +| By-value BSTR input | Caller-owned call-local allocation; borrowed by the callee | Runtime frees it after the call. | | Scalar BSTR output | Owned allocation | Generated conversion frees it with `SysFreeString`. | +| Scalar BSTR InOut | Caller owns the initial and final slot; callee may free/replace the initial allocation | Runtime owns one unique call-local slot, transfers the successful final value once, and frees the valid final value on failure. | +| SAFEARRAY input | Caller-owned descriptor and elements, borrowed for the invocation | A per-array lock keeps the descriptor stable; no ownership transfer occurs. | +| SAFEARRAY output | Callee-owned descriptor transferred through `SAFEARRAY**` | Runtime adopts exactly once after HRESULT success and exact descriptor validation; RAII calls `SafeArrayDestroy` on rejection, conversion failure, or final drop. | +| Typed interface SAFEARRAY element | SafeArray-owned interface reference with an exact proven IID | Input creation and output adoption QueryInterface-validate each non-null value; descriptors with the exact IID, `IID_IUnknown`, or no IID are distinguished, and the latter two rely on element proof for the identity fallback. SafeArray APIs perform element AddRef/Release and `SafeArrayDestroy` releases remaining elements. | | `HANDLE`, `HWND`, `HBITMAP`, etc. | Win32 resource value, not a COM reference | Use the resource-specific API such as `CloseHandle`, `DestroyWindow`, or `DeleteObject` when required. | The JavaScript ownership provenance checks intentionally prevent turning a diff --git a/docs/classic-com-usage.md b/docs/classic-com-usage.md new file mode 100644 index 00000000..446c9d80 --- /dev/null +++ b/docs/classic-com-usage.md @@ -0,0 +1,691 @@ +# Classic COM JavaScript Usage Guide + +This guide explains how to use `dynwinrt` to call Classic COM from Node.js/Electron and how to correctly handle +GUIDs, IIDs, CLSIDs, and REFIIDs. + +> Prefer the safe bindings generated by `dynwinrt-codegen`. Use `@microsoft/dynwinrt/com/unsafe` only when the +> metadata cannot fully describe the ABI and you have verified every calling convention against the native headers +> and Microsoft documentation. + +## 1. Responsibilities of the three entry points + +| Entry point | Purpose | +| -------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `@microsoft/dynwinrt` | Public WinRT API; does not include Classic COM | +| `@microsoft/dynwinrt/com` | COM initialization, GUIDs, and managed Automation/POD values | +| `@microsoft/dynwinrt/com/unsafe` | Manual interface registration, explicit ABI declarations, vtable invocation, and native pointer handling | + +Applications that consume standard generated code usually need only: + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; +import { TaskbarList, TBPFLAG } from "./generated/com/index.js"; +``` + +Do not import COM APIs from the package root: + +```js +// Incorrect: The root entry point remains WinRT-only. +import { DynCom } from "@microsoft/dynwinrt"; +``` + +## 2. Installation + +```powershell +npm install @microsoft/dynwinrt +npm install --save-dev @microsoft/dynwinrt-codegen +``` + +Classic COM code generation requires `Windows.Win32.winmd`. It is typically provided by the +`Microsoft.Windows.SDK.Win32Metadata` NuGet package, for example: + +```text +Q:\.tools\.nuget\packages\microsoft.windows.sdk.win32metadata\ + 71.0.14-preview\Windows.Win32.winmd +``` + +## 3. Initialize the COM apartment + +Call `initializeCom()` once on each thread before that thread first interacts with any COM object: + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; + +initializeCom(1); // MTA, the default +// initializeCom(0); // STA +``` + +Parameter values: + +| Value | Apartment | +| ----: | ----------------------------------------------------------- | +| `0` | STA, for COM APIs that require a single-threaded apartment | +| `1` | MTA, for most background, service, and data-processing APIs | + +Important: + +- An apartment belongs to a thread, not to the entire process. +- Initialize the Node.js main thread and each Worker thread separately, once per thread and before COM object + interaction on that thread. +- Do not initialize a thread as STA and then attempt to change it to MTA. +- `initializeCom()` does not load the Windows App SDK and is not equivalent to `initWinappsdk()`. + +## 4. Generate safe bindings with codegen + +### 4.1 Run a dry run first + +```powershell +$winmd = "Q:\.tools\.nuget\packages\microsoft.windows.sdk.win32metadata\71.0.14-preview\Windows.Win32.winmd" + +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --namespace Windows.Win32.UI.Shell ` + --class-name TaskbarList ` + --output .\generated ` + --dry-run +``` + +`--dry-run` performs metadata, dependency, ABI, ownership, and layout validation without writing files. If +validation fails, the complete interface still contains an unmodeled native contract. The generator fails closed +instead of emitting code that appears usable but might corrupt memory. + +### 4.2 Generate files + +```powershell +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --namespace Windows.Win32.UI.Shell ` + --class-name TaskbarList ` + --output .\generated +``` + +You can also generate multiple fully qualified names at once: + +```powershell +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --class-name "Windows.Win32.UI.Shell.TaskbarList,Windows.Win32.System.Com.ISequentialStream" ` + --output .\generated +``` + +Generated output is placed in `generated/com/`. Internally, the `.js` files import +`@microsoft/dynwinrt/com/unsafe` to execute the validated ABI plan. The public `.d.ts` files reference only the safe +value types from `@microsoft/dynwinrt/com`. + +### 4.3 Customize the runtime path + +For development repositories or packaging scenarios, specify: + +```powershell +npx dynwinrt-codegen generate ` + --winmd $winmd ` + --namespace Windows.Win32.UI.Shell ` + --class-name TaskbarList ` + --import-name ../runtime/com-unsafe.js ` + --output .\generated +``` + +The default package name, `@microsoft/dynwinrt`, maps to `@microsoft/dynwinrt/com/unsafe` in JavaScript and +`@microsoft/dynwinrt/com` in declaration files. The exact name `@microsoft/dynwinrt/com` also maps to +`/com/unsafe`. When a custom path has the exact basename `com.js` or `com-unsafe.js`, codegen converts between the +two names as appropriate. It does not guess or rewrite any other custom module name. + +## 5. Call generated COM classes + +### 5.1 Coclass activation + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; +import { TaskbarList, TBPFLAG } from "./generated/com/index.js"; + +initializeCom(1); + +const taskbar = new TaskbarList(); +try { + taskbar.hrInit(); + taskbar.setProgressState(hwnd, TBPFLAG.TBPF_NORMAL); + taskbar.setProgressValue(hwnd, 30n, 100n); +} finally { + taskbar.release(); +} +``` + +Public constructors are generated only for coclasses whose primary interface can be determined conservatively from +metadata. Interface classes cannot be instantiated directly with `new`. + +### 5.2 QueryInterface views + +```js +import { TaskbarList, ITaskbarList3 } from "./generated/com/index.js"; + +const taskbar = new TaskbarList(); +try { + const v3 = taskbar.as(ITaskbarList3); + try { + // v3 owns an independent +1 reference returned by the actual QueryInterface call. + } finally { + v3.release(); + } + + const optional = taskbar.tryAs(ITaskbarList3); + optional?.release(); + + console.log(taskbar.supports(ITaskbarList3)); +} finally { + taskbar.release(); +} +``` + +Differences: + +| Method | Behavior | +| -------------------------- | -------------------------------------------------------------------------------- | +| `as(InterfaceClass)` | Throws if the IID is not supported | +| `tryAs(InterfaceClass)` | Returns `null` for `E_NOINTERFACE` | +| `supports(InterfaceClass)` | Queries and immediately releases the temporary reference, then returns a Boolean | + +### 5.3 WinRT interop interfaces + +Some Classic COM interfaces provide access to WinRT objects, such as `IDataTransferManagerInterop`. The generator +creates a safe `create()` method: + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; +import { IDataTransferManagerInterop } from "./generated/com/IDataTransferManagerInterop.js"; + +initializeCom(1); + +const interop = IDataTransferManagerInterop.create(); +try { + const manager = interop.getForWindow(hwnd); + try { + // The return value is a managed DynWinRtValue. Pass it to APIs that accept + // this WinRT/COM interface, or cast it by using the exact IID. + console.log(manager.isNull()); // false + } finally { + manager.release(); + } +} finally { + interop.release(); +} +``` + +## 6. JavaScript projections of common native types + +| Native semantics | JavaScript/TypeScript | +| --------------------------------- | --------------------------------------------------------------------- | +| `BOOL` / `VARIANT_BOOL` | `boolean`; Automation true uses the native value `-1` | +| 8-, 16-, and 32-bit integers | `number` | +| 64-bit integers | `bigint` | +| `float` / `double` | `number` | +| By-value `GUID` | Usually projected as a GUID string; the raw ABI uses `WinGuid` values | +| IID/CLSID constants | `WinGuid` or a CLSID string; see the GUID section | +| `BSTR` | `string`; embedded NUL characters are supported | +| NUL-terminated `PWSTR` / `PCWSTR` | `string`; correctly encoded byte storage can also be used | +| Borrowed handles such as `HWND` | `bigint \| number` | +| COM interface output | Generated interface wrapper or managed `DynWinRtValue` | +| Multiple output parameters | Tuple, such as `[string, number]` | +| POD struct | Layout-branded `DynComNativeStruct` | +| POD struct array | Layout-branded `DynComNativeStructArray` | +| `VARIANT` | `DynComVariant` | +| `SAFEARRAY` | `DynComSafeArray` | +| `PROPVARIANT` | `DynComPropVariant` | + +Do not treat every pointer as a Buffer: + +- The **contents** of a handle Buffer represent the handle bits. +- A data-pointer Buffer passes the **address** of its backing store. +- A string Buffer must satisfy the encoding, alignment, and terminator requirements. +- A COM interface must be a managed reference and cannot be replaced by a Buffer. + +## 7. Lifetime and ownership + +### 7.1 COM interfaces + +The following sources return a managed `+1` reference: + +- `CoCreateInstance`; +- `QueryInterface`; +- a validated interface out parameter; +- the QI result returned by `DynComUnsafe.borrowComPointer()`. + +Wrapper objects eventually call `Release` automatically, but deterministic release at a known boundary is +recommended: + +```js +const object = new TaskbarList(); +try { + // Use object. +} finally { + object.release(); +} +``` + +You can call `release()` more than once, but do not call any other member after releasing the object. + +### 7.2 String and Automation ownership + +The runtime uses the matching cleanup function specified by the validated contract: + +| Allocation/ownership | Cleanup | +| -------------------- | --------------------- | +| COM `+1` | `Release` | +| BSTR | `SysFreeString` | +| HSTRING | `WindowsDeleteString` | +| CoTaskMem | `CoTaskMemFree` | +| VARIANT | `VariantClear` | +| SAFEARRAY | `SafeArrayDestroy` | +| PROPVARIANT | `PropVariantClear` | + +Safe codegen rejects the entire interface when the allocator is ambiguous. + +## 8. Complete GUID type reference + +### 8.1 Relationship between GUID, IID, CLSID, and REFIID + +All four use an underlying 128-bit GUID, but they have different semantics: + +| Name | Meaning | +| ------ | ---------------------------------------------------- | +| GUID | General-purpose 128-bit identifier | +| IID | Identity of a COM interface | +| CLSID | Identity of a COM coclass | +| REFIID | Native ABI pointer to a read-only IID: `const GUID*` | + +Do not interchange these concepts merely because they have the same binary layout. For example, a CLSID cannot +replace the IID required by `QueryInterface`. + +### 8.2 `WinGuid` and `WinGUID` + +```ts +import { WinGuid, type WinGUID } from "@microsoft/dynwinrt/com"; + +const iid: WinGUID = WinGuid.parse("00000000-0000-0000-c000-000000000046"); + +console.log(iid.toString()); +``` + +`WinGUID` is only a TypeScript alias for `WinGuid`: + +```ts +export type WinGUID = WinGuid; +``` + +API: + +| API | Description | +| --------------------- | -------------------------------------------- | +| `WinGuid.parse(text)` | Validates and creates a GUID | +| `guid.toString()` | Returns the canonical hyphenated GUID string | + +Always use the canonical format: + +```text +xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +``` + +GUID comparison is case-insensitive for hexadecimal digits under COM semantics. To compare GUIDs, compare their +canonical strings: + +```js +const equal = left.toString().toLowerCase() === right.toString().toLowerCase(); +``` + +Invalid input throws immediately: + +```js +WinGuid.parse("not-a-guid"); // Error: Invalid GUID +``` + +### 8.3 Generated IID constants + +Each generated interface exports a strongly typed IID: + +```ts +import { IID_ITaskbarList3, ITaskbarList3 } from "./generated/com/index.js"; + +// IID_ITaskbarList3: WinGuid +console.log(IID_ITaskbarList3.toString()); + +// The IID on the class descriptor identifies the same interface. +console.log(ITaskbarList3.IID.toString()); +``` + +Generated code uses this IID internally to: + +- register the interface vtable; +- call QueryInterface; +- validate interface out parameters; +- process dynamic-IID output; +- generate `as()` / `tryAs()` / `supports()`. + +### 8.4 CLSID + +A generated coclass usually exports its CLSID as a string: + +```js +import { CLSID_TaskbarList, TaskbarList } from "./generated/com/index.js"; + +console.log(CLSID_TaskbarList); +const value = new TaskbarList(); // The safe wrapper calls CoCreateInstance internally. +value.release(); +``` + +For a handwritten unsafe call, `coCreateInstance()` accepts a CLSID string and an IID: + +```js +import { DynComUnsafe, WinGuid } from "@microsoft/dynwinrt/com/unsafe"; + +const CLSID_FileOperation = "3ad05575-8857-4850-9277-11b85bdb8e09"; +const IID_IFileOperation = WinGuid.parse( + "947aab5f-0a5c-4c13-b4d6-4bf7836fc9f8", +); + +const object = DynComUnsafe.coCreateInstance( + CLSID_FileOperation, + IID_IFileOperation, +); +object.release(); +``` + +### 8.5 A by-value GUID is not a REFIID + +A by-value GUID: + +```js +const value = DynCom.guid(iid); +const type = DynCom.guidType(); +``` + +A REFIID is a `const GUID*`: + +```js +const riid = DynComUnsafe.iidPointer(iid); +``` + +Select the representation that matches the native signature. Treating a by-value GUID as a REFIID, or a REFIID as +a by-value GUID, changes the ABI argument layout. Safe codegen distinguishes them from metadata. For a handwritten +unsafe ABI, the caller is responsible for preserving this distinction. + +## 9. Automation values + +These value types are available from the safe `/com` entry point: + +```js +import { + DynComVariant, + DynComSafeArray, + DynComPropVariant, + WinGuid, +} from "@microsoft/dynwinrt/com"; + +const variant = DynComVariant.bstr("hello"); +const array = DynComSafeArray.i32([1, 2, 3]); +const property = DynComPropVariant.guid( + WinGuid.parse("00000000-0000-0000-c000-000000000046"), +); + +try { + // Pass these values to generated methods. +} finally { + variant.release(); + array.release(); + property.release(); +} +``` + +A SAFEARRAY can preserve nonzero and negative lower bounds: + +```js +const matrix = DynComSafeArray.i32( + [1, 2, 3, 4], + [ + { lowerBound: -2, length: 2 }, + { lowerBound: 5, length: 2 }, + ], +); +``` + +## 10. Handwritten ABI with `com/unsafe` + +### 10.1 When to use it + +Use this API only when all the following conditions are satisfied: + +1. Safe codegen has failed closed. +2. You have the exact native interface IID. +3. You have verified the complete inheritance chain and absolute vtable slot. +4. You have verified every parameter's type, pointer depth, direction, and nullability. +5. You have verified every array's count/capacity/actual-length relationship. +6. You have verified the return convention. +7. You have verified the ownership and cleanup contract for every output. + +### 10.2 Complete example + +The following example manually declares `IFileOperation::SetOperationFlags`. It demonstrates how to write an unsafe +ABI declaration. Production applications should prefer the generated `FileOperation`. + +```js +import { initializeCom } from "@microsoft/dynwinrt/com"; +import { + DynCom, + DynComMethodSig, + DynComUnsafe, + WinGuid, +} from "@microsoft/dynwinrt/com/unsafe"; + +initializeCom(1); + +const CLSID_FileOperation = "3ad05575-8857-4850-9277-11b85bdb8e09"; +const IID_IFileOperation = WinGuid.parse( + "947aab5f-0a5c-4c13-b4d6-4bf7836fc9f8", +); + +const IFileOperation = DynComUnsafe.registerIUnknownInterface( + "Windows.Win32.UI.Shell.IFileOperation", + IID_IFileOperation, +) + // IUnknown occupies slots 0–2; the absolute slot for IFileOperation::SetOperationFlags is 5. + .addMethodAt( + 5, + "SetOperationFlags", + new DynComMethodSig().addIn(DynCom.u32Type()), + ); + +const object = DynComUnsafe.coCreateInstance( + CLSID_FileOperation, + IID_IFileOperation, +); + +try { + const FOF_NO_UI = 0x0614; + IFileOperation.method(5).invoke(object, [DynCom.u32(FOF_NO_UI)]); +} finally { + object.release(); +} +``` + +`DynComUnsafeInterface` intentionally does not provide `addMethod()`. You must use `addMethodAt()` and specify the +exact absolute vtable slot. + +For calls with no output values, the raw `DynComMethodHandle.invoke()` currently returns a placeholder +`DynWinRtValue` whose value is `0`, rather than JavaScript `undefined`. Ignore that return value as shown in the +preceding example. Higher-level generated bindings naturally project such HRESULT methods as `void`. + +### 10.3 Parameter direction + +```js +const signature = new DynComMethodSig() + .addIn(inputType) + .addOut(outputType) + .addInOut(replacementType); +``` + +Available builders: + +| Builder | Native semantics | +| --------------------------------------- | --------------------------------------------------------------- | +| `addIn(type)` | `[in]` | +| `addOut(type)` | Required `[out]` | +| `addOptionalOut(type)` | Nullable `[out]` | +| `addInOut(type)` | `[in, out]` replacement | +| `returns(type)` | Direct native return value | +| `returnsVoid()` | Native `void` return | +| `preserveHresult()` | Preserves a successful HRESULT as a semantic result | +| `preserveEnumeratorNextHresult()` | Preserves enumerator `S_OK`/`S_FALSE` for the default slot 3 | +| `preserveEnumeratorNextHresultAt(slot)` | Preserves an enumerator HRESULT for the specified absolute slot | + +By default, a standard HRESULT method throws for a failing HRESULT and returns its projected result on success. + +### 10.4 Counted buffers + +```js +new DynComMethodSig().addInputBuffer( + DynCom.u8Type(), + countParamIndex, + actualLengthParamIndex, + true, // The count is in bytes. +); +``` + +Related APIs: + +| API | Purpose | +| -------------------------- | ------------------------------------------------- | +| `addInputBuffer` | Caller-provided input array | +| `addCallerOutputBuffer` | Caller allocates capacity; callee writes output | +| `addEnumeratorNextBuffer` | Standard enumerator capacity/fetched relationship | +| `addCoTaskMemOutputBuffer` | Callee allocates with CoTaskMem | +| `addInputStringArray` | Borrowed array of string pointers | + +All parameter indexes refer to the native parameter list, not to JavaScript parameter indexes after hidden +parameters have been removed. + +A standard enumerator must also declare its HRESULT semantics. For example, `IEnumGUID::Next`: + +```js +const next = new DynComMethodSig() + .addIn(DynCom.u32Type()) + .addEnumeratorNextBuffer(DynCom.guidType(), 0, 2) + .addOptionalOut(DynCom.u32Type()) + .preserveEnumeratorNextHresult(); +``` + +Use `preserveEnumeratorNextHresultAt(slot)` for an exact interface whose `Next` method is not in the default slot 3. +Without this return convention, the runtime rejects an EnumeratorNext buffer. + +### 10.5 Pointer output and cleanup + +Select the type explicitly: + +| Type | Semantics | +| ---------------------------- | -------------------------------------------------------------- | +| `unclassifiedPointerType()` | Returns raw bits only; does not release or automatically adopt | +| `borrowedHandleOutputType()` | Borrowed HWND/handle bits; no cleanup | +| `ownedComOutputType()` | Output transfers a COM `+1`; failure paths call `Release` | +| `coTaskMemOutputType()` | Calls `CoTaskMemFree` | +| `bstrOutputType()` | Calls `SysFreeString` | + +Do not map an unknown allocator arbitrarily to the closest available type. + +### 10.6 External COM pointers + +Borrow a pointer and obtain a new managed reference through QI: + +```js +const managed = DynComUnsafe.borrowComPointer(pointerBits, iid); +try { + // managed owns an independent +1 reference. +} finally { + managed.release(); +} +``` + +Consume a `+1` reference that the caller already owns: + +```js +const managed = DynComUnsafe.adoptOwnedComPointer(pointerBits, iid); +``` + +Differences: + +| API | Input ownership | Behavior | +| ---------------------- | --------------------------- | --------------------------------------------------------------- | +| `borrowComPointer` | Caller retains ownership | Calls QueryInterface and returns a new `+1` | +| `adoptOwnedComPointer` | Transfers one existing `+1` | Consumes the reference whether IID validation succeeds or fails | + +Both APIs accept only explicit `bigint` or safe-integer pointer bits. They reject Buffer/Uint8Array backing +addresses to prevent ambiguity between the contents of a Buffer and the address of a Buffer. + +## 11. Error handling + +### 11.1 HRESULT + +A standard failing HRESULT becomes a JavaScript exception: + +```js +try { + object.someMethod(); +} catch (error) { + console.error(error); +} +``` + +Safe generated bindings preserve successful HRESULT values such as `S_FALSE` only when metadata or an exact +registry entry establishes that multiple success values are semantically meaningful. A handwritten unsafe ABI can +call `preserveHresult()` explicitly; the caller is then responsible for interpreting successful status codes +correctly. + +### 11.2 Generation failures + +Common causes include: + +- unknown pointer ownership or allocator; +- incomplete native struct or union layout; +- an unsupported callback or sink; +- an array without a count/actual-length relationship; +- an ambiguous SAFEARRAY/VARIANT/PROPVARIANT element type; +- an unresolved interface IID or inheritance chain; +- unmodeled `STGMEDIUM`, complex union, or resource lifetime. + +These errors define a safety boundary and should not be bypassed with type assertions. Use `/com/unsafe` only after +verifying the complete native ABI. + +## 12. Frequently asked questions + +### Can I pass a GUID string directly to a runtime API that requires an IID? + +No. `registerIUnknownInterface()`, `interfaceType()`, and similar APIs require a `WinGuid`. Call `WinGuid.parse()` +first. Parameters explicitly typed as a CLSID `string` are the exception. + +### Why isn't `IID_*` an ordinary string? + +The runtime requires a value that has already been parsed, validated, and stored in native GUID layout. Call +`.toString()` for logging or serialization. + +### Can I use a random UUID as an IID? + +Only when you implement and control the corresponding COM interface. When calling an existing Windows interface, +the IID must exactly match the interface definition. + +### Why doesn't `WinGuid` expose public fields? + +It is an opaque value object for a native GUID. Hiding its fields prevents JavaScript numeric-precision, byte-order, +and structure-layout errors. + +### Why doesn't the default `/com` entry point export `DynComMethodSig`? + +Handwritten signatures, vtable slots, and pointer cleanup are unsafe ABI operations. Safe generated code uses +`/com/unsafe` internally, while applications see only validated, high-level methods. + +### Can Classic COM call ordinary Win32 DLL functions? + +No. Flat DLL exports such as `CreateFileW`, registry APIs, and GDI APIs are not COM vtables. They require a separate +Win32 DLL and handle model. + +## 13. Additional resources + +- [Classic COM support scope and architecture](classic-com-support.md) +- [Microsoft COM documentation](https://learn.microsoft.com/windows/win32/com/component-object-model--com--portal) +- [COM interface rules](https://learn.microsoft.com/windows/win32/com/com-interface-rules) +- [COM error handling](https://learn.microsoft.com/windows/win32/com/error-handling-in-com) diff --git a/tests/e2e_test.ps1 b/tests/e2e_test.ps1 index 9dc94c9c..e2161168 100644 --- a/tests/e2e_test.ps1 +++ b/tests/e2e_test.ps1 @@ -29,6 +29,7 @@ $comBindingsDir = Join-Path $e2eDir "com" $comShellDir = Join-Path $comBindingsDir "shell" $comInteropDir = Join-Path $comBindingsDir "interop" $comWicDir = Join-Path $comBindingsDir "wic" +$comStreamDir = Join-Path $comBindingsDir "stream" $comSmtcDir = Join-Path $comBindingsDir "smtc" $env:PATH = "$env:USERPROFILE\.cargo\bin;$env:PATH" @@ -176,13 +177,13 @@ foreach ($l in @($Lang | Where-Object { $_ -in @("py", "ts") })) { if ("com" -in $Lang) { Write-Host "`n--- Generate (Classic COM) ---" -ForegroundColor Yellow - $comRuntimeImport = "../../../../../bindings/js/dist/com.js" + $comRuntimeImport = "../../../../../bindings/js/dist/com-unsafe.js" $winrtRuntimeImport = "../../../../bindings/js/dist/winrt.js" & cargo run -p dynwinrt-codegen --release --quiet -- generate ` --winmd $win32Winmd ` --namespace Windows.Win32.UI.Shell ` - --class-name "TaskbarList,IDataTransferManagerInterop,FileOperation,FileOpenDialog" ` + --class-name "TaskbarList,IShellLinkW,IDataTransferManagerInterop,FileOperation,FileOpenDialog" ` --output $comShellDir ` --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM Shell generation failed"; exit 1 } @@ -211,6 +212,14 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM WIC generation failed"; exit 1 } + & cargo run -p dynwinrt-codegen --release --quiet -- generate ` + --winmd $win32Winmd ` + --namespace Windows.Win32.System.Com ` + --class-name ISequentialStream ` + --output $comStreamDir ` + --import-name $comRuntimeImport + if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM stream generation failed"; exit 1 } + & cargo run -p dynwinrt-codegen --release --quiet -- generate ` --namespace Windows.Media ` --class-name SystemMediaTransportControls ` @@ -272,9 +281,11 @@ if ("com" -in $Lang) { "taskbarlist.mjs", "electron-hwnd-buffer.mjs", "persist-file.mjs", + "shell-link-pod.mjs", "file-operation.mjs", "file-open-dialog.mjs", "wic-imaging-factory.mjs", + "sequential-stream-buffer.mjs", "dtm.mjs", "smtc.mjs" ) diff --git a/tests/runners/com/dtm.mjs b/tests/runners/com/dtm.mjs index 9dd8696f..bbdb52e5 100644 --- a/tests/runners/com/dtm.mjs +++ b/tests/runners/com/dtm.mjs @@ -6,7 +6,7 @@ // IDataTransferManagerInterop::GetForWindow(HWND, REFIID, void**) // Run: .\tests\e2e_test.ps1 -SkipBuild -Lang com -import { DynCom, DynComMethodSig, WinGuid } from '../../../bindings/js/dist/com.js'; +import { DynCom, DynComMethodSig, WinGuid } from '../../../bindings/js/dist/com-unsafe.js'; import { IDataTransferManagerInterop } from '../../e2e_generated/com/shell/com/IDataTransferManagerInterop.js'; import { acquireHwndBigInt } from './hwnd.mjs'; diff --git a/tests/runners/com/file-open-dialog.mjs b/tests/runners/com/file-open-dialog.mjs index 5cfd2655..d0d8dde8 100644 --- a/tests/runners/com/file-open-dialog.mjs +++ b/tests/runners/com/file-open-dialog.mjs @@ -2,7 +2,7 @@ // Licensed under the MIT License. import assert from 'node:assert/strict'; -import { DynCom } from '../../../bindings/js/dist/com.js'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; import { FileOpenDialog } from '../../e2e_generated/com/shell/com/FileOpenDialog.js'; DynCom.initialize(0); diff --git a/tests/runners/com/file-operation.mjs b/tests/runners/com/file-operation.mjs index a0791d11..b2a4a57b 100644 --- a/tests/runners/com/file-operation.mjs +++ b/tests/runners/com/file-operation.mjs @@ -2,7 +2,7 @@ // Licensed under the MIT License. import assert from 'node:assert/strict'; -import { DynCom } from '../../../bindings/js/dist/com.js'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; import { FILEOPERATION_FLAGS } from '../../e2e_generated/com/shell/com/FILEOPERATION_FLAGS.js'; import { FileOperation } from '../../e2e_generated/com/shell/com/FileOperation.js'; diff --git a/tests/runners/com/hwnd.mjs b/tests/runners/com/hwnd.mjs index 4afa0c1f..0f797652 100644 --- a/tests/runners/com/hwnd.mjs +++ b/tests/runners/com/hwnd.mjs @@ -11,7 +11,7 @@ // napi `createTestHwnd()` export, which creates a hidden `WS_POPUP` // window in the Node process using the pre-registered `STATIC` class. -import { DynCom } from '../../../bindings/js/dist/com.js'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; import { roInitialize } from '../../../bindings/js/dist/winrt.js'; roInitialize(1); diff --git a/tests/runners/com/module-commonjs.cjs b/tests/runners/com/module-commonjs.cjs index c18a5c7e..3cc98563 100644 --- a/tests/runners/com/module-commonjs.cjs +++ b/tests/runners/com/module-commonjs.cjs @@ -2,7 +2,7 @@ // Licensed under the MIT License. const assert = require('node:assert/strict'); -const { DynCom } = require('../../../bindings/js/dist/com.js'); +const { DynCom } = require('../../../bindings/js/dist/com-unsafe.js'); const barrel = require('../../e2e_generated/com/shell/com/index.js'); const deep = require('../../e2e_generated/com/shell/com/TaskbarList.js'); diff --git a/tests/runners/com/persist-file.mjs b/tests/runners/com/persist-file.mjs index 25c5ff0b..2e4d20cc 100644 --- a/tests/runners/com/persist-file.mjs +++ b/tests/runners/com/persist-file.mjs @@ -2,7 +2,7 @@ // Licensed under the MIT License. import assert from 'node:assert/strict'; -import { DynCom } from '../../../bindings/js/dist/com.js'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; import { IID_IPersistFile, IPersistFile, diff --git a/tests/runners/com/pointer-reject-object.mjs b/tests/runners/com/pointer-reject-object.mjs index 30be9322..61186df9 100644 --- a/tests/runners/com/pointer-reject-object.mjs +++ b/tests/runners/com/pointer-reject-object.mjs @@ -2,7 +2,7 @@ // DynWinRtValue inputs. Borrowing an owned COM object's raw pointer here would // make it indistinguishable from an owned raw pointer to adoptComPointer(), // which can double-release the original wrapper's COM object. -import { DynCom, WinGuid } from '../../../bindings/js/dist/com.js'; +import { DynCom, WinGuid } from '../../../bindings/js/dist/com-unsafe.js'; // iidPointer() returns a DynWinRtValue — a representative value input. const someValue = DynCom.iidPointer(WinGuid.parse('a5caee9b-8708-49d1-8d36-67d25a8da00c')); diff --git a/tests/runners/com/sequential-stream-buffer.mjs b/tests/runners/com/sequential-stream-buffer.mjs new file mode 100644 index 00000000..bea1be33 --- /dev/null +++ b/tests/runners/com/sequential-stream-buffer.mjs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict'; +import { DynCom, DynComMethodSig, WinGuid } from '../../../bindings/js/dist/com-unsafe.js'; +import { + IID_ISequentialStream, + ISequentialStream, +} from '../../e2e_generated/com/stream/com/ISequentialStream.js'; +import { + IID_IWICImagingFactory, + IWICImagingFactory, +} from '../../e2e_generated/com/wic/com/IWICImagingFactory.js'; + +const CLSID_WIC_IMAGING_FACTORY = 'cacaf262-9370-4615-a13b-9f5539da4c0a'; +const IID_IWIC_STREAM = WinGuid.parse('135ff860-22b7-4ddf-b0f6-218f4f299a43'); + +DynCom.initialize(1); + +const factory = IWICImagingFactory._fromNative( + DynCom.coCreateInstance(CLSID_WIC_IMAGING_FACTORY, IID_IWICImagingFactory), +); +const stream = factory.createStream(); +// IWICStream inherits the complete IStream vtable; InitializeFromMemory is slot 16. +const wicStream = DynCom.registerIUnknownInterface( + 'Windows.Win32.Graphics.Imaging.IWICStream', + IID_IWIC_STREAM, +).addMethodAt( + 16, + 'InitializeFromMemory', + new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()), +); + +const expected = Buffer.from('phase8 counted buffer', 'utf8'); +wicStream + .method(16) + .invoke(stream, [DynCom.pointer(expected), DynCom.u32(expected.length)]); + +const sequential = ISequentialStream._fromNative(stream.cast(IID_ISequentialStream)); +const [hresult, actual] = sequential.read(Buffer.alloc(expected.length)); +assert.equal(hresult, 0); +assert.deepEqual(actual, expected); + +sequential.release(); +stream.release(); +factory.release(); + +console.log('sequential-stream-buffer ok'); diff --git a/tests/runners/com/shell-link-pod.mjs b/tests/runners/com/shell-link-pod.mjs new file mode 100644 index 00000000..5293404b --- /dev/null +++ b/tests/runners/com/shell-link-pod.mjs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; +import { + createWIN32_FIND_DATAW, + IID_IShellLinkW, + IShellLinkW, +} from '../../e2e_generated/com/shell/com/IShellLinkW.js'; + +const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; +const SLGP_RAWPATH = 4; + +DynCom.initialize(1); + +const link = IShellLinkW._fromNative( + DynCom.coCreateInstance(CLSID_SHELL_LINK, IID_IShellLinkW), +); +const expected = process.execPath; +link.setPath(expected); + +const findData = createWIN32_FIND_DATAW(); +assert.equal(findData.length, 592); +assert.deepEqual(findData.bytes, Buffer.alloc(592)); + +const [actual, returnedFindData] = link.getPath(32768, findData, SLGP_RAWPATH); +assert.equal(actual.toLowerCase(), expected.toLowerCase()); +assert.equal(returnedFindData.length, 592); + +link.release(); +console.log('shell-link-pod ok'); diff --git a/tests/runners/com/smtc.mjs b/tests/runners/com/smtc.mjs index 4cb90582..d241acd0 100644 --- a/tests/runners/com/smtc.mjs +++ b/tests/runners/com/smtc.mjs @@ -15,7 +15,7 @@ // // Run: .\tests\e2e_test.ps1 -SkipBuild -Lang com -import { DynCom, DynComMethodSig, WinGuid } from '../../../bindings/js/dist/com.js'; +import { DynCom, DynComMethodSig, WinGuid } from '../../../bindings/js/dist/com-unsafe.js'; // Classic-COM interop wrapper: gets the SMTC pointer from an HWND. import { ISystemMediaTransportControlsInterop } from '../../e2e_generated/com/interop/com/ISystemMediaTransportControlsInterop.js'; import { acquireHwndBigInt } from './hwnd.mjs'; diff --git a/tests/runners/com/wic-imaging-factory.mjs b/tests/runners/com/wic-imaging-factory.mjs index b6551df0..d78a1c8b 100644 --- a/tests/runners/com/wic-imaging-factory.mjs +++ b/tests/runners/com/wic-imaging-factory.mjs @@ -2,7 +2,7 @@ // Licensed under the MIT License. import assert from 'node:assert/strict'; -import { DynCom } from '../../../bindings/js/dist/com.js'; +import { DynCom } from '../../../bindings/js/dist/com-unsafe.js'; import { IID_IWICImagingFactory, IWICImagingFactory, diff --git a/tools/dynwinrt-codegen/Cargo.toml b/tools/dynwinrt-codegen/Cargo.toml index 7df94d58..b41fc056 100644 --- a/tools/dynwinrt-codegen/Cargo.toml +++ b/tools/dynwinrt-codegen/Cargo.toml @@ -15,3 +15,21 @@ regex = "1" [dev-dependencies] regex = "1" + +[dev-dependencies.windows] +version = "0.62.2" +features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D_Dxc", + "Win32_Graphics_DirectComposition", + "Win32_Graphics_DirectManipulation", + "Win32_Media_MediaFoundation", + "Win32_Storage_FileSystem", + "Win32_System_Com", + "Win32_System_Ole", + "Win32_System_Variant", + "Win32_System_WinRT", + "Win32_UI_Accessibility", + "Win32_UI_Shell", + "Win32_UI_WindowsAndMessaging", +] diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 32bafc09..7cc2751f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -55,6 +55,109 @@ pub(super) enum PointerAliasKind { StringPointer(StringEncoding), } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum SafeArrayElement { + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + Bool, + Bstr, + Interface { iid: [u8; 16] }, + Variant, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum NativePodScalar { + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + NativeIsize, + NativeUsize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum NativePodFieldType { + Scalar(NativePodScalar), + Guid, + Pointer, + Struct { + name: String, + layout: Box, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativePodField { + pub(super) name: String, + pub(super) offset: usize, + pub(super) count: u32, + pub(super) typ: NativePodFieldType, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativePodArchitectureLayout { + pub(super) size: usize, + pub(super) alignment: usize, + pub(super) fields: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativePodLayout { + pub(super) namespace: String, + pub(super) name: String, + pub(super) x86: NativePodArchitectureLayout, + pub(super) x64: NativePodArchitectureLayout, + pub(super) arm64: NativePodArchitectureLayout, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum NativeUnionFieldType { + Scalar(NativePodScalar), + Guid, + Pointer, + Struct { + name: String, + layout: Box, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativeUnionField { + pub(super) name: String, + pub(super) count: u32, + pub(super) typ: NativeUnionFieldType, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativeUnionArchitectureLayout { + pub(super) size: usize, + pub(super) alignment: usize, + pub(super) fields: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct NativeUnionLayout { + pub(super) namespace: String, + pub(super) name: String, + pub(super) x86: NativeUnionArchitectureLayout, + pub(super) x64: NativeUnionArchitectureLayout, + pub(super) arm64: NativeUnionArchitectureLayout, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ComType { Primitive(ComPrimitive), @@ -65,22 +168,55 @@ pub(super) enum ComType { Guid, HString, Enum { + namespace: String, name: String, underlying: ComEnumUnderlying, }, ScalarAlias { + namespace: String, name: String, underlying: ComScalarRepr, }, RawPointer, PointerAlias { + namespace: String, name: String, kind: PointerAliasKind, }, + NativePod { + layout: NativePodLayout, + }, + NativePodPointer { + layout: NativePodLayout, + }, + NativeUnionPointer { + layout: NativeUnionLayout, + }, Bstr, + Variant, + VariantByValue, + SafeArray { + element: SafeArrayElement, + }, + PropVariant, + DispatchParams, + ExcepInfo, ManagedInterface { iid: String, }, + CoTaskMemWideString, + StringArray { + encoding: StringEncoding, + element_pointer_depth: u8, + element_const: bool, + }, + TypedBuffer { + element: Box, + }, + OwningArray { + element: Box, + interface: Option, + }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -102,13 +238,20 @@ pub(super) enum UnsupportedComType { pub(super) enum ComParamDirection { In, Out, + OptionalOut, InOut, OutStringBuffer, + InputBuffer, + CallerOutputBuffer, + CalleeAllocatedBuffer, } impl ComParamDirection { pub(super) fn is_input(self) -> bool { - matches!(self, Self::In | Self::InOut) + matches!( + self, + Self::In | Self::InOut | Self::InputBuffer | Self::CallerOutputBuffer + ) } } @@ -117,12 +260,16 @@ pub(super) struct ProjectedComParam { pub(super) name: String, pub(super) typ: ComType, pub(super) direction: ComParamDirection, + pub(super) surface_input: bool, + pub(super) surface_result: bool, + pub(super) nullable: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ComReturnConvention { HResult, SemanticHResult, + DispatchInvokeHResult, Void, Direct(ComType), } @@ -130,12 +277,25 @@ pub(super) enum ComReturnConvention { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ResultConversion { Value, + BorrowedHandle, ManagedCom, Bstr, CoTaskMemString(StringEncoding), CoTaskMemData, HString, DynamicIidAdoption, + Buffer, + PlainArray, + EnumeratorArray { + interface: Option, + }, + OwningArray { + interface: Option, + }, + Variant, + SafeArray, + PropVariant, + ExcepInfo, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -159,16 +319,101 @@ pub(super) struct StringBufferPlan { pub(super) optional_param_indices: Vec, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum BufferCountUnit { + Elements, + Bytes, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum TypedBufferSizing { + SingleCall, + FixedCapacity, + TwoCall { max_retries: u8 }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum TypedBufferRelation { + Input { + count_param_index: usize, + actual_length_param_index: Option, + unit: BufferCountUnit, + }, + CallerOutput { + capacity_param_index: usize, + actual_length_param_index: Option, + unit: BufferCountUnit, + sizing: TypedBufferSizing, + }, + EnumeratorNext { + capacity_param_index: usize, + fetched_param_index: usize, + fetched_optional_for_single: bool, + }, + CalleeAllocated { + count_param_index: usize, + unit: BufferCountUnit, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct TypedBufferPlan { + pub(super) buffer_param_index: usize, + pub(super) element: ComType, + pub(super) relation: TypedBufferRelation, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum SharedCountPlan { + StringInputScalarOutput { + count_param_index: usize, + string_input_param_index: usize, + scalar_output_param_index: usize, + }, + Parallel { + count_param_index: usize, + input_param_indices: Vec, + output_param_indices: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(super) struct ProjectedInterfaceRef { + pub(super) namespace: String, + pub(super) name: String, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ProjectedComMethodKind { Normal, + FixedCapacityBytes { + guid_param_index: usize, + }, CallerSuppliedDynamicIid { - natural_param_count: usize, + iid_param_index: usize, + output_param_index: usize, }, SynthesizedGetForWindow { - natural_param_count: usize, + iid_param_index: usize, + output_param_index: usize, target_iid: String, }, + DispatchInvoke { + result_param_index: usize, + excep_info_param_index: usize, + arg_err_param_index: usize, + }, + EnumeratorNext { + buffer_param_index: usize, + capacity_param_index: usize, + fetched_param_index: usize, + fetched_optional_for_single: bool, + interface: Option, + }, + OwningCallerOutput { + buffer_param_index: usize, + capacity_param_index: usize, + }, } /// The JS runtime `typeof`/shape category a validated value uses at a call @@ -223,6 +468,8 @@ pub(super) struct ProjectedComMethod { pub(super) return_convention: ComReturnConvention, pub(super) results: Vec, pub(super) string_buffer: Option, + pub(super) typed_buffers: Vec, + pub(super) shared_counts: Vec, pub(super) kind: ProjectedComMethodKind, pub(super) doc: Option, pub(super) overload: Option, @@ -262,12 +509,26 @@ pub(super) fn dispatch_shape(typ: &ComType) -> Option { | ComScalarRepr::NativeUsize => Some(DispatchShape::BigInt), ComScalarRepr::Primitive(_) => Some(DispatchShape::Number), }, - ComType::ManagedInterface { .. } => Some(DispatchShape::Object), + ComType::ManagedInterface { .. } | ComType::DispatchParams => Some(DispatchShape::Object), // Raw/aliased pointers and BSTR accept multiple overlapping JS input // shapes (`bigint`, `number`, `Buffer`, `Uint8Array`, or `string`) // depending on position, so they can collide with any other category // and are never safe overload-dispatch keys. - ComType::RawPointer | ComType::PointerAlias { .. } | ComType::Bstr => None, + ComType::RawPointer + | ComType::PointerAlias { .. } + | ComType::NativePod { .. } + | ComType::NativePodPointer { .. } + | ComType::NativeUnionPointer { .. } + | ComType::Variant + | ComType::VariantByValue + | ComType::SafeArray { .. } + | ComType::PropVariant + | ComType::ExcepInfo + | ComType::Bstr + | ComType::CoTaskMemWideString + | ComType::StringArray { .. } + | ComType::TypedBuffer { .. } + | ComType::OwningArray { .. } => None, } } @@ -299,6 +560,7 @@ pub(super) struct ProjectedComEnumMember { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ProjectedComEnum { + pub(super) namespace: String, pub(super) name: String, pub(super) underlying: ComEnumUnderlying, pub(super) members: Vec, diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index df2cedda..9915df5e 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -8,14 +8,20 @@ use std::collections::BTreeMap; #[cfg(test)] use super::super::ir::ProjectedComEnumMember; use super::super::ir::{ - ActivationPlan, ComEnumUnderlying, ComParamDirection, ComReturnConvention, ComType, - DispatchShape, OverloadDispatch, PointerAliasKind, ProjectedComCoclass, ProjectedComEnum, - ProjectedComInterface, ProjectedComMethod, ProjectedComMethodKind, ProjectedComParam, - ProjectedEnumValue, ResultConversion, ResultSource, StringEncoding, + ActivationPlan, BufferCountUnit, ComEnumUnderlying, ComParamDirection, ComPrimitive, + ComReturnConvention, ComType, DispatchShape, OverloadDispatch, PointerAliasKind, + ProjectedComCoclass, ProjectedComEnum, ProjectedComInterface, ProjectedComMethod, + ProjectedComMethodKind, ProjectedComParam, ProjectedComResult, ProjectedEnumValue, + ProjectedInterfaceRef, ResultConversion, ResultSource, SharedCountPlan, StringEncoding, + TypedBufferPlan, TypedBufferRelation, TypedBufferSizing, }; use super::naming::js_param_name; +#[cfg(test)] +use super::types::type_dts; use super::types::{ - abi_type_js, input_type_dts, result_type_dts, scalar_type_dts, unwrap_result_js, wrap_arg_js, + abi_type_js, input_type_dts, native_pod_descriptor_js, native_pod_layout_js, + native_union_descriptor_js, native_union_layout_js, result_type_dts, safe_array_abi_type_js, + scalar_type_dts, unwrap_result_js, wrap_arg_js, }; use crate::codegen::winrt::javascript::render::javascript::commonjs::convert_to_cjs_with_eager; @@ -58,7 +64,11 @@ pub(in crate::codegen::com) fn render_com_coclass( extra_files.insert(format!("{}.js", interface.name), output.js); extra_files.insert(format!("{}.d.ts", interface.name), output.dts); for (name, content) in output.extra_files { - extra_files.entry(name).or_insert(content); + if let Some(existing) = extra_files.insert(name.clone(), content.clone()) + && existing != content + { + panic!("validated coclass emitted conflicting `{name}` files"); + } } } ComGeneratedOutput { @@ -149,7 +159,55 @@ fn render_js(meta: &ProjectedComInterface) -> String { en.name, en.name )); } + for interface in collect_enumerator_interfaces(meta) { + if interface.name != meta.name || interface.namespace != meta.namespace { + out.push_str(&format!( + "import {{ {} }} from './{}.js';\n", + interface.name, interface.name + )); + } + } out.push('\n'); + let native_pods = collect_native_pods(meta); + let native_pod_arrays = collect_native_pod_arrays(meta); + for layout in &native_pods { + out.push_str(&format!( + "const {} = {};\n", + native_pod_layout_js(layout), + native_pod_descriptor_js(layout) + )); + out.push_str(&format!( + "export function create{}(bytes) {{ return DynCom.createNativeStruct({}, bytes); }}\n", + layout.name, + native_pod_layout_js(layout) + )); + if native_pod_arrays.contains(&(layout.namespace.clone(), layout.name.clone())) { + out.push_str(&format!( + "export function create{}Array(bytes) {{ return DynCom.createNativeStructArray({}, bytes); }}\n", + layout.name, + native_pod_layout_js(layout) + )); + } + } + if !native_pods.is_empty() { + out.push('\n'); + } + let native_unions = collect_native_unions(meta); + for layout in &native_unions { + out.push_str(&format!( + "const {} = {};\n", + native_union_layout_js(layout), + native_union_descriptor_js(layout) + )); + out.push_str(&format!( + "export function create{}(activeField, bytes) {{ return DynCom.createNativeUnion({}, activeField, bytes); }}\n", + layout.name, + native_union_layout_js(layout) + )); + } + if !native_unions.is_empty() { + out.push('\n'); + } if meta .methods .iter() @@ -221,7 +279,7 @@ fn render_js(meta: &ProjectedComInterface) -> String { .. } => { let full = format!("{class_namespace}.{class_name}"); - out.push_str(&format!(" /** Create a new `{}` by activating the `{full}` factory and QI'ing to the interop.\n * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */\n", meta.name)); + out.push_str(&format!(" /** Create a new `{}` by activating the `{full}` factory and QI'ing to the interop.\n * `initializeCom()` must be called once (e.g. at process startup) before this is used. */\n", meta.name)); out.push_str(&format!(" static create() {{\n const factory = DynWinRtValue.activationFactory('{full}');\n const _obj = factory.cast(IID_{});\n return new {}(_obj);\n }}\n", meta.name, meta.name)); } } @@ -247,21 +305,49 @@ fn render_js(meta: &ProjectedComInterface) -> String { continue; } match method.kind { - ProjectedComMethodKind::Normal => emit_method_js(&mut out, method, &iface_var), + ProjectedComMethodKind::Normal + | ProjectedComMethodKind::FixedCapacityBytes { .. } + | ProjectedComMethodKind::OwningCallerOutput { .. } => { + emit_method_js(&mut out, method, &iface_var) + } ProjectedComMethodKind::CallerSuppliedDynamicIid { - natural_param_count, - } => emit_dynamic_iid_method_js(&mut out, method, natural_param_count, &iface_var), + iid_param_index, + output_param_index, + } => emit_dynamic_iid_method_js( + &mut out, + method, + iid_param_index, + output_param_index, + &iface_var, + ), ProjectedComMethodKind::SynthesizedGetForWindow { - natural_param_count, + iid_param_index, + output_param_index, ref target_iid, } => emit_synthesized_interop_method_js( &mut out, method, - natural_param_count, + iid_param_index, + output_param_index, target_iid, &iface_var, meta, ), + ProjectedComMethodKind::DispatchInvoke { + result_param_index, + excep_info_param_index, + arg_err_param_index, + } => emit_dispatch_invoke_method_js( + &mut out, + method, + result_param_index, + excep_info_param_index, + arg_err_param_index, + &iface_var, + ), + ProjectedComMethodKind::EnumeratorNext { .. } => { + emit_enumerator_next_method_js(&mut out, method, &iface_var) + } } } out.push_str("}\n"); @@ -271,11 +357,20 @@ fn render_js(meta: &ProjectedComInterface) -> String { fn build_method_sig_js(method: &ProjectedComMethod) -> String { let mut parts = Vec::new(); for (index, param) in method.params.iter().enumerate() { + if let Some(plan) = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == index) + { + parts.push(typed_buffer_signature_js(plan)); + continue; + } match param.direction { - ComParamDirection::In => parts.push(format!(".addIn({})", abi_type_js(¶m.typ))), + ComParamDirection::In => parts.push(format!(".addIn({})", param_abi_type_js(param))), ComParamDirection::InOut => { - parts.push(format!(".addInOut({})", abi_type_js(¶m.typ))) + parts.push(format!(".addInOut({})", param_abi_type_js(param))) } + ComParamDirection::OutStringBuffer => parts.push(".addIn(DynCom.pointerType())".into()), ComParamDirection::Out => { if method.string_buffer.as_ref().is_some_and(|plan| { @@ -289,11 +384,108 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { )); } } + ComParamDirection::OptionalOut => { + parts.push(format!( + ".addOptionalOut({})", + out_abi_type_js(method, index, ¶m.typ) + )); + } + ComParamDirection::InputBuffer + | ComParamDirection::CallerOutputBuffer + | ComParamDirection::CalleeAllocatedBuffer => { + unreachable!("typed buffer parameters have an explicit signature plan") + } + } + } + + fn typed_buffer_signature_js(plan: &TypedBufferPlan) -> String { + match plan.relation { + TypedBufferRelation::Input { + count_param_index, + actual_length_param_index, + unit, + } => { + if let ComType::StringArray { encoding, .. } = plan.element { + assert_eq!(actual_length_param_index, None); + assert_eq!(unit, BufferCountUnit::Elements); + format!( + ".addInputStringArray({}, {count_param_index})", + matches!(encoding, StringEncoding::Wide) + ) + } else { + let element = abi_type_js(&plan.element); + format!( + ".addInputBuffer({element}, {count_param_index}, {}, {})", + optional_index_js(actual_length_param_index), + count_unit_is_bytes(unit) + ) + } + } + TypedBufferRelation::CallerOutput { + capacity_param_index, + actual_length_param_index, + unit, + sizing, + } => { + let element = abi_type_js(&plan.element); + format!( + ".addCallerOutputBuffer({element}, {capacity_param_index}, {}, {}, {})", + optional_index_js(actual_length_param_index), + count_unit_is_bytes(unit), + matches!(sizing, TypedBufferSizing::TwoCall { .. }) + ) + } + TypedBufferRelation::EnumeratorNext { + capacity_param_index, + fetched_param_index, + .. + } => { + let element = abi_type_js(&plan.element); + format!( + ".addEnumeratorNextBuffer({element}, {capacity_param_index}, {fetched_param_index})" + ) + } + TypedBufferRelation::CalleeAllocated { + count_param_index, + unit, + } => { + let element = abi_type_js(&plan.element); + format!( + ".addCoTaskMemOutputBuffer({element}, {count_param_index}, {})", + count_unit_is_bytes(unit) + ) + } + } + } + + fn optional_index_js(index: Option) -> String { + index.map_or_else(|| "undefined".into(), |index| index.to_string()) + } + + fn count_unit_is_bytes(unit: BufferCountUnit) -> bool { + match unit { + BufferCountUnit::Elements => false, + BufferCountUnit::Bytes => true, } } match &method.return_convention { ComReturnConvention::HResult => {} + ComReturnConvention::SemanticHResult + if matches!(method.kind, ProjectedComMethodKind::EnumeratorNext { .. }) => + { + if method.vtable_index == 3 { + parts.push(".preserveEnumeratorNextHresult()".into()) + } else { + parts.push(format!( + ".preserveEnumeratorNextHresultAt({})", + method.vtable_index + )) + } + } ComReturnConvention::SemanticHResult => parts.push(".preserveHresult()".into()), + ComReturnConvention::DispatchInvokeHResult => { + parts.push(".captureDispatchInvokeHresult()".into()) + } ComReturnConvention::Void => parts.push(".returnsVoid()".into()), ComReturnConvention::Direct(typ) => parts.push(format!(".returns({})", abi_type_js(typ))), } @@ -311,7 +503,56 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { /// Any pointer output that isn't classified with a known ownership contract /// falls back to the unclassified `pointerType()`, which the runtime does not /// allow callers to adopt as an owned value. +fn param_abi_type_js(param: &ProjectedComParam) -> String { + if param.nullable && param.typ == ComType::Bstr { + return "DynCom.nullableBstrType()".into(); + } + if param.nullable + && let ComType::NativePodPointer { layout } = ¶m.typ + { + return format!( + "DynCom.nativeStructPointerType({}, true)", + native_pod_layout_js(layout) + ); + } + abi_type_js(¶m.typ) +} + +fn wrap_param_arg_js(param: &ProjectedComParam, variable: &str) -> String { + let wrapped = wrap_arg_js(¶m.typ, variable); + if param.nullable { + return match param.typ { + ComType::NativePodPointer { .. } => { + format!("{variable} === null ? DynCom.nullNativeStructPointer() : {wrapped}") + } + ComType::ManagedInterface { .. } => { + format!("{variable} === null ? DynCom.nullComValue() : {wrapped}") + } + ComType::RawPointer | ComType::PointerAlias { .. } => { + format!("{variable} === null ? DynCom.pointer(null) : {wrapped}") + } + ComType::Bstr => format!("{variable} === null ? DynCom.nullBstr() : {wrapped}"), + _ => unreachable!("nullable projection was validated"), + }; + } + wrapped +} + +fn param_input_type_dts(param: &ProjectedComParam) -> String { + let typ = input_type_dts(¶m.typ); + if param.nullable { + format!("{typ} | null") + } else { + typ + } +} + fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComType) -> String { + if method.params[param_index].nullable + && let ComType::SafeArray { element } = typ + { + return safe_array_abi_type_js(*element, true); + } let conversion = method .results .iter() @@ -319,12 +560,23 @@ fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComTyp .map(|result| &result.conversion); match conversion { Some(ResultConversion::DynamicIidAdoption) => "DynCom.ownedComPointerType()".into(), - Some(ResultConversion::Bstr) => "DynCom.bstrPointerType()".into(), + Some(ResultConversion::BorrowedHandle) => "DynCom.borrowedHandleOutputType()".into(), + Some(ResultConversion::Bstr) => "DynCom.bstrType()".into(), Some(ResultConversion::CoTaskMemString(_) | ResultConversion::CoTaskMemData) => { "DynCom.coTaskMemPointerType()".into() } Some( - ResultConversion::ManagedCom | ResultConversion::HString | ResultConversion::Value, + ResultConversion::ManagedCom + | ResultConversion::HString + | ResultConversion::Value + | ResultConversion::Buffer + | ResultConversion::PlainArray + | ResultConversion::EnumeratorArray { .. } + | ResultConversion::OwningArray { .. } + | ResultConversion::Variant + | ResultConversion::SafeArray + | ResultConversion::PropVariant + | ResultConversion::ExcepInfo, ) | None => abi_type_js(typ), } @@ -335,7 +587,7 @@ fn input_params(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> .params .iter() .enumerate() - .filter(|(_, param)| param.direction.is_input()) + .filter(|(_, param)| param.surface_input) .collect() } @@ -344,6 +596,144 @@ fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str emit_method_js_named(out, method, iface_var, &method.camel_name); } +fn emit_dispatch_invoke_method_js( + out: &mut String, + method: &ProjectedComMethod, + result_param_index: usize, + excep_info_param_index: usize, + arg_err_param_index: usize, + iface_var: &str, +) { + let inputs = input_params(method); + let mut params = inputs + .iter() + .enumerate() + .map(|(surface, (_, param))| js_param_name(¶m.name, surface)) + .collect::>(); + params.push("options = {}".into()); + out.push_str(&format!( + " {}({}) {{\n", + method.camel_name, + params.join(", ") + )); + for option in ["result", "excepInfo", "argErr"] { + out.push_str(&format!( + " if (options.{option} !== undefined && typeof options.{option} !== 'boolean') throw new TypeError('IDispatch Invoke option `{option}` must be boolean');\n" + )); + } + out.push_str(" const _requestResult = options.result ?? true;\n"); + out.push_str(" const _requestExcepInfo = options.excepInfo ?? true;\n"); + out.push_str(" const _requestArgErr = options.argErr ?? true;\n"); + + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| match param.direction { + ComParamDirection::OptionalOut if index == result_param_index => { + Some("DynCom.boolValue(_requestResult)".into()) + } + ComParamDirection::OptionalOut if index == excep_info_param_index => { + Some("DynCom.boolValue(_requestExcepInfo)".into()) + } + ComParamDirection::OptionalOut if index == arg_err_param_index => { + Some("DynCom.boolValue(_requestArgErr)".into()) + } + ComParamDirection::OptionalOut => { + unreachable!("validated IDispatch::Invoke has exactly three optional outputs") + } + _ if param.surface_input => { + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible dispatch input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + } + _ => None, + }) + .collect::>(); + out.push_str(&format!( + " const _call = {iface_var}.method({}).invokeDispatch(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + out.push_str(" const _resultValue = _call.takeResult();\n"); + out.push_str(" const _excepInfoValue = _call.takeExcepInfo();\n"); + out.push_str(" if (_call.hresult < 0) {\n"); + out.push_str(" const _excepInfo = _excepInfoValue == null ? undefined : DynCom.takeExcepInfo(_excepInfoValue);\n"); + out.push_str(" const _hresult = `0x${(_call.hresult >>> 0).toString(16).padStart(8, '0').toUpperCase()}`;\n"); + out.push_str(" const _description = _excepInfo?.description;\n"); + out.push_str(" const _error = new Error(`IDispatch::Invoke failed with HRESULT ${_hresult}${_description ? `: ${_description}` : ''}`);\n"); + out.push_str(" _error.hresult = _call.hresult;\n"); + out.push_str(" if (_excepInfo !== undefined) _error.excepInfo = _excepInfo;\n"); + out.push_str(" if (_call.argErr != null) _error.argErr = _call.argErr;\n"); + out.push_str(" if (_call.finalizationError != null) _error.cause = new Error(`EXCEPINFO deferred fill failed: ${_call.finalizationError}`);\n"); + out.push_str(" throw _error;\n"); + out.push_str(" }\n"); + out.push_str(" const _result = {};\n"); + let result_index = method + .results + .iter() + .position(|result| result.source == ResultSource::Param(result_param_index)) + .expect("optional dispatch result has a projected result"); + let conversion = unwrap_method_result_js(method, &method.results[result_index], "_resultValue"); + out.push_str(&format!( + " if (_resultValue != null) _result.result = {conversion};\n" + )); + out.push_str(" return _result;\n"); + out.push_str(" }\n"); +} + +fn emit_enumerator_next_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str) { + let ProjectedComMethodKind::EnumeratorNext { + buffer_param_index, + fetched_param_index, + fetched_optional_for_single, + .. + } = &method.kind + else { + unreachable!("EnumeratorNext renderer requires EnumeratorNext IR") + }; + let plan = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == *buffer_param_index) + .expect("EnumeratorNext buffer plan"); + let result = method + .results + .iter() + .find(|result| result.source == ResultSource::Param(*buffer_param_index)) + .expect("EnumeratorNext values result"); + emit_method_doc_js(out, &method.doc); + out.push_str(&format!(" {}(count) {{\n", method.camel_name)); + out.push_str(" if (!Number.isInteger(count) || count <= 0 || count > 0xFFFFFFFF) throw new RangeError('IEnum::Next count must be an integer from 1 through 4294967295');\n"); + out.push_str(&format!( + " const _values = DynCom.enumeratorOutputArray({}, BigInt(count));\n", + abi_type_js(&plan.element) + )); + let mut args = vec!["_values".to_string()]; + if *fetched_optional_for_single { + assert_eq!( + method.params[*fetched_param_index].direction, + ComParamDirection::OptionalOut + ); + args.push("DynCom.boolValue(true)".into()); + } + out.push_str(&format!( + " const _out = {iface_var}.method({}).invokeAll(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + out.push_str(&format!( + " return {};\n", + unwrap_method_result_js(method, result, "_out[1]") + )); + out.push_str(" }\n"); +} + /// Emits a one-line `@see` JSDoc comment above a method when metadata /// supplied a doc reference (win32metadata's `DocumentationAttribute`, a /// `learn.microsoft.com` URL — see `com_metadata::parse_methods`). Renders @@ -390,13 +780,409 @@ fn emit_method_js_named( out.push_str(" }\n"); return; } - let args = inputs - .iter() - .enumerate() - .map(|(surface, (_, param))| wrap_arg_js(¶m.typ, &js_param_name(¶m.name, surface))) - .collect::>(); - emit_invocation_and_results(out, method, iface_var, &args); - out.push_str(" }\n"); + if let ProjectedComMethodKind::OwningCallerOutput { + buffer_param_index, + capacity_param_index, + } = method.kind + { + emit_owning_caller_output_method_body( + out, + method, + buffer_param_index, + capacity_param_index, + &inputs, + iface_var, + ); + out.push_str(" }\n"); + return; + } + if let Some(plan) = method.typed_buffers.iter().find(|plan| { + matches!( + plan.relation, + TypedBufferRelation::CallerOutput { + sizing: TypedBufferSizing::FixedCapacity, + .. + } + ) + }) { + emit_fixed_capacity_buffer_method_body(out, method, plan, &inputs, iface_var); + out.push_str(" }\n"); + return; + } + if let Some(plan) = method.typed_buffers.iter().find(|plan| { + matches!( + plan.relation, + TypedBufferRelation::CallerOutput { + sizing: TypedBufferSizing::TwoCall { .. }, + .. + } + ) + }) { + emit_two_call_buffer_method_body(out, method, plan, &inputs, iface_var); + out.push_str(" }\n"); + return; + } + for group in &method.shared_counts { + match group { + SharedCountPlan::StringInputScalarOutput { + count_param_index, + string_input_param_index, + scalar_output_param_index, + } => { + let input = &method.params[*string_input_param_index]; + let input_surface = inputs + .iter() + .position(|(index, _)| *index == *string_input_param_index) + .expect("shared string input is visible"); + let input_name = js_param_name(&input.name, input_surface); + out.push_str(&format!( + " const _sharedInput{count_param_index} = {};\n", + wrap_param_arg_js(input, &input_name) + )); + let output_plan = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == *scalar_output_param_index) + .expect("shared scalar output has a typed-buffer plan"); + out.push_str(&format!( + " const _sharedOutput{count_param_index} = DynCom.callerOutputArray({}, DynCom.bufferCount(_sharedInput{count_param_index}));\n", + abi_type_js(&output_plan.element) + )); + } + SharedCountPlan::Parallel { + count_param_index, + input_param_indices, + output_param_indices, + } => { + for input_index in input_param_indices { + let input = &method.params[*input_index]; + let input_surface = inputs + .iter() + .position(|(index, _)| *index == *input_index) + .expect("shared parallel input is visible"); + let input_name = js_param_name(&input.name, input_surface); + out.push_str(&format!( + " const _sharedInput{input_index} = {};\n", + wrap_param_arg_js(input, &input_name) + )); + } + let first_input = input_param_indices + .first() + .expect("parallel shared count has an input"); + let input_plan = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == *first_input) + .expect("parallel shared input has a typed-buffer plan"); + out.push_str(&format!( + " const _sharedCount{count_param_index} = DynCom.bufferElementCount(_sharedInput{first_input}, {});\n", + abi_type_js(&input_plan.element) + )); + for output_index in output_param_indices { + let output_plan = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == *output_index) + .expect("shared parallel output has a typed-buffer plan"); + out.push_str(&format!( + " const _sharedOutput{output_index} = DynCom.callerOutputArray({}, _sharedCount{count_param_index});\n", + abi_type_js(&output_plan.element) + )); + } + } + } + } + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + for group in &method.shared_counts { + match group { + SharedCountPlan::StringInputScalarOutput { + count_param_index, + string_input_param_index, + scalar_output_param_index, + } if *string_input_param_index == index => { + return Some(format!("_sharedInput{count_param_index}")); + } + SharedCountPlan::StringInputScalarOutput { + count_param_index, + scalar_output_param_index, + .. + } if *scalar_output_param_index == index => { + return Some(format!("_sharedOutput{count_param_index}")); + } + SharedCountPlan::Parallel { + input_param_indices, + .. + } if input_param_indices.contains(&index) => { + return Some(format!("_sharedInput{index}")); + } + SharedCountPlan::Parallel { + output_param_indices, + .. + } if output_param_indices.contains(&index) => { + return Some(format!("_sharedOutput{index}")); + } + _ => {} + } + } + if !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + emit_invocation_and_results(out, method, iface_var, &args); + out.push_str(" }\n"); +} + +fn emit_owning_caller_output_method_body( + out: &mut String, + method: &ProjectedComMethod, + buffer_param_index: usize, + capacity_param_index: usize, + inputs: &[(usize, &ProjectedComParam)], + iface_var: &str, +) { + let plan = method + .typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == buffer_param_index) + .expect("owning caller-output buffer plan"); + let capacity_surface = inputs + .iter() + .position(|(index, _)| *index == capacity_param_index) + .expect("owning caller-output capacity is visible"); + let capacity_name = js_param_name(&method.params[capacity_param_index].name, capacity_surface); + let capacity_expression = if count_type_uses_bigint(&method.params[capacity_param_index].typ) { + out.push_str(&format!( + " if (typeof {capacity_name} !== 'bigint' || {capacity_name} < 0n) throw new RangeError('Owning COM array capacity must be a non-negative bigint');\n" + )); + capacity_name.clone() + } else { + out.push_str(&format!( + " if (!Number.isSafeInteger({capacity_name}) || {capacity_name} < 0) throw new RangeError('Owning COM array capacity must be a non-negative safe integer');\n" + )); + format!("BigInt({capacity_name})") + }; + out.push_str(&format!( + " const _values = DynCom.callerOutputArray({}, {capacity_expression});\n", + abi_type_js(&plan.element) + )); + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == buffer_param_index { + return Some("_values".into()); + } + if index == capacity_param_index || !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + emit_invocation_and_results(out, method, iface_var, &args); +} + +fn count_type_uses_bigint(typ: &ComType) -> bool { + matches!( + typ, + ComType::NativeIsize + | ComType::NativeUsize + | ComType::Primitive(ComPrimitive::I64 | ComPrimitive::U64) + | ComType::ScalarAlias { + underlying: super::super::ir::ComScalarRepr::NativeIsize + | super::super::ir::ComScalarRepr::NativeUsize + | super::super::ir::ComScalarRepr::Primitive( + ComPrimitive::I64 | ComPrimitive::U64 + ), + .. + } + ) +} + +fn emit_fixed_capacity_buffer_method_body( + out: &mut String, + method: &ProjectedComMethod, + plan: &TypedBufferPlan, + inputs: &[(usize, &ProjectedComParam)], + iface_var: &str, +) { + let ProjectedComMethodKind::FixedCapacityBytes { guid_param_index } = method.kind else { + unreachable!("fixed-capacity bytes require explicit projected method semantics") + }; + let TypedBufferRelation::CallerOutput { + capacity_param_index, + unit: BufferCountUnit::Bytes, + sizing: TypedBufferSizing::FixedCapacity, + .. + } = plan.relation + else { + unreachable!("fixed-capacity projection is restricted to byte buffers") + }; + assert!(matches!( + plan.element, + ComType::Primitive(super::super::ir::ComPrimitive::U8) + )); + let capacity_surface = inputs + .iter() + .position(|(index, _)| *index == capacity_param_index) + .expect("fixed capacity is a visible projected input"); + let capacity_name = js_param_name(&method.params[capacity_param_index].name, capacity_surface); + out.push_str(&format!( + " if (!Number.isSafeInteger({capacity_name}) || {capacity_name} < 0) throw new RangeError('COM buffer capacity must be a non-negative safe integer');\n" + )); + out.push_str(&format!( + " const _capacity = DynCom.bufferAllocationLength(BigInt({capacity_name}));\n" + )); + out.push_str(&format!( + " const _buffer = DynCom.callerOutputArray({}, BigInt(_capacity));\n", + abi_type_js(&plan.element) + )); + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == plan.buffer_param_index { + return Some("_buffer".into()); + } + if index == capacity_param_index || !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible input"); + if index == guid_param_index { + return Some(format!( + "DynCom.iidPointer(WinGuid.parse({}))", + js_param_name(¶m.name, surface) + )); + } + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + emit_invocation_and_results(out, method, iface_var, &args); +} + +fn emit_two_call_buffer_method_body( + out: &mut String, + method: &ProjectedComMethod, + plan: &TypedBufferPlan, + inputs: &[(usize, &ProjectedComParam)], + iface_var: &str, +) { + let TypedBufferRelation::CallerOutput { + unit: BufferCountUnit::Bytes, + sizing: TypedBufferSizing::TwoCall { max_retries }, + .. + } = plan.relation + else { + unreachable!("two-call buffer projection is restricted to byte buffers") + }; + let buffer_result_index = method + .results + .iter() + .position(|result| result.source == ResultSource::Param(plan.buffer_param_index)) + .expect("two-call buffer has a projected result"); + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == plan.buffer_param_index { + return Some( + "(_capacity === 0 ? DynCom.nullBuffer() : DynCom.buffer(_buffer))".into(), + ); + } + if !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + out.push_str(" let _capacity = 0;\n"); + out.push_str(&format!( + " for (let _attempt = 0; _attempt <= {max_retries}; _attempt++) {{\n" + )); + out.push_str(" const _buffer = Buffer.alloc(_capacity);\n"); + match method.results.len() { + 0 => unreachable!("two-call buffers always produce a result"), + 1 => out.push_str(&format!( + " const _out = {iface_var}.method({}).invoke(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )), + _ => out.push_str(&format!( + " const _out = {iface_var}.method({}).invokeAll(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )), + } + let buffer_expression = if method.results.len() == 1 { + "_out".into() + } else { + format!("_out[{buffer_result_index}]") + }; + out.push_str(&format!( + " const _actual = DynCom.bufferCount({buffer_expression});\n" + )); + out.push_str(" if (_actual <= BigInt(_capacity)) {\n"); + match method.results.len() { + 1 => out.push_str(&format!( + " return {};\n", + unwrap_method_result_js(method, &method.results[0], "_out") + )), + _ => { + let values = method + .results + .iter() + .enumerate() + .map(|(index, result)| { + unwrap_method_result_js(method, result, &format!("_out[{index}]")) + }) + .collect::>(); + out.push_str(&format!( + " return [{}];\n", + values.join(", ") + )); + } + } + out.push_str(" }\n"); + out.push_str(" _capacity = DynCom.bufferAllocationLength(_actual);\n"); + out.push_str(" }\n"); + out.push_str( + " throw new Error('COM buffer size changed during bounded two-call retry');\n", + ); } /// Renders one same-name overload group: every branch's private @@ -489,8 +1275,8 @@ fn emit_string_buffer_method_body( .iter() .position(|(input_index, _)| *input_index == index) .expect("validated input"); - Some(wrap_arg_js( - ¶m.typ, + Some(wrap_param_arg_js( + param, &js_param_name(¶m.name, surface), )) } else if index > plan.count_param_index && plan.optional_param_indices.contains(&index) @@ -529,14 +1315,16 @@ fn emit_string_buffer_method_body( 0 => out.push_str(" return _text;\n"), 1 => out.push_str(&format!( " return [_text, {}];\n", - unwrap_result_js(&method.results[0], "_out") + unwrap_method_result_js(method, &method.results[0], "_out") )), _ => { let values = method .results .iter() .enumerate() - .map(|(index, result)| unwrap_result_js(result, &format!("_out[{index}]"))) + .map(|(index, result)| { + unwrap_method_result_js(method, result, &format!("_out[{index}]")) + }) .collect::>(); out.push_str(&format!(" return [_text, {}];\n", values.join(", "))); } @@ -563,7 +1351,7 @@ fn emit_invocation_and_results( )); out.push_str(&format!( " return {};\n", - unwrap_result_js(&method.results[0], "_out") + unwrap_method_result_js(method, &method.results[0], "_out") )); } _ => { @@ -576,7 +1364,9 @@ fn emit_invocation_and_results( .results .iter() .enumerate() - .map(|(index, result)| unwrap_result_js(result, &format!("_r[{index}]"))) + .map(|(index, result)| { + unwrap_method_result_js(method, result, &format!("_r[{index}]")) + }) .collect::>(); out.push_str(&format!(" return [{}];\n", values.join(", "))); } @@ -586,85 +1376,231 @@ fn emit_invocation_and_results( fn emit_dynamic_iid_method_js( out: &mut String, method: &ProjectedComMethod, - natural_count: usize, + iid_param_index: usize, + output_param_index: usize, iface_var: &str, ) { - let natural = &method.params[..natural_count]; - let mut surface = natural + let inputs = input_params(method); + let surface = inputs .iter() .enumerate() - .map(|(index, param)| js_param_name(¶m.name, index)) + .map(|(surface, (_, param))| js_param_name(¶m.name, surface)) .collect::>(); - surface.push("iid".into()); - let mut args = natural + let iid_surface = inputs .iter() - .enumerate() - .map(|(index, param)| wrap_arg_js(¶m.typ, &js_param_name(¶m.name, index))) - .collect::>(); - args.push("DynCom.iidPointer(_iid)".into()); + .position(|(index, _)| *index == iid_param_index) + .expect("caller-supplied IID is a visible input"); + let iid_name = js_param_name(&method.params[iid_param_index].name, iid_surface); + let args = dynamic_iid_args(method, &inputs, iid_param_index, "DynCom.iidPointer(_iid)"); out.push_str(&format!( - " {}({}) {{\n const _iid = WinGuid.parse(iid);\n", + " {}({}) {{\n const _iid = WinGuid.parse({iid_name});\n", method.camel_name, surface.join(", ") )); - out.push_str(&format!( - " const _raw = {iface_var}.method({}).invoke(this._obj, [{}]);\n", - method.vtable_index, - args.join(", ") - )); - out.push_str(" return DynCom.adoptComPointer(_raw, _iid);\n }\n"); + emit_dynamic_iid_invocation(out, method, output_param_index, iface_var, &args, "_iid"); + out.push_str(" }\n"); } fn emit_synthesized_interop_method_js( out: &mut String, method: &ProjectedComMethod, - natural_count: usize, + iid_param_index: usize, + output_param_index: usize, _target_iid: &str, iface_var: &str, meta: &ProjectedComInterface, ) { - let natural = &method.params[..natural_count]; - let params = natural - .iter() - .enumerate() - .map(|(index, param)| js_param_name(¶m.name, index)) - .collect::>(); - let mut args = natural + let inputs = input_params(method); + let params = inputs .iter() .enumerate() - .map(|(index, param)| wrap_arg_js(¶m.typ, &js_param_name(¶m.name, index))) + .map(|(surface, (_, param))| js_param_name(¶m.name, surface)) .collect::>(); let class_name = match &meta.activation { ActivationPlan::WinRtFactory { class_name, .. } => class_name, _ => unreachable!("validated interop activation"), }; - args.push(format!("DynCom.iidPointer(IID_{class_name}_default)")); + let iid_expression = format!("IID_{class_name}_default"); + let iid_arg = format!("DynCom.iidPointer({iid_expression})"); + let args = dynamic_iid_args(method, &inputs, iid_param_index, &iid_arg); out.push_str(&format!( " {}({}) {{\n", method.camel_name, params.join(", ") )); - out.push_str(&format!( - " const _raw = {iface_var}.method({}).invoke(this._obj, [{}]);\n", - method.vtable_index, - args.join(", ") - )); - out.push_str(&format!(" const _out = DynCom.adoptComPointer(_raw, IID_{class_name}_default);\n return _out;\n }}\n")); + if method.results.len() == 1 { + out.push_str(&format!( + " const _raw = {iface_var}.method({}).invoke(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + out.push_str(&format!( + " const _out = {};\n return _out;\n", + unwrap_dynamic_iid_result_js( + method, + &method.results[0], + "_raw", + output_param_index, + &iid_expression, + ) + )); + } else { + emit_dynamic_iid_invocation( + out, + method, + output_param_index, + iface_var, + &args, + &iid_expression, + ); + } + out.push_str(" }\n"); +} + +fn dynamic_iid_args( + method: &ProjectedComMethod, + inputs: &[(usize, &ProjectedComParam)], + iid_param_index: usize, + iid_arg: &str, +) -> Vec { + method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == iid_param_index { + return Some(iid_arg.to_string()); + } + if !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect() +} + +fn emit_dynamic_iid_invocation( + out: &mut String, + method: &ProjectedComMethod, + output_param_index: usize, + iface_var: &str, + args: &[String], + iid_expression: &str, +) { + match method.results.len() { + 0 => unreachable!("dynamic-IID methods always have an owned interface result"), + 1 => { + out.push_str(&format!( + " const _out = {iface_var}.method({}).invoke(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + out.push_str(&format!( + " return {};\n", + unwrap_dynamic_iid_result_js( + method, + &method.results[0], + "_out", + output_param_index, + iid_expression, + ) + )); + } + _ => { + out.push_str(&format!( + " const _r = {iface_var}.method({}).invokeAll(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + let values = method + .results + .iter() + .enumerate() + .map(|(index, result)| { + unwrap_dynamic_iid_result_js( + method, + result, + &format!("_r[{index}]"), + output_param_index, + iid_expression, + ) + }) + .collect::>(); + out.push_str(&format!(" return [{}];\n", values.join(", "))); + } + } +} + +fn unwrap_dynamic_iid_result_js( + method: &ProjectedComMethod, + result: &ProjectedComResult, + expression: &str, + output_param_index: usize, + iid_expression: &str, +) -> String { + if result.source == ResultSource::Param(output_param_index) { + assert_eq!( + result.conversion, + ResultConversion::DynamicIidAdoption, + "dynamic-IID output must carry explicit adoption provenance" + ); + format!("DynCom.adoptComPointer({expression}, {iid_expression})") + } else { + unwrap_method_result_js(method, result, expression) + } } fn render_dts(meta: &ProjectedComInterface) -> String { let mut out = String::new(); out.push_str("// Generated by dynwinrt-codegen — do not edit\n"); + out.push_str(&format!( + "import type {{ WinGuid }} from '{}';\n", + com_public_import_name() + )); for en in &meta.referenced_enums { out.push_str(&format!( "import {{ {} }} from './{}.js';\n", en.name, en.name )); } + for interface in collect_enumerator_interfaces(meta) { + if interface.name != meta.name || interface.namespace != meta.namespace { + out.push_str(&format!( + "import type {{ {} }} from './{}.js';\n", + interface.name, interface.name + )); + } + } if needs_bridge_import(meta) { out.push_str(&format!( "import type {{ DynWinRtValue }} from '{}';\n", - com_runtime_import_name() + com_public_import_name() + )); + } + if !collect_native_pods(meta).is_empty() { + let types = if collect_native_pod_arrays(meta).is_empty() { + "DynComNativeStruct" + } else { + "DynComNativeStruct, DynComNativeStructArray" + }; + out.push_str(&format!( + "import type {{ {types} }} from '{}';\n", + com_public_import_name() + )); + } + let runtime_types = collect_runtime_types(meta); + if !runtime_types.is_empty() { + out.push_str(&format!( + "import type {{ {} }} from '{}';\n", + runtime_types.join(", "), + com_public_import_name() )); } out.push('\n'); @@ -695,8 +1631,44 @@ fn render_dts(meta: &ProjectedComInterface) -> String { if !collect_pointer_aliases(meta).is_empty() { out.push('\n'); } + let native_pod_arrays = collect_native_pod_arrays(meta); + for layout in collect_native_pods(meta) { + out.push_str(&format!( + "/** Validated native POD bytes ({}-specific size selected at runtime). */\nexport type {} = DynComNativeStruct & {{ readonly __dynComNativeStructLayout: '{}.{}' }};\nexport declare function create{}(bytes?: Buffer): {};\n", + layout.namespace, layout.name, layout.namespace, layout.name, layout.name, layout.name + )); + if native_pod_arrays.contains(&(layout.namespace.clone(), layout.name.clone())) { + out.push_str(&format!( + "export type {}Array = DynComNativeStructArray & {{ readonly __dynComNativeStructArrayLayout: '{}.{}' }};\nexport declare function create{}Array(bytes: Buffer): {}Array;\n", + layout.name, layout.namespace, layout.name, layout.name, layout.name + )); + } + } + if !collect_native_pods(meta).is_empty() { + out.push('\n'); + } + for layout in collect_native_unions(meta) { + out.push_str(&format!( + "/** Validated native POD union bytes. Construction requires the exact active field. */\nexport type {} = DynComNativeUnion & {{ readonly __dynComNativeUnionLayout: '{}.{}' }};\nexport declare function create{}(activeField: {}, bytes?: Buffer): {};\n", + layout.name, + layout.namespace, + layout.name, + layout.name, + layout + .x64 + .fields + .iter() + .map(|field| format!("'{}'", field.name)) + .collect::>() + .join(" | "), + layout.name + )); + } + if !collect_native_unions(meta).is_empty() { + out.push('\n'); + } out.push_str(&format!( - "export declare const IID_{}: unknown;\n\nexport declare class {} {{\n", + "export declare const IID_{}: WinGuid;\n\nexport declare class {} {{\n", meta.name, meta.name )); out.push_str(&format!( @@ -708,7 +1680,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { ActivationPlan::None => {} ActivationPlan::Coclass { .. } => {} ActivationPlan::WinRtFactory { .. } => out.push_str(&format!( - " /** Activate the projected WinRT class and QI to the interop.\n * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */\n static create(): {};\n", + " /** Activate the projected WinRT class and QI to the interop.\n * `initializeCom()` must be called once (e.g. at process startup) before this is used. */\n static create(): {};\n", meta.name )), } @@ -744,21 +1716,30 @@ fn render_dts(meta: &ProjectedComInterface) -> String { continue; } let (params, ret) = match method.kind { - ProjectedComMethodKind::Normal => (dts_params(method), dts_return_type(method)), - ProjectedComMethodKind::CallerSuppliedDynamicIid { - natural_param_count, - } => { - let mut params = dts_natural_params(method, natural_param_count); - params.push("iid: string".into()); - (params, "DynWinRtValue".into()) + ProjectedComMethodKind::Normal + | ProjectedComMethodKind::FixedCapacityBytes { .. } + | ProjectedComMethodKind::OwningCallerOutput { .. } => { + (dts_params(method), dts_return_type(method)) } - ProjectedComMethodKind::SynthesizedGetForWindow { - natural_param_count, - .. + ProjectedComMethodKind::CallerSuppliedDynamicIid { + iid_param_index, .. } => ( - dts_natural_params(method, natural_param_count), - "DynWinRtValue".into(), + dts_dynamic_iid_params(method, iid_param_index), + dts_return_type(method), ), + ProjectedComMethodKind::SynthesizedGetForWindow { .. } => { + (dts_params(method), dts_return_type(method)) + } + ProjectedComMethodKind::DispatchInvoke { .. } => { + let mut params = dts_params(method); + params.push( + "options?: { result?: boolean; excepInfo?: boolean; argErr?: boolean }".into(), + ); + (params, "{ result?: DynComVariant }".into()) + } + ProjectedComMethodKind::EnumeratorNext { .. } => { + (vec!["count: number".into()], dts_return_type(method)) + } }; emit_method_doc_dts(&mut out, &method.doc); out.push_str(&format!( @@ -781,15 +1762,22 @@ fn emit_method_doc_dts(out: &mut String, doc: &Option) { } } -fn dts_natural_params(method: &ProjectedComMethod, count: usize) -> Vec { - method.params[..count] +fn dts_dynamic_iid_params(method: &ProjectedComMethod, iid_param_index: usize) -> Vec { + method + .params .iter() .enumerate() - .map(|(index, param)| { + .filter(|(_, param)| param.surface_input) + .enumerate() + .map(|(surface, (index, param))| { format!( "{}: {}", - js_param_name(¶m.name, index), - input_type_dts(¶m.typ) + js_param_name(¶m.name, surface), + if index == iid_param_index { + "string".into() + } else { + param_input_type_dts(param) + } ) }) .collect() @@ -800,7 +1788,7 @@ fn dts_params(method: &ProjectedComMethod) -> Vec { .params .iter() .enumerate() - .filter(|(_, param)| param.direction.is_input()) + .filter(|(_, param)| param.surface_input) .enumerate() .map(|(surface, (index, param))| { let mut name = js_param_name(¶m.name, surface); @@ -811,7 +1799,15 @@ fn dts_params(method: &ProjectedComMethod) -> Vec { { name.push('?'); } - format!("{name}: {}", input_type_dts(¶m.typ)) + let typ = match method.kind { + ProjectedComMethodKind::FixedCapacityBytes { guid_param_index } + if index == guid_param_index => + { + "string".into() + } + _ => param_input_type_dts(param), + }; + format!("{name}: {typ}") }) .collect() } @@ -826,7 +1822,7 @@ fn dts_return_type(method: &ProjectedComMethod) -> String { method .results .iter() - .map(result_type_dts) + .map(|result| method_result_type_dts(method, result)) .collect::>() .join(", ") ) @@ -834,19 +1830,60 @@ fn dts_return_type(method: &ProjectedComMethod) -> String { } match method.results.len() { 0 => "void".into(), - 1 => result_type_dts(&method.results[0]), + 1 => method_result_type_dts(method, &method.results[0]), _ => format!( "[{}]", method .results .iter() - .map(result_type_dts) + .map(|result| method_result_type_dts(method, result)) .collect::>() .join(", ") ), } } +fn nullable_result_param<'a>( + method: &'a ProjectedComMethod, + result: &ProjectedComResult, +) -> Option<&'a ProjectedComParam> { + let ResultSource::Param(index) = result.source else { + return None; + }; + method.params[index] + .nullable + .then_some(&method.params[index]) +} + +fn unwrap_method_result_js( + method: &ProjectedComMethod, + result: &ProjectedComResult, + expression: &str, +) -> String { + match nullable_result_param(method, result).map(|param| ¶m.typ) { + Some(ComType::NativePodPointer { .. }) => { + let converted = unwrap_result_js(result, "value"); + format!( + "((value) => DynCom.isNullNativeStructPointer(value) ? null : {converted})({expression})" + ) + } + Some(ComType::SafeArray { .. }) => { + format!("DynCom.takeNullableSafeArray({expression})") + } + Some(_) => unreachable!("nullable result projection was validated"), + None => unwrap_result_js(result, expression), + } +} + +fn method_result_type_dts(method: &ProjectedComMethod, result: &ProjectedComResult) -> String { + let typ = result_type_dts(result); + if nullable_result_param(method, result).is_some() { + format!("{typ} | null") + } else { + typ + } +} + fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, PointerAliasKind)> { let mut aliases = BTreeMap::new(); for method in &meta.methods { @@ -861,12 +1898,10 @@ fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, Pointer }) { match typ { - ComType::PointerAlias { name, kind } => { + ComType::PointerAlias { name, kind, .. } => { aliases.insert(name.clone(), *kind); } - ComType::Bstr => { - aliases.insert("BSTR".into(), PointerAliasKind::HandleValue); - } + ComType::Primitive(_) | ComType::NativeIsize | ComType::NativeUsize @@ -877,36 +1912,263 @@ fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, Pointer | ComType::Enum { .. } | ComType::ScalarAlias { .. } | ComType::RawPointer - | ComType::ManagedInterface { .. } => {} + | ComType::Bstr + | ComType::NativePod { .. } + | ComType::NativePodPointer { .. } + | ComType::NativeUnionPointer { .. } + | ComType::Variant + | ComType::VariantByValue + | ComType::SafeArray { .. } + | ComType::PropVariant + | ComType::DispatchParams + | ComType::ExcepInfo + | ComType::ManagedInterface { .. } + | ComType::CoTaskMemWideString + | ComType::StringArray { .. } + | ComType::TypedBuffer { .. } + | ComType::OwningArray { .. } => {} } } } aliases.into_iter().collect() } +fn collect_enumerator_interfaces(meta: &ProjectedComInterface) -> Vec { + let mut interfaces = std::collections::BTreeSet::new(); + for method in &meta.methods { + if let ProjectedComMethodKind::EnumeratorNext { + interface: Some(interface), + .. + } = &method.kind + { + interfaces.insert(interface.clone()); + } + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + { + if let ComType::OwningArray { + interface: Some(interface), + .. + } = typ + { + interfaces.insert(interface.clone()); + } + } + } + interfaces.into_iter().collect() +} + +fn collect_native_pods(meta: &ProjectedComInterface) -> Vec { + let mut layouts = BTreeMap::new(); + for method in &meta.methods { + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + .chain(match &method.return_convention { + ComReturnConvention::Direct(typ) => Some(typ), + _ => None, + }) + { + match typ { + ComType::NativePod { layout } | ComType::NativePodPointer { layout } => { + layouts.insert( + (layout.namespace.clone(), layout.name.clone()), + layout.clone(), + ); + } + ComType::TypedBuffer { element } => { + if let ComType::NativePod { layout } = element.as_ref() { + layouts.insert( + (layout.namespace.clone(), layout.name.clone()), + layout.clone(), + ); + } + } + ComType::OwningArray { element, .. } => { + if let ComType::NativePod { layout } = element.as_ref() { + layouts.insert( + (layout.namespace.clone(), layout.name.clone()), + layout.clone(), + ); + } + } + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Guid + | ComType::HString + | ComType::Enum { .. } + | ComType::ScalarAlias { .. } + | ComType::RawPointer + | ComType::PointerAlias { .. } + | ComType::Bstr + | ComType::NativeUnionPointer { .. } + | ComType::Variant + | ComType::VariantByValue + | ComType::SafeArray { .. } + | ComType::PropVariant + | ComType::DispatchParams + | ComType::ExcepInfo + | ComType::ManagedInterface { .. } + | ComType::CoTaskMemWideString + | ComType::StringArray { .. } => {} + } + } + } + layouts.into_values().collect() +} + +fn collect_native_pod_arrays( + meta: &ProjectedComInterface, +) -> std::collections::BTreeSet<(String, String)> { + let mut layouts = std::collections::BTreeSet::new(); + for method in &meta.methods { + for typ in method.params.iter().map(|param| ¶m.typ) { + if let ComType::TypedBuffer { element } = typ + && let ComType::NativePod { layout } = element.as_ref() + { + layouts.insert((layout.namespace.clone(), layout.name.clone())); + } + } + } + layouts +} + +fn collect_native_unions(meta: &ProjectedComInterface) -> Vec { + let mut layouts = BTreeMap::new(); + for method in &meta.methods { + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + .chain(match &method.return_convention { + ComReturnConvention::Direct(typ) => Some(typ), + _ => None, + }) + { + if let ComType::NativeUnionPointer { layout } = typ { + layouts.insert( + (layout.namespace.clone(), layout.name.clone()), + layout.clone(), + ); + } + } + } + layouts.into_values().collect() +} + +fn collect_runtime_types(meta: &ProjectedComInterface) -> Vec<&'static str> { + let mut types = std::collections::BTreeSet::new(); + for method in &meta.methods { + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + { + match typ { + ComType::NativeUnionPointer { .. } => { + types.insert("DynComNativeUnion"); + } + ComType::Variant => { + types.insert("DynComVariant"); + } + ComType::VariantByValue => { + types.insert("DynComVariant"); + } + ComType::SafeArray { .. } => { + types.insert("DynComSafeArray"); + } + ComType::PropVariant => { + types.insert("DynComPropVariant"); + } + ComType::DispatchParams => { + types.insert("DynComDispatchParams"); + } + ComType::ExcepInfo => { + types.insert("DynComExcepInfo"); + } + ComType::OwningArray { element, .. } => match element.as_ref() { + ComType::Variant => { + types.insert("DynComVariant"); + } + _ => {} + }, + _ => {} + } + } + } + types.into_iter().collect() +} + fn collect_scalar_aliases( meta: &ProjectedComInterface, ) -> Vec<(String, super::super::ir::ComScalarRepr)> { let mut aliases = BTreeMap::new(); for method in &meta.methods { - for typ in - method - .params - .iter() - .map(|param| ¶m.typ) - .chain(match &method.return_convention { - ComReturnConvention::Direct(typ) => Some(typ), - _ => None, - }) + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + .chain(match &method.return_convention { + ComReturnConvention::Direct(typ) => Some(typ), + _ => None, + }) { - if let ComType::ScalarAlias { name, underlying } = typ { - aliases.insert(name.clone(), *underlying); - } + collect_scalar_alias(typ, &mut aliases); } } aliases.into_iter().collect() } +fn collect_scalar_alias( + typ: &ComType, + aliases: &mut BTreeMap, +) { + match typ { + ComType::ScalarAlias { + name, underlying, .. + } => { + aliases.insert(name.clone(), *underlying); + } + ComType::TypedBuffer { element } | ComType::OwningArray { element, .. } => { + collect_scalar_alias(element, aliases) + } + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Guid + | ComType::HString + | ComType::Enum { .. } + | ComType::RawPointer + | ComType::PointerAlias { .. } + | ComType::Bstr + | ComType::NativePod { .. } + | ComType::NativePodPointer { .. } + | ComType::NativeUnionPointer { .. } + | ComType::Variant + | ComType::VariantByValue + | ComType::SafeArray { .. } + | ComType::PropVariant + | ComType::DispatchParams + | ComType::ExcepInfo + | ComType::ManagedInterface { .. } + | ComType::CoTaskMemWideString + | ComType::StringArray { .. } => {} + } +} + fn needs_bridge_import(meta: &ProjectedComInterface) -> bool { matches!(meta.activation, ActivationPlan::WinRtFactory { .. }) || meta.methods.iter().any(|method| { @@ -914,7 +2176,11 @@ fn needs_bridge_import(meta: &ProjectedComInterface) -> bool { || method .params .iter() - .any(|param| matches!(param.typ, ComType::ManagedInterface { .. })) + .any(|param| type_needs_bridge_import(¶m.typ)) + || method + .results + .iter() + .any(|result| type_needs_bridge_import(&result.typ)) || method.results.iter().any(|result| { matches!( result.conversion, @@ -923,18 +2189,61 @@ fn needs_bridge_import(meta: &ProjectedComInterface) -> bool { | ResultConversion::DynamicIidAdoption ) }) + || matches!( + &method.return_convention, + ComReturnConvention::Direct(typ) if type_needs_bridge_import(typ) + ) }) } +fn type_needs_bridge_import(typ: &ComType) -> bool { + match typ { + ComType::ManagedInterface { .. } => true, + ComType::TypedBuffer { element } => type_needs_bridge_import(element), + ComType::OwningArray { element, interface } => { + interface.is_none() && type_needs_bridge_import(element) + } + _ => false, + } +} + fn com_runtime_import_name() -> String { + let import_name = crate::codegen::project::get_import_name(); + if import_name == "@microsoft/dynwinrt" { + format!("{import_name}/com/unsafe") + } else if import_name == "@microsoft/dynwinrt/com" { + format!("{import_name}/unsafe") + } else if let Some(import_name) = + replace_exact_module_basename(&import_name, "com.js", "com-unsafe.js") + { + import_name + } else { + import_name + } +} + +fn com_public_import_name() -> String { let import_name = crate::codegen::project::get_import_name(); if import_name == "@microsoft/dynwinrt" { format!("{import_name}/com") + } else if import_name == "@microsoft/dynwinrt/com/unsafe" { + "@microsoft/dynwinrt/com".into() + } else if let Some(import_name) = + replace_exact_module_basename(&import_name, "com-unsafe.js", "com.js") + { + import_name } else { import_name } } +fn replace_exact_module_basename(value: &str, from: &str, to: &str) -> Option { + let (prefix, basename) = value + .rfind(|character| character == '/' || character == '\\') + .map_or(("", value), |index| value.split_at(index + 1)); + (basename == from).then(|| format!("{prefix}{to}")) +} + fn render_enum_files(en: &ProjectedComEnum) -> (String, String) { let mut js = String::from("// Generated by dynwinrt-codegen — do not edit\n"); js.push_str(&format!("export const {} = Object.freeze({{\n", en.name)); diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index 5ab38988..dce08a24 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -2,10 +2,11 @@ // Licensed under the MIT License. use super::*; -use crate::codegen::com::generate_com_interface_files; +use crate::codegen::com::ir::{ComPrimitive, ComScalarRepr}; use crate::codegen::com::javascript::naming::{camel_case, strip_hungarian}; -use crate::codegen::com::project::project_com_interface; -use crate::codegen::com::project::types::project_type; +use crate::codegen::com::project::{ + project_com_interface_for_test as project_com_interface, project_type_for_test as project_type, +}; use crate::com_metadata::{ ComEnumMeta, ComEnumValue, ComInterfaceMeta, MethodMeta, ParamDirection, ParamMeta, }; @@ -13,6 +14,14 @@ use crate::types::TypeMeta; type HandleAliasKind = PointerAliasKind; +fn generate_com_interface_files( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result { + let projected = project_com_interface(meta, winmd_paths)?; + Ok(render_com_interface(&projected)) +} + #[test] fn renderer_api_accepts_only_projected_ir() { let projected = ProjectedComInterface { @@ -27,6 +36,857 @@ fn renderer_api_accepts_only_projected_ir() { let output = render_com_interface(&projected); assert!(output.js.contains("registerIUnknownInterface")); assert!(output.dts.contains("export declare class ITest")); + assert!( + output + .dts + .contains("import type { WinGuid } from '@microsoft/dynwinrt/com';") + ); + assert!( + output + .dts + .contains("export declare const IID_ITest: WinGuid;") + ); +} + +#[test] +fn renderer_projects_borrowed_hwnd_output_as_numeric_handle() { + let hwnd = ComType::PointerAlias { + namespace: "Windows.Win32.Foundation".into(), + name: "HWND".into(), + kind: PointerAliasKind::HandleValue, + }; + let projected = ProjectedComInterface { + name: "IWindowOwner".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "GetWindow".into(), + camel_name: "getWindow".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "phwnd".into(), + typ: hwnd.clone(), + direction: ComParamDirection::Out, + surface_input: false, + surface_result: true, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: vec![ProjectedComResult { + typ: hwnd, + source: ResultSource::Param(0), + conversion: ResultConversion::BorrowedHandle, + }], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + let output = render_com_interface(&projected); + assert!( + output + .js + .contains(".addOut(DynCom.borrowedHandleOutputType())") + ); + assert!(output.js.contains("return DynCom.asPointerBigint(_out);")); + assert!(output.dts.contains("getWindow(): HWND;")); + assert!(!output.dts.contains("getWindow(): Buffer")); + assert!(!output.js.contains("adoptComPointer")); +} + +#[test] +fn canonical_iunknown_arrays_use_managed_values_without_nominal_wrappers() { + let array = ComType::OwningArray { + element: Box::new(ComType::ManagedInterface { + iid: "00000000-0000-0000-c000-000000000046".into(), + }), + interface: None, + }; + assert_eq!(type_dts(&array), "DynWinRtValue[]"); + assert_eq!( + super::super::types::wrap_arg_js(&array, "values"), + "DynCom.interfaceArray(WinGuid.parse('00000000-0000-0000-c000-000000000046'), values)" + ); + let result = ProjectedComResult { + typ: array, + source: ResultSource::Param(0), + conversion: ResultConversion::OwningArray { interface: None }, + }; + assert_eq!(result_type_dts(&result), "DynWinRtValue[]"); + assert_eq!( + unwrap_result_js(&result, "_out"), + "Array.from(DynCom.takeComArray(_out))" + ); + + let projected = ProjectedComInterface { + name: "IUnknownArray".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "GetValues".into(), + camel_name: "getValues".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "values".into(), + typ: result.typ.clone(), + direction: ComParamDirection::Out, + surface_input: false, + surface_result: true, + nullable: false, + }], + results: vec![result], + return_convention: ComReturnConvention::HResult, + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + let output = render_com_interface(&projected); + assert!( + output + .dts + .contains("import type { DynWinRtValue } from '@microsoft/dynwinrt/com';") + ); +} + +#[test] +fn renderer_projects_bstr_replacement_as_a_string_roundtrip() { + let projected = ProjectedComInterface { + name: "IReplaceText".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "Replace".into(), + camel_name: "replace".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "value".into(), + typ: ComType::Bstr, + direction: ComParamDirection::InOut, + surface_input: true, + surface_result: true, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: vec![ProjectedComResult { + typ: ComType::Bstr, + source: ResultSource::Param(0), + conversion: ResultConversion::Bstr, + }], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + let output = render_com_interface(&projected); + + assert!( + output + .js + .contains("new DynComMethodSig().addInOut(DynCom.bstrType())") + ); + assert!(output.js.contains("DynCom.bstr(value)")); + assert!(output.js.contains("DynCom.takeBstr(")); + assert!(output.dts.contains("replace(value: string): string;")); + assert!(!output.js.contains("Buffer")); + assert!(!output.dts.contains("bigint")); +} + +#[test] +fn renderer_allows_null_only_for_nullable_bstr_inputs() { + let projected = ProjectedComInterface { + name: "IOptionalText".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "SetOptional".into(), + camel_name: "setOptional".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "value".into(), + typ: ComType::Bstr, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: true, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + let output = render_com_interface(&projected); + + assert!( + output + .js + .contains("new DynComMethodSig().addIn(DynCom.nullableBstrType())") + ); + assert!( + output + .js + .contains("value === null ? DynCom.nullBstr() : DynCom.bstr(value)") + ); + assert!( + output + .dts + .contains("setOptional(value: string | null): void;") + ); +} + +#[test] +fn real_automation_bstr_interfaces_render_natural_string_apis() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + for (namespace, interface_name) in [ + ("Windows.Win32.Web.InternetExplorer", "ITargetNotify2"), + ("Windows.Win32.Storage.Imapi", "IDiscRecorder"), + ("Windows.Win32.System.TaskScheduler", "IExecAction2"), + ] { + let meta = + crate::com_metadata::parse_com_interface(&winmd, namespace, interface_name).unwrap(); + let projected = crate::codegen::com::project::project_com_interface(&meta, &winmd) + .unwrap_or_else(|error| panic!("{namespace}.{interface_name}: {error}")); + let output = render_com_interface(&projected); + assert!(output.js.contains("DynCom.bstrType()")); + assert!(output.js.contains("DynCom.takeBstr(")); + assert!(output.dts.contains("string")); + if interface_name == "IDiscRecorder" { + assert!( + output + .dts + .contains("getDisplayNames(): [string, string, string];") + ); + } + } +} + +#[test] +fn renderer_keeps_dynamic_iid_native_order_and_all_results() { + let input = |name: &str, typ| ProjectedComParam { + name: name.into(), + typ, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }; + let output = |name: &str, typ| ProjectedComParam { + name: name.into(), + typ, + direction: ComParamDirection::Out, + surface_input: false, + surface_result: true, + nullable: false, + }; + let method = ProjectedComMethod { + name: "Resolve".into(), + camel_name: "resolve".into(), + vtable_index: 7, + params: vec![ + input("context", ComType::Primitive(ComPrimitive::U32)), + output("status", ComType::Primitive(ComPrimitive::I32)), + input("riid", ComType::RawPointer), + output("object", ComType::RawPointer), + input("flags", ComType::Primitive(ComPrimitive::U16)), + output("cookie", ComType::Primitive(ComPrimitive::U64)), + ], + return_convention: ComReturnConvention::HResult, + results: vec![ + ProjectedComResult { + typ: ComType::Primitive(ComPrimitive::I32), + source: ResultSource::Param(1), + conversion: ResultConversion::Value, + }, + ProjectedComResult { + typ: ComType::RawPointer, + source: ResultSource::Param(3), + conversion: ResultConversion::DynamicIidAdoption, + }, + ProjectedComResult { + typ: ComType::Primitive(ComPrimitive::U64), + source: ResultSource::Param(5), + conversion: ResultConversion::Value, + }, + ], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::CallerSuppliedDynamicIid { + iid_param_index: 2, + output_param_index: 3, + }, + doc: None, + overload: None, + }; + let output = render_com_interface(&ProjectedComInterface { + name: "IResolve".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000010".into(), + is_iunknown_rooted: true, + methods: vec![method], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }); + + assert!(output.js.contains( + ".addIn(DynCom.u32Type()).addOut(DynCom.i32Type()).addIn(DynCom.pointerType()).addOut(DynCom.ownedComPointerType()).addIn(DynCom.u16Type()).addOut(DynCom.u64Type())" + )); + assert!(output.js.contains("resolve(context, riid, flags)")); + assert!(output.js.contains("const _iid = WinGuid.parse(riid)")); + assert!(output.js.contains( + "invokeAll(this._obj, [DynCom.u32(context), DynCom.iidPointer(_iid), DynCom.u16(flags)])" + )); + assert!( + output.js.contains( + "return [DynCom.toNumber(_r[0]), DynCom.adoptComPointer(_r[1], _iid), DynCom.toU64Bigint(_r[2])];" + ), + "{}", + output.js + ); + assert!(output.dts.contains( + "resolve(context: number, riid: string, flags: number): [number, DynWinRtValue, bigint];" + )); +} + +#[test] +fn renderer_emits_distinct_by_value_variant_inputs() { + let projected = ProjectedComInterface { + name: "IVariantInput".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000002".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "UseVariant".into(), + camel_name: "useVariant".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "value".into(), + typ: ComType::VariantByValue, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + let output = render_com_interface(&projected); + assert!(output.js.contains( + ".addMethodAt(3, 'UseVariant', new DynComMethodSig().addIn(DynCom.variantByValueType()))" + )); + assert!(output.js.contains("DynCom.variant(value)")); + assert!( + output + .dts + .contains("useVariant(value: DynComVariant): void;") + ); + assert!(!output.dts.contains("DynComVariant | null")); +} + +#[test] +fn typed_buffer_scalar_aliases_are_collected_for_declarations() { + let alias = ComType::ScalarAlias { + namespace: "Windows.Win32.System.Com".into(), + name: "DISPID".into(), + underlying: ComScalarRepr::Primitive(ComPrimitive::I32), + }; + let projected = ProjectedComInterface { + name: "ITest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "Resolve".into(), + camel_name: "resolve".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "values".into(), + typ: ComType::TypedBuffer { + element: Box::new(alias), + }, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + assert_eq!( + collect_scalar_aliases(&projected), + vec![("DISPID".into(), ComScalarRepr::Primitive(ComPrimitive::I32))] + ); +} + +#[test] +fn renderer_serializes_fixed_capacity_bytes_from_projected_ir() { + let byte_buffer = ComType::TypedBuffer { + element: Box::new(ComType::Primitive(ComPrimitive::U8)), + }; + let projected = ProjectedComInterface { + name: "ITestBlob".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "GetBlob".into(), + camel_name: "getBlob".into(), + vtable_index: 15, + params: vec![ + ProjectedComParam { + name: "guidKey".into(), + typ: ComType::Guid, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }, + ProjectedComParam { + name: "pBuf".into(), + typ: byte_buffer.clone(), + direction: ComParamDirection::CallerOutputBuffer, + surface_input: false, + surface_result: true, + nullable: false, + }, + ProjectedComParam { + name: "capacity".into(), + typ: ComType::Primitive(ComPrimitive::U32), + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }, + ProjectedComParam { + name: "pcbBlobSize".into(), + typ: ComType::Primitive(ComPrimitive::U32), + direction: ComParamDirection::Out, + surface_input: false, + surface_result: false, + nullable: false, + }, + ], + return_convention: ComReturnConvention::HResult, + results: vec![ProjectedComResult { + typ: byte_buffer, + source: ResultSource::Param(1), + conversion: ResultConversion::Buffer, + }], + string_buffer: None, + typed_buffers: vec![TypedBufferPlan { + buffer_param_index: 1, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::CallerOutput { + capacity_param_index: 2, + actual_length_param_index: Some(3), + unit: BufferCountUnit::Bytes, + sizing: TypedBufferSizing::FixedCapacity, + }, + }], + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::FixedCapacityBytes { + guid_param_index: 0, + }, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + let output = render_com_interface(&projected); + assert!( + output + .js + .contains(".addCallerOutputBuffer(DynCom.u8Type(), 2, 3, true, false)") + ); + assert!(output.js.contains("getBlob(guidKey, capacity)")); + assert!( + output + .js + .contains("DynCom.callerOutputArray(DynCom.u8Type(), BigInt(_capacity))") + ); + assert!( + output + .dts + .contains("getBlob(guidKey: string, capacity: number): Buffer;") + ); +} + +#[test] +fn parallel_arrays_use_semantic_element_counts_and_guid_conversion() { + let projected = ProjectedComInterface { + name: "IParallel".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000010".into(), + is_iunknown_rooted: true, + methods: vec![ProjectedComMethod { + name: "Copy".into(), + camel_name: "copy".into(), + vtable_index: 3, + params: vec![ + ProjectedComParam { + name: "values".into(), + typ: ComType::TypedBuffer { + element: Box::new(ComType::Primitive(ComPrimitive::U32)), + }, + direction: ComParamDirection::InputBuffer, + surface_input: true, + surface_result: false, + nullable: false, + }, + ProjectedComParam { + name: "ids".into(), + typ: ComType::TypedBuffer { + element: Box::new(ComType::Guid), + }, + direction: ComParamDirection::CallerOutputBuffer, + surface_input: false, + surface_result: true, + nullable: false, + }, + ProjectedComParam { + name: "count".into(), + typ: ComType::Primitive(ComPrimitive::U32), + direction: ComParamDirection::In, + surface_input: false, + surface_result: false, + nullable: false, + }, + ], + return_convention: ComReturnConvention::HResult, + results: vec![ProjectedComResult { + typ: ComType::TypedBuffer { + element: Box::new(ComType::Guid), + }, + source: ResultSource::Param(1), + conversion: ResultConversion::PlainArray, + }], + string_buffer: None, + typed_buffers: vec![ + TypedBufferPlan { + buffer_param_index: 0, + element: ComType::Primitive(ComPrimitive::U32), + relation: TypedBufferRelation::Input { + count_param_index: 2, + actual_length_param_index: None, + unit: BufferCountUnit::Elements, + }, + }, + TypedBufferPlan { + buffer_param_index: 1, + element: ComType::Guid, + relation: TypedBufferRelation::CallerOutput { + capacity_param_index: 2, + actual_length_param_index: None, + unit: BufferCountUnit::Elements, + sizing: TypedBufferSizing::SingleCall, + }, + }, + ], + shared_counts: vec![SharedCountPlan::Parallel { + count_param_index: 2, + input_param_indices: vec![0], + output_param_indices: vec![1], + }], + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + let output = render_com_interface(&projected); + assert!( + output + .js + .contains("DynCom.bufferElementCount(_sharedInput0, DynCom.u32Type())") + ); + assert!(output.js.contains("DynCom.takeGuidArray(")); +} + +#[test] +fn owning_array_bigint_capacity_is_not_number_validated() { + assert!(count_type_uses_bigint(&ComType::NativeUsize)); + assert!(count_type_uses_bigint(&ComType::Primitive( + ComPrimitive::U64 + ))); + assert!(!count_type_uses_bigint(&ComType::Primitive( + ComPrimitive::U32 + ))); +} + +#[test] +fn renderer_emits_tagged_unions_and_automation_runtime_transfers() { + use crate::codegen::com::ir::{ + NativePodScalar, NativeUnionArchitectureLayout, NativeUnionField, NativeUnionFieldType, + NativeUnionLayout, ProjectedComResult, + }; + + let union_architecture = NativeUnionArchitectureLayout { + size: 8, + alignment: 8, + fields: vec![ + NativeUnionField { + name: "integer".into(), + count: 1, + typ: NativeUnionFieldType::Scalar(NativePodScalar::U64), + }, + NativeUnionField { + name: "pointer".into(), + count: 1, + typ: NativeUnionFieldType::Pointer, + }, + ], + }; + let union = ComType::NativeUnionPointer { + layout: NativeUnionLayout { + namespace: "Tests".into(), + name: "TaggedValue".into(), + x86: union_architecture.clone(), + x64: union_architecture.clone(), + arm64: union_architecture, + }, + }; + let method = + |name: &str, slot: usize, input: ComType, output: ComType, conversion: ResultConversion| { + ProjectedComMethod { + name: name.into(), + camel_name: camel_case(name), + vtable_index: slot, + params: vec![ + ProjectedComParam { + name: "value".into(), + typ: input, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }, + ProjectedComParam { + name: "result".into(), + typ: output.clone(), + direction: ComParamDirection::Out, + surface_input: false, + surface_result: true, + nullable: false, + }, + ], + return_convention: ComReturnConvention::HResult, + results: vec![ProjectedComResult { + typ: output, + source: ResultSource::Param(1), + conversion, + }], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + } + }; + let projected = ProjectedComInterface { + name: "IAutomationTest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000009".into(), + is_iunknown_rooted: true, + methods: vec![ + method( + "UseUnion", + 3, + union, + ComType::Variant, + ResultConversion::Variant, + ), + method( + "UseVariant", + 4, + ComType::Variant, + ComType::SafeArray { + element: crate::codegen::com::ir::SafeArrayElement::Bstr, + }, + ResultConversion::SafeArray, + ), + method( + "UseSafeArray", + 5, + ComType::SafeArray { + element: crate::codegen::com::ir::SafeArrayElement::Bstr, + }, + ComType::PropVariant, + ResultConversion::PropVariant, + ), + ], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + + let output = render_com_interface(&projected); + assert!(output.js.contains("createTaggedValue(activeField, bytes)")); + assert!(output.js.contains("DynCom.nativeUnion(")); + assert!(output.js.contains("DynCom.variant(")); + assert!(output.js.contains("DynCom.safeArray(")); + assert!(output.js.contains("DynCom.takeVariant(")); + assert!(output.js.contains("DynCom.takeSafeArray(")); + assert!(output.js.contains("DynCom.takePropVariant(")); + assert!(output.dts.contains("activeField: 'integer' | 'pointer'")); + assert!(output.dts.contains("DynComNativeUnion")); + assert!(output.dts.contains("DynComVariant")); + assert!(output.dts.contains("DynComSafeArray")); + assert!(output.dts.contains("DynComPropVariant")); +} + +#[test] +fn renderer_emits_explicit_idispatch_invoke_options_and_compound_types() { + let input = |name: &str, typ| ProjectedComParam { + name: name.into(), + typ, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }; + let optional_output = |name: &str, typ| ProjectedComParam { + name: name.into(), + typ, + direction: ComParamDirection::OptionalOut, + surface_input: false, + surface_result: true, + nullable: false, + }; + let failure_output = |name: &str, typ| ProjectedComParam { + surface_result: false, + ..optional_output(name, typ) + }; + let method = ProjectedComMethod { + name: "Invoke".into(), + camel_name: "invoke".into(), + vtable_index: 6, + params: vec![ + input("dispIdMember", ComType::Primitive(ComPrimitive::I32)), + input("riid", ComType::RawPointer), + input("lcid", ComType::Primitive(ComPrimitive::U32)), + input("wFlags", ComType::Primitive(ComPrimitive::U16)), + input("dispParams", ComType::DispatchParams), + optional_output("varResult", ComType::Variant), + failure_output("excepInfo", ComType::ExcepInfo), + failure_output("argErr", ComType::Primitive(ComPrimitive::U32)), + ], + return_convention: ComReturnConvention::DispatchInvokeHResult, + results: vec![ProjectedComResult { + typ: ComType::Variant, + source: ResultSource::Param(5), + conversion: ResultConversion::Variant, + }], + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::DispatchInvoke { + result_param_index: 5, + excep_info_param_index: 6, + arg_err_param_index: 7, + }, + doc: None, + overload: None, + }; + let output = render_com_interface(&ProjectedComInterface { + name: "IDispatch".into(), + namespace: "Windows.Win32.System.Com".into(), + iid: "00020400-0000-0000-c000-000000000046".into(), + is_iunknown_rooted: true, + methods: vec![method], + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }); + + assert!(output.js.contains(".addIn(DynCom.dispatchParamsType())")); + assert!( + output + .js + .contains(".addOptionalOut(DynCom.excepInfoType())") + ); + assert!( + output + .js + .contains("invoke(dispIdMember, riid, lcid, wFlags, dispParams, options = {})") + ); + assert!(output.js.contains("DynCom.dispatchParams(dispParams)")); + assert!(output.js.contains("DynCom.boolValue(_requestExcepInfo)")); + assert!(output.js.contains(".captureDispatchInvokeHresult()")); + assert!(output.js.contains(".invokeDispatch(this._obj")); + assert!(output.js.contains("_error.hresult = _call.hresult")); + assert!(output.js.contains("_error.excepInfo = _excepInfo")); + assert!(output.js.contains("_error.argErr = _call.argErr")); + assert!(output.js.contains("_error.cause = new Error")); + assert!(output.js.contains("HRESULT ${_hresult}")); + assert!( + output + .js + .contains("_description ? `: ${_description}` : ''") + ); + assert!( + output + .js + .contains("_result.result = DynCom.takeVariant(_resultValue)") + ); + assert!(!output.js.contains("_result.excepInfo")); + assert!(!output.js.contains("_result.argErr")); + assert!(output.dts.contains("dispParams: DynComDispatchParams")); + assert!(output.dts.contains("): { result?: DynComVariant };")); } #[test] @@ -234,6 +1094,7 @@ fn render_enum_files(en: &ComEnumMeta) -> (String, String) { _ => panic!("unsupported test enum underlying type"), }; let projected = ProjectedComEnum { + namespace: en.namespace.clone(), name: en.name.clone(), underlying, members: en @@ -290,7 +1151,14 @@ fn camel_case_basic() { fn default_runtime_import_uses_com_subpath() { let previous = crate::codegen::project::get_import_name(); crate::codegen::project::set_import_name("@microsoft/dynwinrt"); - assert_eq!(com_runtime_import_name(), "@microsoft/dynwinrt/com"); + assert_eq!(com_runtime_import_name(), "@microsoft/dynwinrt/com/unsafe"); + assert_eq!(com_public_import_name(), "@microsoft/dynwinrt/com"); + crate::codegen::project::set_import_name("../dist/com.js"); + assert_eq!(com_runtime_import_name(), "../dist/com-unsafe.js"); + assert_eq!(com_public_import_name(), "../dist/com.js"); + crate::codegen::project::set_import_name("./mycom.js"); + assert_eq!(com_runtime_import_name(), "./mycom.js"); + assert_eq!(com_public_import_name(), "./mycom.js"); crate::codegen::project::set_import_name(&previous); } @@ -730,6 +1598,8 @@ fn interop_generation_fails_when_target_iid_unresolvable() { coclass_name: None, own_methods_start: 3, referenced_enums: Vec::new(), + raw_referenced_enums: None, + raw_methods: None, }; // Pass empty winmd_paths — even with the newest-SDK fallback, the // synthetic class name won't be found anywhere. @@ -782,6 +1652,8 @@ fn non_interop_iunknown_interface_still_generates_without_winmd_lookup() { coclass_name: None, own_methods_start: 3, referenced_enums: Vec::new(), + raw_referenced_enums: None, + raw_methods: None, }; let out = generate_com_interface_files(&com, "") .expect("plain classic-COM codegen must succeed with no winmds"); @@ -812,6 +1684,8 @@ fn plain_iface_with_method(m: MethodMeta) -> crate::com_metadata::ComInterfaceMe coclass_name: None, own_methods_start: 3, referenced_enums: Vec::new(), + raw_referenced_enums: None, + raw_methods: None, } } @@ -1824,12 +2698,13 @@ fn caller_supplied_riid_output_is_adopted() { let com = plain_iface_with_method(method); let output = generate_com_interface_files(&com, "").unwrap(); - assert!(output.js.contains("bindToHandler(pbc, iid)")); - assert!(output.js.contains("DynCom.adoptComPointer(_raw, _iid)")); + assert!(output.js.contains("bindToHandler(pbc, riid)")); + assert!(output.js.contains("const _iid = WinGuid.parse(riid)")); + assert!(output.js.contains("DynCom.adoptComPointer(_out, _iid)")); assert!( output .dts - .contains("bindToHandler(pbc: bigint | Buffer, iid: string): DynWinRtValue;") + .contains("bindToHandler(pbc: bigint | Buffer, riid: string): DynWinRtValue;") ); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs index b984c4b3..2c23144f 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -2,9 +2,13 @@ // Licensed under the MIT License. use super::super::ir::{ - ComEnumUnderlying, ComPrimitive, ComScalarRepr, ComType, PointerAliasKind, ProjectedComResult, - ResultConversion, StringEncoding, + ComEnumUnderlying, ComPrimitive, ComScalarRepr, ComType, NativePodArchitectureLayout, + NativePodFieldType, NativePodLayout, NativePodScalar, NativeUnionArchitectureLayout, + NativeUnionFieldType, NativeUnionLayout, PointerAliasKind, ProjectedComResult, + ResultConversion, SafeArrayElement, StringEncoding, }; +#[cfg(test)] +use super::super::ir::{NativePodField, NativeUnionField}; pub(super) fn abi_type_js(typ: &ComType) -> String { match typ { @@ -30,12 +34,69 @@ pub(super) fn abi_type_js(typ: &ComType) -> String { ComType::HString => "DynCom.hstringType()".into(), ComType::Enum { underlying, .. } => enum_abi_type_js(*underlying).into(), ComType::ScalarAlias { underlying, .. } => scalar_abi_type_js(*underlying).into(), - ComType::RawPointer | ComType::PointerAlias { .. } | ComType::Bstr => { - "DynCom.pointerType()".into() + ComType::RawPointer | ComType::PointerAlias { .. } => "DynCom.pointerType()".into(), + ComType::Bstr => "DynCom.bstrType()".into(), + ComType::NativePod { layout } => { + format!("DynCom.nativeStructType({})", native_pod_layout_js(layout)) } + ComType::NativePodPointer { layout } => format!( + "DynCom.nativeStructPointerType({})", + native_pod_layout_js(layout) + ), + ComType::NativeUnionPointer { layout } => format!( + "DynCom.nativeUnionPointerType({})", + native_union_layout_js(layout) + ), + ComType::Variant => "DynCom.variantType()".into(), + ComType::VariantByValue => "DynCom.variantByValueType()".into(), + ComType::SafeArray { element } => safe_array_abi_type_js(*element, false), + ComType::PropVariant => "DynCom.propVariantType()".into(), + ComType::DispatchParams => "DynCom.dispatchParamsType()".into(), + ComType::ExcepInfo => "DynCom.excepInfoType()".into(), ComType::ManagedInterface { iid } => { format!("DynCom.interfaceType(WinGuid.parse('{iid}'))") } + ComType::CoTaskMemWideString => "DynCom.coTaskMemWideStringType()".into(), + ComType::StringArray { .. } => "DynCom.pointerType()".into(), + ComType::TypedBuffer { element } => abi_type_js(element), + ComType::OwningArray { element, .. } => abi_type_js(element), + } +} + +pub(super) fn safe_array_abi_type_js(element: SafeArrayElement, nullable: bool) -> String { + match element { + SafeArrayElement::Interface { iid } => format!( + "DynCom.safeArrayType('unknown', WinGuid.parse('{}'){})", + super::super::project::format_guid(&iid), + if nullable { ", true" } else { "" } + ), + _ => format!( + "DynCom.safeArrayType('{}'{}{})", + safe_array_element_name(element), + if nullable { ", undefined" } else { "" }, + if nullable { ", true" } else { "" } + ), + } +} + +fn safe_array_element_name(element: SafeArrayElement) -> &'static str { + match element { + SafeArrayElement::I8 => "i8", + SafeArrayElement::U8 => "u8", + SafeArrayElement::I16 => "i16", + SafeArrayElement::U16 => "u16", + SafeArrayElement::I32 => "i32", + SafeArrayElement::U32 => "u32", + SafeArrayElement::I64 => "i64", + SafeArrayElement::U64 => "u64", + SafeArrayElement::F32 => "f32", + SafeArrayElement::F64 => "f64", + SafeArrayElement::Bool => "bool", + SafeArrayElement::Bstr => "bstr", + SafeArrayElement::Interface { .. } => { + unreachable!("interface SAFEARRAY elements use exact-IID rendering") + } + SafeArrayElement::Variant => "variant", } } @@ -44,10 +105,12 @@ pub(super) fn input_type_dts(typ: &ComType) -> String { ComType::PointerAlias { name, kind: PointerAliasKind::HandleValue, + .. } if name == "HWND" => format!("{name} | Buffer | Uint8Array"), ComType::PointerAlias { name, kind: PointerAliasKind::DataPointer, + .. } => format!("{name} | Buffer | Uint8Array"), _ => type_dts(typ), } @@ -78,18 +141,63 @@ pub(super) fn type_dts(typ: &ComType) -> String { ComType::ScalarAlias { name, .. } => name.clone(), ComType::RawPointer => "bigint | Buffer".into(), ComType::PointerAlias { name, .. } => name.clone(), - ComType::Bstr => "BSTR".into(), + ComType::NativePod { layout } | ComType::NativePodPointer { layout } => layout.name.clone(), + ComType::NativeUnionPointer { layout } => layout.name.clone(), + ComType::Bstr => "string".into(), + ComType::Variant => "DynComVariant".into(), + ComType::VariantByValue => "DynComVariant".into(), + ComType::SafeArray { .. } => "DynComSafeArray".into(), + ComType::PropVariant => "DynComPropVariant".into(), + ComType::DispatchParams => "DynComDispatchParams".into(), + ComType::ExcepInfo => "DynComExcepInfo".into(), ComType::ManagedInterface { .. } => "DynWinRtValue".into(), + ComType::CoTaskMemWideString => "string".into(), + ComType::StringArray { .. } => "string[]".into(), + ComType::TypedBuffer { element } => match element.as_ref() { + ComType::NativePod { layout } => format!("{}Array", layout.name), + _ => "Buffer | ArrayBufferView".into(), + }, + ComType::OwningArray { element, interface } => interface.as_ref().map_or_else( + || format!("{}[]", type_dts(element)), + |interface| format!("{}[]", interface.name), + ), } } pub(super) fn result_type_dts(result: &ProjectedComResult) -> String { - match result.conversion { + match &result.conversion { ResultConversion::Bstr | ResultConversion::CoTaskMemString(_) => "string".into(), ResultConversion::CoTaskMemData | ResultConversion::ManagedCom | ResultConversion::DynamicIidAdoption => "DynWinRtValue".into(), - ResultConversion::Value | ResultConversion::HString => type_dts(&result.typ), + ResultConversion::Value | ResultConversion::BorrowedHandle | ResultConversion::HString => { + type_dts(&result.typ) + } + ResultConversion::Buffer => "Buffer".into(), + ResultConversion::PlainArray => { + let ComType::TypedBuffer { element } = &result.typ else { + unreachable!("plain array result requires a typed-buffer result") + }; + format!("{}[]", type_dts(element)) + } + ResultConversion::EnumeratorArray { interface } => { + let (element, projected_interface) = projected_array_parts(&result.typ); + interface.as_ref().or(projected_interface).map_or_else( + || format!("{}[]", type_dts(element)), + |interface| format!("{}[]", interface.name), + ) + } + ResultConversion::OwningArray { interface } => { + let (element, projected_interface) = projected_array_parts(&result.typ); + interface.as_ref().or(projected_interface).map_or_else( + || format!("{}[]", type_dts(element)), + |interface| format!("{}[]", interface.name), + ) + } + ResultConversion::Variant => "DynComVariant".into(), + ResultConversion::SafeArray => "DynComSafeArray".into(), + ResultConversion::PropVariant => "DynComPropVariant".into(), + ResultConversion::ExcepInfo => "DynComExcepInfo".into(), } } @@ -117,10 +225,12 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { ComType::HString => format!("DynCom.hstring({variable})"), ComType::Enum { underlying, .. } => wrap_enum_arg_js(*underlying, variable), ComType::ScalarAlias { underlying, .. } => wrap_scalar_arg_js(*underlying, variable), - ComType::RawPointer | ComType::Bstr => format!("DynCom.pointer({variable})"), + ComType::RawPointer => format!("DynCom.pointer({variable})"), + ComType::Bstr => format!("DynCom.bstr({variable})"), ComType::PointerAlias { name, kind: PointerAliasKind::HandleValue, + .. } if name == "HWND" => { format!("DynCom.pointer(DynCom.handleValue({variable}))") } @@ -133,12 +243,57 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { .. } => format!("DynCom.ansiStringPointer({variable})"), ComType::PointerAlias { .. } => format!("DynCom.pointer({variable})"), + ComType::NativePod { layout } | ComType::NativePodPointer { layout } => format!( + "DynCom.nativeStruct({}, {variable})", + native_pod_layout_js(layout) + ), + ComType::NativeUnionPointer { layout } => format!( + "DynCom.nativeUnion({}, {variable})", + native_union_layout_js(layout) + ), + ComType::Variant => format!("DynCom.variant({variable})"), + ComType::VariantByValue => format!("DynCom.variant({variable})"), + ComType::SafeArray { .. } => format!("DynCom.safeArray({variable})"), + ComType::PropVariant => format!("DynCom.propVariant({variable})"), + ComType::DispatchParams => format!("DynCom.dispatchParams({variable})"), + ComType::ExcepInfo => unreachable!("EXCEPINFO is output-only"), ComType::ManagedInterface { .. } => variable.to_string(), + ComType::CoTaskMemWideString => { + unreachable!("CoTaskMem string elements are output-only") + } + ComType::StringArray { encoding, .. } => match encoding { + StringEncoding::Wide => format!("DynCom.wideStringArray({variable})"), + StringEncoding::Ansi => format!("DynCom.ansiStringArray({variable})"), + }, + ComType::TypedBuffer { element } => match element.as_ref() { + ComType::NativePod { layout } => format!( + "DynCom.nativeStructBuffer({}, {variable})", + native_pod_layout_js(layout) + ), + _ => format!("DynCom.buffer({variable})"), + }, + ComType::OwningArray { element, interface } => match element.as_ref() { + ComType::ManagedInterface { iid } => { + if interface.is_some() { + format!( + "DynCom.interfaceArray(WinGuid.parse('{iid}'), {variable}.map(value => value._obj))" + ) + } else { + format!("DynCom.interfaceArray(WinGuid.parse('{iid}'), {variable})") + } + } + ComType::Bstr => format!("DynCom.bstrArray({variable})"), + ComType::Variant => format!("DynCom.variantArray({variable})"), + ComType::CoTaskMemWideString => { + unreachable!("CoTaskMem string elements are output-only") + } + _ => unreachable!("validated owning array element"), + }, } } pub(super) fn unwrap_result_js(result: &ProjectedComResult, expression: &str) -> String { - match result.conversion { + match &result.conversion { ResultConversion::Bstr => format!("DynCom.takeBstr({expression})"), ResultConversion::CoTaskMemString(StringEncoding::Wide) => { format!("DynCom.takeCoTaskMemWideString({expression})") @@ -153,7 +308,36 @@ pub(super) fn unwrap_result_js(result: &ProjectedComResult, expression: &str) -> expression.to_string() } ResultConversion::HString => format!("{expression}.toString()"), - ResultConversion::Value => unwrap_value_js(&result.typ, expression), + ResultConversion::Value | ResultConversion::BorrowedHandle => { + unwrap_value_js(&result.typ, expression) + } + ResultConversion::Buffer => format!("DynCom.takeBuffer({expression})"), + ResultConversion::PlainArray => { + let ComType::TypedBuffer { element } = &result.typ else { + unreachable!("plain array result requires a typed-buffer result") + }; + unwrap_array_result_js(element, None, expression) + } + ResultConversion::EnumeratorArray { interface } => { + let (element, projected_interface) = projected_array_parts(&result.typ); + unwrap_array_result_js( + element, + interface.as_ref().or(projected_interface), + expression, + ) + } + ResultConversion::OwningArray { interface } => { + let (element, projected_interface) = projected_array_parts(&result.typ); + unwrap_array_result_js( + element, + interface.as_ref().or(projected_interface), + expression, + ) + } + ResultConversion::Variant => format!("DynCom.takeVariant({expression})"), + ResultConversion::SafeArray => format!("DynCom.takeSafeArray({expression})"), + ResultConversion::PropVariant => format!("DynCom.takePropVariant({expression})"), + ResultConversion::ExcepInfo => format!("DynCom.takeExcepInfo({expression})"), } } @@ -182,10 +366,240 @@ fn unwrap_value_js(typ: &ComType, expression: &str) -> String { ComType::HString => format!("{expression}.toString()"), ComType::Enum { underlying, .. } => unwrap_enum_js(*underlying, expression), ComType::ScalarAlias { underlying, .. } => unwrap_scalar_js(*underlying, expression), - ComType::RawPointer | ComType::PointerAlias { .. } | ComType::Bstr => { + ComType::RawPointer | ComType::PointerAlias { .. } => { format!("DynCom.asPointerBigint({expression})") } + ComType::Bstr => unreachable!("BSTR outputs require the BSTR result conversion"), + ComType::NativePod { layout } | ComType::NativePodPointer { layout } => format!( + "DynCom.nativeStructBytes({}, {expression})", + native_pod_layout_js(layout) + ), + ComType::NativeUnionPointer { .. } => { + unreachable!("native union outputs require an active-field contract") + } + ComType::Variant => format!("DynCom.takeVariant({expression})"), + ComType::VariantByValue => unreachable!("by-value VARIANT is input-only"), + ComType::SafeArray { .. } => format!("DynCom.takeSafeArray({expression})"), + ComType::PropVariant => format!("DynCom.takePropVariant({expression})"), + ComType::DispatchParams => unreachable!("DISPPARAMS is input-only"), + ComType::ExcepInfo => format!("DynCom.takeExcepInfo({expression})"), ComType::ManagedInterface { .. } => expression.to_string(), + ComType::CoTaskMemWideString => { + unreachable!("CoTaskMem string elements are array-only") + } + ComType::StringArray { .. } => { + unreachable!("string arrays are input-only") + } + ComType::TypedBuffer { .. } => format!("DynCom.takeBuffer({expression})"), + ComType::OwningArray { .. } => { + unreachable!("owning arrays require an explicit array result conversion") + } + } +} + +fn projected_array_parts( + typ: &ComType, +) -> (&ComType, Option<&super::super::ir::ProjectedInterfaceRef>) { + match typ { + ComType::TypedBuffer { element } => (element, None), + ComType::OwningArray { element, interface } => (element, interface.as_ref()), + _ => unreachable!("array result requires a projected array type"), + } +} + +fn unwrap_array_result_js( + element: &ComType, + interface: Option<&super::super::ir::ProjectedInterfaceRef>, + expression: &str, +) -> String { + if let Some(interface) = interface { + return format!( + "Array.from(DynCom.takeComArray({expression}), value => {}._fromNative(value))", + interface.name + ); + } + match element { + ComType::Bstr => format!("Array.from(DynCom.takeBstrArray({expression}))"), + ComType::Variant => format!("Array.from(DynCom.takeVariantArray({expression}))"), + ComType::CoTaskMemWideString => { + format!("Array.from(DynCom.takeCoTaskMemWideStringArray({expression}))") + } + ComType::Guid => format!("Array.from(DynCom.takeGuidArray({expression}))"), + ComType::NativePod { layout } => format!( + "Array.from(DynCom.takeNativeStructArray({expression}, {}))", + native_pod_layout_js(layout) + ), + ComType::ManagedInterface { .. } => { + format!("Array.from(DynCom.takeComArray({expression}))") + } + element => format!( + "Array.from(DynCom.{}({expression}))", + scalar_array_take_method(element) + ), + } +} + +fn scalar_array_take_method(typ: &ComType) -> &'static str { + match typ { + ComType::Primitive(primitive) => match primitive { + ComPrimitive::Bool => "takeBoolArray", + ComPrimitive::I8 => "takeI8Array", + ComPrimitive::U8 => "takeU8Array", + ComPrimitive::I16 => "takeI16Array", + ComPrimitive::U16 | ComPrimitive::Char16 => "takeU16Array", + ComPrimitive::I32 => "takeI32Array", + ComPrimitive::U32 => "takeU32Array", + ComPrimitive::I64 => "takeI64Array", + ComPrimitive::U64 => "takeU64Array", + ComPrimitive::F32 => "takeF32Array", + ComPrimitive::F64 => "takeF64Array", + }, + ComType::NativeIsize => "takeIsizeArray", + ComType::NativeUsize => "takeUsizeArray", + ComType::Win32Bool => "takeWin32BoolArray", + ComType::HResult => "takeI32Array", + ComType::Enum { underlying, .. } => match underlying { + ComEnumUnderlying::I8 => "takeI8Array", + ComEnumUnderlying::U8 => "takeU8Array", + ComEnumUnderlying::I16 => "takeI16Array", + ComEnumUnderlying::U16 => "takeU16Array", + ComEnumUnderlying::I32 => "takeI32Array", + ComEnumUnderlying::U32 => "takeU32Array", + ComEnumUnderlying::I64 => "takeI64Array", + ComEnumUnderlying::U64 => "takeU64Array", + }, + ComType::ScalarAlias { underlying, .. } => match underlying { + ComScalarRepr::Primitive(primitive) => { + scalar_array_take_method(&ComType::Primitive(*primitive)) + } + ComScalarRepr::NativeIsize => "takeIsizeArray", + ComScalarRepr::NativeUsize => "takeUsizeArray", + }, + _ => unreachable!("validated plain array output element"), + } +} + +pub(super) fn native_pod_layout_js(layout: &NativePodLayout) -> String { + format!("_nativeLayout_{}", layout.name) +} + +pub(super) fn native_pod_descriptor_js(layout: &NativePodLayout) -> String { + let descriptor = format!( + "{{\"name\":\"{}.{}\",\"x86\":{},\"x64\":{},\"arm64\":{}}}", + layout.namespace, + layout.name, + native_pod_architecture_json(&layout.x86), + native_pod_architecture_json(&layout.x64), + native_pod_architecture_json(&layout.arm64), + ); + format!( + "'{}'", + descriptor.replace('\\', "\\\\").replace('\'', "\\'") + ) +} + +pub(super) fn native_union_layout_js(layout: &NativeUnionLayout) -> String { + format!("_nativeUnionLayout_{}", layout.name) +} + +pub(super) fn native_union_descriptor_js(layout: &NativeUnionLayout) -> String { + let descriptor = format!( + "{{\"name\":\"{}.{}\",\"x86\":{},\"x64\":{},\"arm64\":{}}}", + layout.namespace, + layout.name, + native_union_architecture_json(&layout.x86), + native_union_architecture_json(&layout.x64), + native_union_architecture_json(&layout.arm64), + ); + format!( + "'{}'", + descriptor.replace('\\', "\\\\").replace('\'', "\\'") + ) +} + +fn native_pod_architecture_json(layout: &NativePodArchitectureLayout) -> String { + let fields = layout + .fields + .iter() + .map(|field| { + format!( + "{{\"name\":\"{}\",\"offset\":{},\"count\":{},\"type\":{}}}", + field.name, + field.offset, + field.count, + native_pod_field_type_json(&field.typ), + ) + }) + .collect::>() + .join(","); + format!( + "{{\"size\":{},\"alignment\":{},\"fields\":[{}]}}", + layout.size, layout.alignment, fields + ) +} + +fn native_pod_field_type_json(typ: &NativePodFieldType) -> String { + match typ { + NativePodFieldType::Scalar(scalar) => { + format!("{{\"kind\":\"{}\"}}", native_pod_scalar_name(*scalar)) + } + NativePodFieldType::Guid => "{\"kind\":\"guid\"}".into(), + NativePodFieldType::Pointer => "{\"kind\":\"pointer\"}".into(), + NativePodFieldType::Struct { name, layout } => format!( + "{{\"kind\":\"struct\",\"name\":\"{name}\",\"layout\":{}}}", + native_pod_architecture_json(layout) + ), + } +} + +fn native_union_architecture_json(layout: &NativeUnionArchitectureLayout) -> String { + let fields = layout + .fields + .iter() + .map(|field| { + format!( + "{{\"name\":\"{}\",\"count\":{},\"type\":{}}}", + field.name, + field.count, + native_union_field_type_json(&field.typ), + ) + }) + .collect::>() + .join(","); + format!( + "{{\"size\":{},\"alignment\":{},\"fields\":[{}]}}", + layout.size, layout.alignment, fields + ) +} + +fn native_union_field_type_json(typ: &NativeUnionFieldType) -> String { + match typ { + NativeUnionFieldType::Scalar(scalar) => { + format!("{{\"kind\":\"{}\"}}", native_pod_scalar_name(*scalar)) + } + NativeUnionFieldType::Guid => "{\"kind\":\"guid\"}".into(), + NativeUnionFieldType::Pointer => "{\"kind\":\"pointer\"}".into(), + NativeUnionFieldType::Struct { name, layout } => format!( + "{{\"kind\":\"struct\",\"name\":\"{name}\",\"layout\":{}}}", + native_pod_architecture_json(layout) + ), + } +} + +fn native_pod_scalar_name(scalar: NativePodScalar) -> &'static str { + match scalar { + NativePodScalar::I8 => "i8", + NativePodScalar::U8 => "u8", + NativePodScalar::I16 => "i16", + NativePodScalar::U16 => "u16", + NativePodScalar::I32 => "i32", + NativePodScalar::U32 => "u32", + NativePodScalar::I64 => "i64", + NativePodScalar::U64 => "u64", + NativePodScalar::F32 => "f32", + NativePodScalar::F64 => "f64", + NativePodScalar::NativeIsize => "isize", + NativePodScalar::NativeUsize => "usize", } } @@ -306,6 +720,83 @@ fn unwrap_enum_js(underlying: ComEnumUnderlying, expression: &str) -> String { mod tests { use super::*; + fn pod_layout() -> NativePodLayout { + let architecture = NativePodArchitectureLayout { + size: 8, + alignment: 4, + fields: vec![ + NativePodField { + name: "value".into(), + offset: 0, + count: 1, + typ: NativePodFieldType::Scalar(NativePodScalar::U32), + }, + NativePodField { + name: "parts".into(), + offset: 4, + count: 2, + typ: NativePodFieldType::Scalar(NativePodScalar::U16), + }, + ], + }; + NativePodLayout { + namespace: "Test".into(), + name: "POD".into(), + x86: architecture.clone(), + x64: architecture.clone(), + arm64: architecture, + } + } + + fn union_layout() -> NativeUnionLayout { + let architecture = NativeUnionArchitectureLayout { + size: 8, + alignment: 8, + fields: vec![ + NativeUnionField { + name: "integer".into(), + count: 1, + typ: NativeUnionFieldType::Scalar(NativePodScalar::U64), + }, + NativeUnionField { + name: "pointer".into(), + count: 1, + typ: NativeUnionFieldType::Pointer, + }, + ], + }; + NativeUnionLayout { + namespace: "Test".into(), + name: "UNION".into(), + x86: architecture.clone(), + x64: architecture.clone(), + arm64: architecture, + } + } + + #[test] + fn native_pod_rendering_uses_only_validated_runtime_primitives() { + let typ = ComType::NativePod { + layout: pod_layout(), + }; + assert!(abi_type_js(&typ).starts_with("DynCom.nativeStructType(")); + assert_eq!(type_dts(&typ), "POD"); + assert!(wrap_arg_js(&typ, "value").starts_with("DynCom.nativeStruct(")); + assert!(unwrap_value_js(&typ, "result").starts_with("DynCom.nativeStructBytes(")); + let descriptor = native_pod_descriptor_js(match &typ { + ComType::NativePod { layout } => layout, + _ => unreachable!(), + }); + assert!(descriptor.contains("\"x86\":{\"size\":8")); + assert!(descriptor.contains("\"count\":2")); + + let pointer = ComType::NativePodPointer { + layout: pod_layout(), + }; + assert!(abi_type_js(&pointer).starts_with("DynCom.nativeStructPointerType(")); + assert!(wrap_arg_js(&pointer, "value").starts_with("DynCom.nativeStruct(")); + } + #[test] fn mappings_cover_every_supported_com_type() { let types = vec![ @@ -328,19 +819,30 @@ mod tests { ComType::Guid, ComType::HString, ComType::Enum { + namespace: "Tests".into(), name: "E".into(), underlying: ComEnumUnderlying::U32, }, ComType::ScalarAlias { + namespace: "Tests".into(), name: "COLORREF".into(), underlying: ComScalarRepr::Primitive(ComPrimitive::U32), }, ComType::RawPointer, ComType::PointerAlias { + namespace: "Tests".into(), name: "HWND".into(), kind: PointerAliasKind::HandleValue, }, ComType::Bstr, + ComType::NativeUnionPointer { + layout: union_layout(), + }, + ComType::Variant, + ComType::SafeArray { + element: SafeArrayElement::Bstr, + }, + ComType::PropVariant, ComType::ManagedInterface { iid: "00000000-0000-0000-0000-000000000000".into(), }, diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index 35a14444..3442728e 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -5,6 +5,7 @@ mod ir; mod javascript; +mod model; mod project; use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; @@ -16,7 +17,81 @@ pub fn generate_com_interface_files( winmd_paths: &str, ) -> Result { let projected = project::project_com_interface(meta, winmd_paths)?; - Ok(javascript::render::render_com_interface(&projected)) + let mut output = javascript::render::render_com_interface(&projected); + let mut pending = enumerator_interface_refs(&projected); + let mut generated = std::collections::BTreeSet::from([( + meta.interface.namespace.clone(), + meta.interface.name.clone(), + )]); + let mut extras = output + .extra_files + .drain(..) + .collect::>(); + while let Some((namespace, name)) = pending.pop_first() { + if !generated.insert((namespace.clone(), name.clone())) { + continue; + } + let referenced = crate::com_metadata::parse_com_interface(winmd_paths, &namespace, &name) + .ok_or_else(|| { + format!("owning array element interface {namespace}.{name} could not be resolved") + })?; + let projected = project::project_com_interface(&referenced, winmd_paths) + .or_else(|_| project::project_com_reference_interface(&referenced))?; + pending.extend(enumerator_interface_refs(&projected)); + let rendered = javascript::render::render_com_interface(&projected); + insert_extra(&mut extras, format!("{name}.js"), rendered.js)?; + insert_extra(&mut extras, format!("{name}.d.ts"), rendered.dts)?; + for (file, content) in rendered.extra_files { + insert_extra(&mut extras, file, content)?; + } + } + output.extra_files = extras.into_iter().collect(); + Ok(output) +} + +fn enumerator_interface_refs( + projected: &ir::ProjectedComInterface, +) -> std::collections::BTreeSet<(String, String)> { + let mut refs = std::collections::BTreeSet::new(); + for method in &projected.methods { + if let ir::ProjectedComMethodKind::EnumeratorNext { + interface: Some(interface), + .. + } = &method.kind + { + refs.insert((interface.namespace.clone(), interface.name.clone())); + } + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + { + if let ir::ComType::OwningArray { + interface: Some(interface), + .. + } = typ + { + refs.insert((interface.namespace.clone(), interface.name.clone())); + } + } + } + refs +} + +fn insert_extra( + extras: &mut std::collections::BTreeMap, + file: String, + content: String, +) -> Result<(), String> { + if let Some(existing) = extras.insert(file.clone(), content.clone()) + && existing != content + { + return Err(format!( + "EnumeratorNext referenced interface generation produced conflicting `{file}`" + )); + } + Ok(()) } pub fn generate_com_coclass_files( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs new file mode 100644 index 00000000..c43a48e2 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs @@ -0,0 +1,668 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::num::NonZeroU8; + +use super::diagnostics::{ModelError, UnsupportedReason}; +use super::ids::{ComGuid, EnumId, LayoutId, SignatureId, TypeId}; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(in crate::codegen::com) struct QualifiedName { + namespace: String, + name: String, +} + +impl QualifiedName { + pub(super) fn new( + namespace: impl Into, + name: impl Into, + ) -> Result { + let namespace = namespace.into(); + let name = name.into(); + if namespace.trim().is_empty() || name.trim().is_empty() { + return Err(ModelError::InvalidName(format!("{namespace}.{name}"))); + } + Ok(Self { namespace, name }) + } + + pub(in crate::codegen::com) fn namespace(&self) -> &str { + &self.namespace + } + + pub(in crate::codegen::com) fn name(&self) -> &str { + &self.name + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum ScalarType { + Bool, + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + Char16, + NativeIsize, + NativeUsize, + Win32Bool, + HResult, +} + +impl ScalarType { + pub(super) const fn is_integer(self) -> bool { + !matches!(self, Self::F32 | Self::F64) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum Constness { + Const, + Mutable, + Unspecified, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum StringEncoding { + Utf16, + Ansi, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum CallingConvention { + System, + Stdcall, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct HandleKind { + native_name: QualifiedName, +} + +impl HandleKind { + pub(super) const fn new(native_name: QualifiedName) -> Self { + Self { native_name } + } + + pub(in crate::codegen::com) const fn native_name(&self) -> &QualifiedName { + &self.native_name + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum DataPointee { + Typed(TypeId), + Opaque(Option), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum BufferElement { + Typed(TypeId), + Character(StringEncoding), + StringPointer { + encoding: StringEncoding, + pointer_depth: NonZeroU8, + constness: Constness, + }, + Opaque(QualifiedName), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum BufferElementOwnership { + Plain, + Borrowed, + ComOwned, + BstrOwned, + VariantOwned, + CoTaskMemStringOwned, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum ComAbiType { + Scalar(ScalarType), + Guid, + Enum(EnumId), + NativeStruct(LayoutId), + NativeUnion(LayoutId), + Pointer { + pointee: TypeId, + depth: NonZeroU8, + constness: Constness, + }, + Handle(HandleKind), + DataPointer { + pointee: DataPointee, + depth: NonZeroU8, + constness: Constness, + }, + StringPointer { + encoding: StringEncoding, + constness: Constness, + }, + Bstr, + HString, + ComInterface { + iid: ComGuid, + }, + CountedBuffer { + element: BufferElement, + element_ownership: BufferElementOwnership, + pointer_depth: NonZeroU8, + constness: Constness, + }, + SafeArray { + element: Option, + }, + Variant, + PropVariant, + DispatchParams, + ExcepInfo, + FunctionPointer(SignatureId), + Unknown(UnsupportedReason), +} + +impl ComAbiType { + pub(super) fn requires_pointer_return_convention(&self) -> bool { + matches!( + self, + Self::Pointer { .. } + | Self::DataPointer { .. } + | Self::StringPointer { .. } + | Self::Bstr + | Self::ComInterface { .. } + | Self::CountedBuffer { .. } + | Self::SafeArray { .. } + | Self::FunctionPointer(_) + ) + } + + pub(super) fn referenced_types(&self) -> impl Iterator { + let referenced = match self { + Self::Pointer { pointee, .. } => Some(*pointee), + Self::DataPointer { + pointee: DataPointee::Typed(pointee), + .. + } => Some(*pointee), + Self::CountedBuffer { + element: BufferElement::Typed(element), + .. + } + | Self::SafeArray { + element: Some(element), + } => Some(*element), + _ => None, + }; + referenced.into_iter() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct ComTypeDefinition { + native_name: Option, + underlying: Option, + abi: ComAbiType, +} + +impl ComTypeDefinition { + pub(super) const fn new( + native_name: Option, + underlying: Option, + abi: ComAbiType, + ) -> Self { + Self { + native_name, + underlying, + abi, + } + } + + pub(in crate::codegen::com) const fn native_name(&self) -> Option<&QualifiedName> { + self.native_name.as_ref() + } + + pub(in crate::codegen::com) const fn underlying(&self) -> Option { + self.underlying + } + + pub(in crate::codegen::com) const fn abi(&self) -> &ComAbiType { + &self.abi + } + + pub(super) fn referenced_types(&self) -> impl Iterator + '_ { + self.underlying + .into_iter() + .chain(self.abi.referenced_types()) + } +} + +#[derive(Debug, Default)] +pub(super) struct ComTypeTable { + definitions: Vec>, +} + +impl ComTypeTable { + pub(super) fn reserve(&mut self) -> Result { + let id = TypeId::from_index(self.definitions.len()) + .ok_or(ModelError::CapacityExceeded("COM type"))?; + self.definitions.push(None); + Ok(id) + } + + pub(super) fn insert(&mut self, definition: ComTypeDefinition) -> Result { + let id = self.reserve()?; + self.define(id, definition)?; + Ok(id) + } + + pub(super) fn define( + &mut self, + id: TypeId, + definition: ComTypeDefinition, + ) -> Result<(), ModelError> { + let Some(slot) = self.definitions.get(id.index()) else { + return Err(ModelError::UnknownId { + kind: "COM type", + index: id.index(), + }); + }; + if slot.is_some() { + return Err(ModelError::DuplicateDefinition { + kind: "COM type", + index: id.index(), + }); + } + for referenced in definition.referenced_types() { + if referenced.index() >= self.definitions.len() { + return Err(ModelError::UnknownId { + kind: "COM type", + index: referenced.index(), + }); + } + } + self.definitions[id.index()] = Some(definition); + Ok(()) + } + + pub(super) fn get(&self, id: TypeId) -> Result<&ComTypeDefinition, ModelError> { + match self.definitions.get(id.index()) { + Some(Some(definition)) => Ok(definition), + Some(None) => Err(ModelError::IncompleteDefinition { + kind: "COM type", + index: id.index(), + }), + None => Err(ModelError::UnknownId { + kind: "COM type", + index: id.index(), + }), + } + } + + pub(super) fn validate_complete(&self) -> Result<(), ModelError> { + for (index, definition) in self.definitions.iter().enumerate() { + if definition.is_none() { + return Err(ModelError::IncompleteDefinition { + kind: "COM type", + index, + }); + } + } + Ok(()) + } + + pub(super) fn ids(&self) -> impl Iterator + '_ { + (0..self.definitions.len()).filter_map(TypeId::from_index) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum ComEnumValue { + Signed(i64), + Unsigned(u64), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct ComEnumMember { + name: String, + value: ComEnumValue, +} + +impl ComEnumMember { + pub(super) fn new(name: String, value: ComEnumValue) -> Self { + Self { name, value } + } + + pub(in crate::codegen::com) fn name(&self) -> &str { + &self.name + } + + pub(in crate::codegen::com) const fn value(&self) -> &ComEnumValue { + &self.value + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct ComEnumDefinition { + native_name: QualifiedName, + underlying: ScalarType, + members: Vec, + is_flags: bool, +} + +impl ComEnumDefinition { + pub(super) fn new( + native_name: QualifiedName, + underlying: ScalarType, + ) -> Result { + if !underlying.is_integer() { + return Err(ModelError::InvalidContract(format!( + "enum {}.{} cannot use non-integer underlying type {underlying:?}", + native_name.namespace(), + native_name.name() + ))); + } + Ok(Self { + native_name, + underlying, + members: Vec::new(), + is_flags: false, + }) + } + + pub(super) fn set_members(&mut self, members: Vec, is_flags: bool) { + self.members = members; + self.is_flags = is_flags; + } + + pub(in crate::codegen::com) const fn native_name(&self) -> &QualifiedName { + &self.native_name + } + + pub(in crate::codegen::com) const fn underlying(&self) -> ScalarType { + self.underlying + } + + pub(in crate::codegen::com) fn members(&self) -> &[ComEnumMember] { + &self.members + } + + pub(in crate::codegen::com) const fn is_flags(&self) -> bool { + self.is_flags + } +} + +#[derive(Debug, Default)] +pub(super) struct EnumTable { + definitions: Vec, +} + +impl EnumTable { + pub(super) fn insert(&mut self, definition: ComEnumDefinition) -> Result { + let id = EnumId::from_index(self.definitions.len()) + .ok_or(ModelError::CapacityExceeded("enum"))?; + self.definitions.push(definition); + Ok(id) + } + + pub(super) fn get(&self, id: EnumId) -> Result<&ComEnumDefinition, ModelError> { + self.definitions + .get(id.index()) + .ok_or(ModelError::UnknownId { + kind: "enum", + index: id.index(), + }) + } + + pub(super) fn get_mut(&mut self, id: EnumId) -> Result<&mut ComEnumDefinition, ModelError> { + self.definitions + .get_mut(id.index()) + .ok_or(ModelError::UnknownId { + kind: "enum", + index: id.index(), + }) + } + + pub(super) fn ids(&self) -> impl Iterator + '_ { + (0..self.definitions.len()).filter_map(EnumId::from_index) + } + + pub(super) fn iter(&self) -> impl Iterator { + self.definitions.iter() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum FunctionReturn { + Void, + Value(TypeId), + Pointer(TypeId), +} + +impl FunctionReturn { + pub(super) const fn abi_type(self) -> Option { + match self { + Self::Void => None, + Self::Value(abi_type) | Self::Pointer(abi_type) => Some(abi_type), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct FunctionSignature { + calling_convention: CallingConvention, + params: Vec, + return_kind: FunctionReturn, +} + +impl FunctionSignature { + pub(super) const fn new( + calling_convention: CallingConvention, + params: Vec, + return_kind: FunctionReturn, + ) -> Self { + Self { + calling_convention, + params, + return_kind, + } + } + + pub(super) const fn calling_convention(&self) -> CallingConvention { + self.calling_convention + } + + pub(super) fn params(&self) -> &[TypeId] { + &self.params + } + + pub(super) const fn return_kind(&self) -> FunctionReturn { + self.return_kind + } +} + +#[derive(Debug, Default)] +pub(super) struct SignatureTable { + definitions: Vec>, +} + +impl SignatureTable { + pub(super) fn reserve(&mut self) -> Result { + let id = SignatureId::from_index(self.definitions.len()) + .ok_or(ModelError::CapacityExceeded("function signature"))?; + self.definitions.push(None); + Ok(id) + } + + pub(super) fn insert( + &mut self, + definition: FunctionSignature, + ) -> Result { + let id = self.reserve()?; + self.define(id, definition)?; + Ok(id) + } + + pub(super) fn define( + &mut self, + id: SignatureId, + definition: FunctionSignature, + ) -> Result<(), ModelError> { + let Some(slot) = self.definitions.get_mut(id.index()) else { + return Err(ModelError::UnknownId { + kind: "function signature", + index: id.index(), + }); + }; + if slot.is_some() { + return Err(ModelError::DuplicateDefinition { + kind: "function signature", + index: id.index(), + }); + } + *slot = Some(definition); + Ok(()) + } + + pub(super) fn get(&self, id: SignatureId) -> Result<&FunctionSignature, ModelError> { + match self.definitions.get(id.index()) { + Some(Some(definition)) => Ok(definition), + Some(None) => Err(ModelError::IncompleteDefinition { + kind: "function signature", + index: id.index(), + }), + None => Err(ModelError::UnknownId { + kind: "function signature", + index: id.index(), + }), + } + } + + pub(super) fn validate_complete(&self) -> Result<(), ModelError> { + for (index, definition) in self.definitions.iter().enumerate() { + if definition.is_none() { + return Err(ModelError::IncompleteDefinition { + kind: "function signature", + index, + }); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroU8; + + use super::*; + + fn unnamed(abi: ComAbiType) -> ComTypeDefinition { + ComTypeDefinition::new(None, None, abi) + } + + #[test] + fn reserved_ids_support_recursive_pointer_graphs() { + let mut table = ComTypeTable::default(); + let node = table.reserve().unwrap(); + let node_pointer = table + .insert(unnamed(ComAbiType::Pointer { + pointee: node, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + })) + .unwrap(); + table + .define( + node, + ComTypeDefinition::new( + Some(QualifiedName::new("Example", "NODE").unwrap()), + None, + ComAbiType::DataPointer { + pointee: DataPointee::Typed(node_pointer), + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + ), + ) + .unwrap(); + + table.validate_complete().unwrap(); + assert!(table.get(node).is_ok()); + } + + #[test] + fn unknown_nested_types_fail_closed() { + let mut table = ComTypeTable::default(); + let unknown = table + .insert(unnamed(ComAbiType::Unknown( + UnsupportedReason::UnknownPointerMeaning, + ))) + .unwrap(); + let buffer = table + .insert(unnamed(ComAbiType::CountedBuffer { + element: BufferElement::Typed(unknown), + element_ownership: BufferElementOwnership::Unknown, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + })) + .unwrap(); + + assert_eq!( + table.get(buffer).unwrap().abi(), + &ComAbiType::CountedBuffer { + element: BufferElement::Typed(unknown), + element_ownership: BufferElementOwnership::Unknown, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + } + ); + } + + #[test] + fn aliases_preserve_native_and_underlying_identity() { + let mut table = ComTypeTable::default(); + let u32_type = table + .insert(unnamed(ComAbiType::Scalar(ScalarType::U32))) + .unwrap(); + let colorref = table + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Windows.Win32.Foundation", "COLORREF").unwrap()), + Some(u32_type), + ComAbiType::Scalar(ScalarType::U32), + )) + .unwrap(); + let definition = table.get(colorref).unwrap(); + + assert_eq!(definition.underlying(), Some(u32_type)); + assert_eq!(definition.native_name().unwrap().name(), "COLORREF"); + assert_eq!( + definition.native_name().unwrap().namespace(), + "Windows.Win32.Foundation" + ); + } + + #[test] + fn direct_pointer_convention_is_semantic_not_pointer_width() { + assert!( + ComAbiType::ComInterface { + iid: ComGuid::from_bytes([1; 16]) + } + .requires_pointer_return_convention() + ); + assert!( + !ComAbiType::Handle(HandleKind::new( + QualifiedName::new("Windows.Win32.Foundation", "HWND").unwrap() + )) + .requires_pointer_return_convention() + ); + assert!( + !ComAbiType::HString.requires_pointer_return_convention(), + "opaque handles are direct values even when pointer-width" + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/contract.rs b/tools/dynwinrt-codegen/src/codegen/com/model/contract.rs new file mode 100644 index 00000000..cb673dc7 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/contract.rs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::diagnostics::ModelError; +use super::ids::{ParamIndex, TypeId}; +use super::ownership::{Cleanup, ComOwnership, validate_ownership_cleanup}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum Direction { + In, + Out, + InOut, +} + +impl Direction { + pub(in crate::codegen::com) const fn is_input(self) -> bool { + matches!(self, Self::In | Self::InOut) + } + + pub(super) const fn is_output(self) -> bool { + matches!(self, Self::Out | Self::InOut) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum Nullability { + Required, + Nullable, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum CountUnit { + Elements, + Bytes, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum BufferSizing { + SingleCall, + FixedCapacity, + TwoCall { max_retries: u8 }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum CountRelation { + InputCount { + count_param: ParamIndex, + actual_length_param: Option, + unit: CountUnit, + }, + CallerCapacity { + capacity_param: ParamIndex, + actual_length_param: Option, + unit: CountUnit, + sizing: BufferSizing, + }, + EnumeratorNext { + capacity_param: ParamIndex, + fetched_param: ParamIndex, + fetched_optional_for_single: bool, + }, + CalleeAllocated { + count_param: ParamIndex, + unit: CountUnit, + }, +} + +impl CountRelation { + fn referenced_params(&self) -> impl Iterator { + let (first, second) = match self { + Self::InputCount { + count_param, + actual_length_param, + .. + } => (*count_param, *actual_length_param), + Self::CalleeAllocated { count_param, .. } => (*count_param, None), + Self::CallerCapacity { + capacity_param, + actual_length_param, + .. + } => (*capacity_param, *actual_length_param), + Self::EnumeratorNext { + capacity_param, + fetched_param, + .. + } => (*capacity_param, Some(*fetched_param)), + }; + std::iter::once(first).chain(second) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct ComParamContract { + name: String, + abi_type: TypeId, + direction: Direction, + optional: bool, + nullability: Nullability, + count: Option, + ownership: ComOwnership, + cleanup: Cleanup, +} + +impl ComParamContract { + #[allow(clippy::too_many_arguments)] + pub(super) fn new( + name: impl Into, + abi_type: TypeId, + direction: Direction, + optional: bool, + nullability: Nullability, + count: Option, + ownership: ComOwnership, + cleanup: Cleanup, + ) -> Result { + let name = name.into(); + if name.trim().is_empty() { + return Err(ModelError::InvalidContract( + "parameter name must not be empty".into(), + )); + } + validate_ownership_cleanup(&ownership, &cleanup)?; + Ok(Self { + name, + abi_type, + direction, + optional, + nullability, + count, + ownership, + cleanup, + }) + } + + pub(in crate::codegen::com) fn name(&self) -> &str { + &self.name + } + + pub(in crate::codegen::com) const fn abi_type(&self) -> TypeId { + self.abi_type + } + + pub(in crate::codegen::com) const fn direction(&self) -> Direction { + self.direction + } + + pub(in crate::codegen::com) const fn optional(&self) -> bool { + self.optional + } + + pub(in crate::codegen::com) const fn nullability(&self) -> Nullability { + self.nullability + } + + pub(in crate::codegen::com) const fn count(&self) -> Option<&CountRelation> { + self.count.as_ref() + } + + pub(in crate::codegen::com) const fn ownership(&self) -> &ComOwnership { + &self.ownership + } + + pub(in crate::codegen::com) const fn cleanup(&self) -> &Cleanup { + &self.cleanup + } + + pub(super) fn validate_param_references( + &self, + own_index: ParamIndex, + param_count: usize, + ) -> Result<(), ModelError> { + if let Some(count) = &self.count { + for referenced in count.referenced_params() { + validate_distinct_param_reference("count", own_index, referenced, param_count)?; + } + } + Ok(()) + } +} + +fn validate_distinct_param_reference( + role: &str, + own_index: ParamIndex, + referenced: ParamIndex, + param_count: usize, +) -> Result<(), ModelError> { + if referenced.index() >= param_count { + return Err(ModelError::InvalidContract(format!( + "{role} parameter index {} is outside the {param_count}-parameter method", + referenced.index() + ))); + } + if referenced == own_index { + return Err(ModelError::InvalidContract(format!( + "parameter {} cannot be its own {role}", + own_index.index() + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn borrowed_param(count: Option) -> ComParamContract { + ComParamContract::new( + "buffer", + TypeId::from_index(0).unwrap(), + Direction::In, + false, + Nullability::Required, + count, + ComOwnership::Borrowed, + Cleanup::None, + ) + .unwrap() + } + + #[test] + fn parameter_relationships_are_indexed_and_bounded() { + let param = borrowed_param(Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Bytes, + })); + param + .validate_param_references(ParamIndex::new(0), 2) + .unwrap(); + assert!(param.direction().is_input()); + assert!(!param.direction().is_output()); + assert_eq!(param.nullability(), Nullability::Required); + assert!(param.count().is_some()); + + assert!( + borrowed_param(Some(CountRelation::InputCount { + count_param: ParamIndex::new(2), + actual_length_param: None, + unit: CountUnit::Elements, + })) + .validate_param_references(ParamIndex::new(0), 2) + .is_err() + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/diagnostics.rs b/tools/dynwinrt-codegen/src/codegen/com/model/diagnostics.rs new file mode 100644 index 00000000..057c123b --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/diagnostics.rs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum UnsupportedReason { + UnknownNativeType, + UnknownPointerMeaning, + UnknownLayout, + UnknownOwnership, + UnknownCleanup, + MissingInterfaceIid, + MissingCountRelationship, + UnsupportedArray, + UnsupportedFunctionPointer, + UnsupportedVariantShape, + UnsupportedSafeArrayElement, + IncompleteInheritedVtable, + Other(String), +} + +impl fmt::Display for UnsupportedReason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownNativeType => f.write_str("unknown native type"), + Self::UnknownPointerMeaning => f.write_str("unknown pointer meaning"), + Self::UnknownLayout => f.write_str("unknown native layout"), + Self::UnknownOwnership => f.write_str("unknown ownership"), + Self::UnknownCleanup => f.write_str("unknown cleanup"), + Self::MissingInterfaceIid => f.write_str("missing interface IID"), + Self::MissingCountRelationship => f.write_str("missing count relationship"), + Self::UnsupportedArray => f.write_str("unsupported array"), + Self::UnsupportedFunctionPointer => f.write_str("unsupported function pointer"), + Self::UnsupportedVariantShape => f.write_str("unsupported VARIANT shape"), + Self::UnsupportedSafeArrayElement => f.write_str("unsupported SAFEARRAY element"), + Self::IncompleteInheritedVtable => f.write_str("incomplete inherited vtable"), + Self::Other(message) => f.write_str(message), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum ModelError { + CapacityExceeded(&'static str), + InvalidName(String), + UnknownId { + kind: &'static str, + index: usize, + }, + DuplicateDefinition { + kind: &'static str, + index: usize, + }, + IncompleteDefinition { + kind: &'static str, + index: usize, + }, + Unsupported(UnsupportedReason), + InvalidLayout(String), + InvalidOwnership(String), + InvalidContract(String), + Context { + context: String, + source: Box, + }, +} + +impl ModelError { + pub(super) fn context(self, context: impl Into) -> Self { + Self::Context { + context: context.into(), + source: Box::new(self), + } + } + + pub(super) fn unsupported_reason(&self) -> Option<&UnsupportedReason> { + match self { + Self::Unsupported(reason) => Some(reason), + Self::Context { source, .. } => source.unsupported_reason(), + _ => None, + } + } +} + +impl fmt::Display for ModelError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CapacityExceeded(kind) => write!(f, "{kind} table exceeds u32 capacity"), + Self::InvalidName(name) => write!(f, "invalid qualified name `{name}`"), + Self::UnknownId { kind, index } => write!(f, "unknown {kind} id {index}"), + Self::DuplicateDefinition { kind, index } => { + write!(f, "{kind} id {index} is already defined") + } + Self::IncompleteDefinition { kind, index } => { + write!(f, "{kind} id {index} is reserved but not defined") + } + Self::Unsupported(reason) => write!(f, "unsupported COM semantic: {reason}"), + Self::InvalidLayout(message) => write!(f, "invalid native layout: {message}"), + Self::InvalidOwnership(message) => write!(f, "invalid ownership: {message}"), + Self::InvalidContract(message) => write!(f, "invalid COM contract: {message}"), + Self::Context { context, source } => write!(f, "{context}: {source}"), + } + } +} + +impl std::error::Error for ModelError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Context { source, .. } => Some(source), + _ => None, + } + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/ids.rs b/tools/dynwinrt-codegen/src/codegen/com/model/ids.rs new file mode 100644 index 00000000..67edae27 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/ids.rs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::diagnostics::ModelError; + +macro_rules! define_id { + ($name:ident) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub(in crate::codegen::com) struct $name(u32); + + impl $name { + pub(super) fn from_index(index: usize) -> Option { + u32::try_from(index).ok().map(Self) + } + + pub(in crate::codegen::com) const fn index(self) -> usize { + self.0 as usize + } + } + }; +} + +define_id!(TypeId); +define_id!(LayoutId); +define_id!(EnumId); +define_id!(SignatureId); +define_id!(CleanupId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(in crate::codegen::com) struct ParamIndex(usize); + +impl ParamIndex { + pub(super) const fn new(index: usize) -> Self { + Self(index) + } + + pub(in crate::codegen::com) const fn index(self) -> usize { + self.0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(in crate::codegen::com) struct ComGuid([u8; 16]); + +impl ComGuid { + pub(super) const ZERO: Self = Self([0; 16]); + + pub(super) const fn from_bytes(bytes: [u8; 16]) -> Self { + Self(bytes) + } + + pub(in crate::codegen::com) const fn as_bytes(&self) -> &[u8; 16] { + &self.0 + } + + pub(super) fn is_zero(self) -> bool { + self == Self::ZERO + } + + pub(super) fn parse(value: &str) -> Result { + if value.len() != 36 + || value.as_bytes().get(8) != Some(&b'-') + || value.as_bytes().get(13) != Some(&b'-') + || value.as_bytes().get(18) != Some(&b'-') + || value.as_bytes().get(23) != Some(&b'-') + { + return Err(ModelError::InvalidContract(format!( + "invalid GUID `{value}`" + ))); + } + let hex = value + .bytes() + .filter(|byte| *byte != b'-') + .collect::>(); + if hex.len() != 32 { + return Err(ModelError::InvalidContract(format!( + "invalid GUID `{value}`" + ))); + } + let mut bytes = [0; 16]; + for (index, pair) in hex.chunks_exact(2).enumerate() { + let high = hex_digit(pair[0]) + .ok_or_else(|| ModelError::InvalidContract(format!("invalid GUID `{value}`")))?; + let low = hex_digit(pair[1]) + .ok_or_else(|| ModelError::InvalidContract(format!("invalid GUID `{value}`")))?; + bytes[index] = (high << 4) | low; + } + Ok(Self(bytes)) + } +} + +fn hex_digit(value: u8) -> Option { + match value { + b'0'..=b'9' => Some(value - b'0'), + b'a'..=b'f' => Some(value - b'a' + 10), + b'A'..=b'F' => Some(value - b'A' + 10), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_round_trip_their_arena_index() { + let id = TypeId::from_index(42).unwrap(); + assert_eq!(id.index(), 42); + #[cfg(target_pointer_width = "64")] + assert!(TypeId::from_index(u32::MAX as usize + 1).is_none()); + #[cfg(target_pointer_width = "32")] + assert_eq!(TypeId::from_index(usize::MAX).unwrap().index(), usize::MAX); + } + + #[test] + fn guid_keeps_all_abi_bytes() { + let guid = ComGuid::from_bytes([0x5a; 16]); + assert_eq!(guid.as_bytes(), &[0x5a; 16]); + assert!(!guid.is_zero()); + assert!(ComGuid::ZERO.is_zero()); + } + + #[test] + fn guid_parser_requires_canonical_shape() { + let guid = ComGuid::parse("00000000-0000-0000-c000-000000000046").unwrap(); + assert!(!guid.is_zero()); + assert!(ComGuid::parse("not-a-guid").is_err()); + assert!(ComGuid::parse("000000000000-0000-c000-000000000046").is_err()); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/layout.rs b/tools/dynwinrt-codegen/src/codegen/com/model/layout.rs new file mode 100644 index 00000000..bae12751 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/layout.rs @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::HashSet; +use std::num::NonZeroU32; + +use super::diagnostics::ModelError; +use super::ids::{LayoutId, TypeId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(in crate::codegen::com) enum Architecture { + X86, + X64, + Arm64, +} + +impl Architecture { + pub(super) const ALL: [Self; 3] = [Self::X86, Self::X64, Self::Arm64]; + + pub(super) const fn metadata_mask(self) -> u8 { + match self { + Self::X86 => 0b001, + Self::X64 => 0b010, + Self::Arm64 => 0b100, + } + } + + pub(super) const fn pointer_size(self) -> usize { + match self { + Self::X86 => 4, + Self::X64 | Self::Arm64 => 8, + } + } + + pub(super) const fn pointer_alignment(self) -> usize { + self.pointer_size() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum StructLayout { + Sequential, + Explicit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum LayoutKind { + Struct(StructLayout), + Union, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct FieldLayout { + name: String, + abi_type: TypeId, + offset: usize, + fixed_count: Option, +} + +impl FieldLayout { + pub(super) fn new( + name: impl Into, + abi_type: TypeId, + offset: usize, + fixed_count: Option, + ) -> Result { + let name = name.into(); + if name.trim().is_empty() { + return Err(ModelError::InvalidLayout( + "field name must not be empty".into(), + )); + } + Ok(Self { + name, + abi_type, + offset, + fixed_count, + }) + } + + pub(in crate::codegen::com) fn name(&self) -> &str { + &self.name + } + + pub(in crate::codegen::com) const fn abi_type(&self) -> TypeId { + self.abi_type + } + + pub(in crate::codegen::com) const fn offset(&self) -> usize { + self.offset + } + + pub(in crate::codegen::com) const fn fixed_count(&self) -> Option { + self.fixed_count + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct NativeLayout { + size: usize, + alignment: usize, + packing: usize, + kind: LayoutKind, + fields: Vec, +} + +impl NativeLayout { + pub(super) fn new( + size: usize, + alignment: usize, + packing: usize, + kind: LayoutKind, + fields: Vec, + ) -> Result { + if size == 0 { + return Err(ModelError::InvalidLayout( + "layout size must be non-zero".into(), + )); + } + if alignment == 0 || !alignment.is_power_of_two() { + return Err(ModelError::InvalidLayout( + "alignment must be a non-zero power of two".into(), + )); + } + if packing == 0 || !packing.is_power_of_two() { + return Err(ModelError::InvalidLayout( + "packing must be a non-zero power of two".into(), + )); + } + if size % alignment != 0 { + return Err(ModelError::InvalidLayout(format!( + "{size}-byte layout is not a multiple of alignment {alignment}" + ))); + } + let mut names = HashSet::new(); + for field in &fields { + if !names.insert(field.name()) { + return Err(ModelError::InvalidLayout(format!( + "duplicate field `{}`", + field.name() + ))); + } + if field.offset() >= size { + return Err(ModelError::InvalidLayout(format!( + "field `{}` starts outside the {size}-byte layout", + field.name() + ))); + } + if kind == LayoutKind::Union && field.offset() != 0 { + return Err(ModelError::InvalidLayout(format!( + "union field `{}` must start at offset zero", + field.name() + ))); + } + } + Ok(Self { + size, + alignment, + packing, + kind, + fields, + }) + } + + pub(in crate::codegen::com) const fn size(&self) -> usize { + self.size + } + + pub(in crate::codegen::com) const fn alignment(&self) -> usize { + self.alignment + } + + pub(in crate::codegen::com) const fn packing(&self) -> usize { + self.packing + } + + pub(in crate::codegen::com) const fn kind(&self) -> LayoutKind { + self.kind + } + + pub(in crate::codegen::com) fn fields(&self) -> &[FieldLayout] { + &self.fields + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct NativeLayoutSet { + x86: NativeLayout, + x64: NativeLayout, + arm64: NativeLayout, +} + +impl NativeLayoutSet { + pub(super) const fn new(x86: NativeLayout, x64: NativeLayout, arm64: NativeLayout) -> Self { + Self { x86, x64, arm64 } + } + + pub(in crate::codegen::com) const fn get(&self, architecture: Architecture) -> &NativeLayout { + match architecture { + Architecture::X86 => &self.x86, + Architecture::X64 => &self.x64, + Architecture::Arm64 => &self.arm64, + } + } +} + +#[derive(Debug, Default)] +pub(super) struct LayoutTable { + layouts: Vec>, +} + +impl LayoutTable { + pub(super) fn reserve(&mut self) -> Result { + let id = LayoutId::from_index(self.layouts.len()) + .ok_or(ModelError::CapacityExceeded("native layout"))?; + self.layouts.push(None); + Ok(id) + } + + pub(super) fn insert(&mut self, layout: NativeLayoutSet) -> Result { + let id = self.reserve()?; + self.define(id, layout)?; + Ok(id) + } + + pub(super) fn define( + &mut self, + id: LayoutId, + layout: NativeLayoutSet, + ) -> Result<(), ModelError> { + let Some(slot) = self.layouts.get_mut(id.index()) else { + return Err(ModelError::UnknownId { + kind: "native layout", + index: id.index(), + }); + }; + if slot.is_some() { + return Err(ModelError::DuplicateDefinition { + kind: "native layout", + index: id.index(), + }); + } + *slot = Some(layout); + Ok(()) + } + + pub(super) fn get(&self, id: LayoutId) -> Result<&NativeLayoutSet, ModelError> { + match self.layouts.get(id.index()) { + Some(Some(layout)) => Ok(layout), + Some(None) => Err(ModelError::IncompleteDefinition { + kind: "native layout", + index: id.index(), + }), + None => Err(ModelError::UnknownId { + kind: "native layout", + index: id.index(), + }), + } + } + + pub(super) fn validate_complete(&self) -> Result<(), ModelError> { + for (index, layout) in self.layouts.iter().enumerate() { + if layout.is_none() { + return Err(ModelError::IncompleteDefinition { + kind: "native layout", + index, + }); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scalar_field(offset: usize) -> FieldLayout { + FieldLayout::new("value", TypeId::from_index(0).unwrap(), offset, None).unwrap() + } + + fn layout(size: usize, architecture: Architecture) -> NativeLayout { + NativeLayout::new( + size, + architecture.pointer_alignment().min(4), + 8, + LayoutKind::Struct(StructLayout::Sequential), + vec![scalar_field(0)], + ) + .unwrap() + } + + #[test] + fn architecture_has_explicit_pointer_width() { + assert_eq!(Architecture::X86.pointer_size(), 4); + assert_eq!(Architecture::X64.pointer_alignment(), 8); + assert_eq!(Architecture::Arm64.pointer_size(), 8); + } + + #[test] + fn union_fields_must_overlap_at_zero() { + let field = FieldLayout::new("value", TypeId::from_index(0).unwrap(), 4, None).unwrap(); + assert!(matches!( + NativeLayout::new(8, 8, 8, LayoutKind::Union, vec![field]), + Err(ModelError::InvalidLayout(_)) + )); + } + + #[test] + fn layout_table_preserves_all_architecture_variants() { + let mut table = LayoutTable::default(); + let id = table.reserve().unwrap(); + table + .define( + id, + NativeLayoutSet::new( + layout(4, Architecture::X86), + layout(8, Architecture::X64), + layout(8, Architecture::Arm64), + ), + ) + .unwrap(); + + assert_eq!(table.get(id).unwrap().get(Architecture::X86).size(), 4); + assert_eq!(table.get(id).unwrap().get(Architecture::X64).size(), 8); + assert_eq!(table.get(id).unwrap().get(Architecture::Arm64).size(), 8); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs new file mode 100644 index 00000000..4884c333 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -0,0 +1,3522 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::HashSet; +use std::num::{NonZeroU8, NonZeroU32}; + +use crate::com_metadata::{ + ComInterfaceMeta, RawComMethod, RawComParam, RawComType, RawConstness, RawCountUnit, + RawElementOwnership, RawExactMethodContractKind, RawLayoutKind, RawNamedKind, RawNativeLayout, + RawNativeLayoutSet, RawNativeType, RawPacking, RawParamDirection, RawSafeArrayOwnership, + RawSafeArrayVartype, RawStringEncoding, +}; + +use super::ComModel; +use super::abi::{ + BufferElement, BufferElementOwnership, CallingConvention, ComAbiType, ComEnumDefinition, + ComEnumMember, ComEnumValue as SemanticEnumValue, ComTypeDefinition, Constness, DataPointee, + HandleKind, QualifiedName, ScalarType, StringEncoding, +}; +use super::contract::{ + BufferSizing, ComParamContract, CountRelation, CountUnit, Direction, Nullability, +}; +use super::diagnostics::{ModelError, UnsupportedReason}; +use super::ids::{ComGuid, EnumId, ParamIndex, TypeId}; +use super::layout::{ + Architecture, FieldLayout, LayoutKind, NativeLayout, NativeLayoutSet, StructLayout, +}; +use super::method::{ + ComMethodContract, ComMethodSpecialContract, ComReturnKind, DynamicIidContract, +}; +use super::ownership::{Cleanup, ComOwnership, HandleCleanup}; + +#[derive(Debug)] +pub(in crate::codegen::com) struct SemanticComInterface { + model: ComModel, + iid: ComGuid, + is_iunknown_rooted: bool, + methods: Vec, + referenced_enums: Vec, +} + +impl SemanticComInterface { + fn validate(&self) -> Result<(), ModelError> { + let first_method_slot = if self.is_iunknown_rooted { 3 } else { 6 }; + let mut slots = std::collections::HashSet::new(); + for method in &self.methods { + if method.vtable_slot() < first_method_slot { + return Err(ModelError::InvalidContract(format!( + "{} uses reserved vtable slot {} (first user slot is {first_method_slot})", + method.name(), + method.vtable_slot() + ))); + } + if !slots.insert(method.vtable_slot()) { + return Err(ModelError::InvalidContract(format!( + "duplicate vtable slot {} on method {}", + method.vtable_slot(), + method.name() + ))); + } + method + .validate(&self.model) + .map_err(|error| error.context(method.name()))?; + } + self.model.validate_complete()?; + Ok(()) + } + + pub(in crate::codegen::com) const fn iid(&self) -> ComGuid { + self.iid + } + + pub(in crate::codegen::com) const fn is_iunknown_rooted(&self) -> bool { + self.is_iunknown_rooted + } + + pub(in crate::codegen::com) fn methods(&self) -> &[ComMethodContract] { + &self.methods + } + + pub(in crate::codegen::com) fn type_definition( + &self, + id: TypeId, + ) -> Result<&ComTypeDefinition, ModelError> { + self.model.types().get(id) + } + + pub(in crate::codegen::com) fn enum_definition( + &self, + id: super::ids::EnumId, + ) -> Result<&ComEnumDefinition, ModelError> { + self.model.enums.get(id) + } + + pub(in crate::codegen::com) fn layout_definition( + &self, + id: super::ids::LayoutId, + ) -> Result<&super::layout::NativeLayoutSet, ModelError> { + self.model.layouts.get(id) + } + + pub(in crate::codegen::com) fn find_enum( + &self, + namespace: &str, + name: &str, + ) -> Option<&ComEnumDefinition> { + self.model.enums.iter().find(|definition| { + definition.native_name().namespace() == namespace + && definition.native_name().name() == name + }) + } + + pub(in crate::codegen::com) fn referenced_enums( + &self, + ) -> impl Iterator { + self.referenced_enums + .iter() + .map(|id| self.model.enums.get(*id).expect("validated enum id")) + } +} + +pub(super) fn map_interface(meta: &ComInterfaceMeta) -> Result { + let raw_methods = meta.raw_methods.as_ref().ok_or_else(|| { + ModelError::InvalidContract(format!( + "{}.{} has no raw COM metadata facts", + meta.interface.namespace, meta.interface.name + )) + })?; + if meta.interface.methods.len() != raw_methods.len() { + return Err(ModelError::InvalidContract(format!( + "{}.{} has {} compatibility methods but {} raw methods", + meta.interface.namespace, + meta.interface.name, + meta.interface.methods.len(), + raw_methods.len() + ))); + } + if raw_methods.iter().any(|method| { + method.params.iter().any(|param| { + raw_contains_named_type(¶m.typ, "Windows.Win32.System.Com", "BIND_OPTS") + }) || raw_contains_named_type(&method.return_type, "Windows.Win32.System.Com", "BIND_OPTS") + }) { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "IBindCtx BIND_OPTS requires cbStruct to be initialized to the architecture-specific structure size" + .into(), + ))); + } + let iid = ComGuid::parse(&meta.interface.iid)?; + let mut model = ComModel::default(); + let methods = meta + .interface + .methods + .iter() + .zip(raw_methods) + .map(|(method, raw)| { + map_method( + &mut model, + iid, + &meta.interface.iid, + &meta.interface.namespace, + &meta.interface.name, + method, + raw, + ) + }) + .collect::, _>>()?; + let referenced_enums = attach_enum_metadata( + &mut model, + meta.raw_referenced_enums.as_ref().ok_or_else(|| { + ModelError::InvalidContract(format!( + "{}.{} has no raw enum metadata facts", + meta.interface.namespace, meta.interface.name + )) + })?, + )?; + let interface = SemanticComInterface { + model, + iid, + is_iunknown_rooted: meta.is_iunknown_rooted, + methods, + referenced_enums, + }; + if !interface.is_iunknown_rooted + && interface + .methods + .iter() + .any(|method| method.return_kind() == ComReturnKind::EnumeratorNextHResult) + { + return Err(ModelError::InvalidContract( + "EnumeratorNext is restricted to IUnknown-rooted interfaces".into(), + )); + } + interface.validate()?; + Ok(interface) +} + +fn raw_contains_named_type(raw: &RawComType, namespace: &str, name: &str) -> bool { + if matches!( + &raw.native_type, + RawNativeType::Named { + namespace: candidate_namespace, + name: candidate_name, + .. + } if candidate_namespace == namespace && candidate_name == name + ) { + return true; + } + raw.underlying + .as_deref() + .is_some_and(|underlying| raw_contains_named_type(underlying, namespace, name)) + || matches!( + &raw.native_type, + RawNativeType::Array(element) + if raw_contains_named_type(element, namespace, name) + ) +} + +fn attach_enum_metadata( + model: &mut ComModel, + raw_enums: &[crate::com_metadata::ComEnumMeta], +) -> Result, ModelError> { + let mut referenced = Vec::with_capacity(raw_enums.len()); + for raw_enum in raw_enums { + let underlying = metadata_enum_scalar(&raw_enum.underlying).ok_or( + ModelError::Unsupported(UnsupportedReason::UnknownNativeType), + )?; + let mut ids = model + .enums + .ids() + .filter(|id| { + model.enums.get(*id).is_ok_and(|definition| { + definition.native_name().namespace() == raw_enum.namespace + && definition.native_name().name() == raw_enum.name + }) + }) + .collect::>(); + if ids.is_empty() { + ids.push(model.enums.insert(ComEnumDefinition::new( + QualifiedName::new(&raw_enum.namespace, &raw_enum.name)?, + underlying, + )?)?); + } + let first = ids[0]; + let members = raw_enum + .members + .iter() + .map(|member| { + ComEnumMember::new( + member.name.clone(), + match member.value { + crate::com_metadata::ComEnumValue::Signed(value) => { + SemanticEnumValue::Signed(value) + } + crate::com_metadata::ComEnumValue::Unsigned(value) => { + SemanticEnumValue::Unsigned(value) + } + }, + ) + }) + .collect::>(); + for id in ids { + let definition = model.enums.get_mut(id)?; + if definition.underlying() != underlying { + return Err(ModelError::InvalidContract(format!( + "enum {}.{} underlying type disagrees with raw semantic type", + raw_enum.namespace, raw_enum.name + ))); + } + definition.set_members(members.clone(), raw_enum.is_flags); + } + if !referenced.contains(&first) { + referenced.push(first); + } + } + Ok(referenced) +} + +fn metadata_enum_scalar(typ: &crate::types::TypeMeta) -> Option { + match typ { + crate::types::TypeMeta::I8 => Some(ScalarType::I8), + crate::types::TypeMeta::U8 => Some(ScalarType::U8), + crate::types::TypeMeta::I16 => Some(ScalarType::I16), + crate::types::TypeMeta::U16 => Some(ScalarType::U16), + crate::types::TypeMeta::I32 => Some(ScalarType::I32), + crate::types::TypeMeta::U32 => Some(ScalarType::U32), + crate::types::TypeMeta::I64 => Some(ScalarType::I64), + crate::types::TypeMeta::U64 => Some(ScalarType::U64), + _ => None, + } +} + +fn map_method( + model: &mut ComModel, + interface_iid: ComGuid, + interface_iid_text: &str, + interface_namespace: &str, + interface_name: &str, + method: &crate::com_metadata::MethodMeta, + raw: &RawComMethod, +) -> Result { + crate::com_metadata::validate_borrowed_hwnd_output_evidence(raw) + .map_err(ModelError::InvalidContract)?; + crate::com_metadata::validate_attached_enumerator_evidence(raw) + .map_err(ModelError::InvalidContract)?; + crate::com_metadata::validate_attached_safe_array_evidence(raw) + .map_err(ModelError::InvalidContract)?; + if let Some(contract) = &raw.exact_contract { + crate::com_metadata::validate_exact_method_contract( + interface_namespace, + interface_name, + interface_iid_text, + raw, + contract, + ) + .map_err(ModelError::InvalidContract)?; + if contract.kind == RawExactMethodContractKind::UnsafePrivateData { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "{}; see {}", + contract.reason, contract.citation + )))); + } + } + if method.name != raw.projected_name || method.params.len() != raw.params.len() { + return Err(ModelError::InvalidContract(format!( + "{} compatibility and raw metadata are not aligned", + method.name + ))); + } + if raw.enumerator_next.is_some() && raw.semantic_hresult.is_none() { + return Err(ModelError::InvalidContract(format!( + "{} EnumeratorNext requires exact multiple-success HRESULT evidence", + method.name + ))); + } + let dynamic_iid = dynamic_iid_contract(raw)?; + let params = method + .params + .iter() + .zip(&raw.params) + .enumerate() + .map(|(index, (compatibility, raw_param))| { + if compatibility.name != raw_param.name { + return Err(ModelError::InvalidContract(format!( + "parameter `{}` is not aligned with raw parameter `{}`", + compatibility.name, raw_param.name + ))); + } + map_param( + model, + interface_namespace, + interface_name, + index, + raw_param, + raw, + dynamic_iid.is_some_and(|contract| contract.output_param_index().index() == index), + ) + .map_err(|error| { + error.context(format!( + "{}.{} ({:?})", + raw.projected_name, raw_param.name, raw_param.typ + )) + }) + }) + .collect::, ModelError>>()?; + let return_kind = map_return(model, raw) + .map_err(|error| error.context(format!("{} return", raw.projected_name)))?; + if raw.semantic_hresult.is_some() + && !matches!( + return_kind, + ComReturnKind::SemanticHResult | ComReturnKind::EnumeratorNextHResult + ) + { + return Err(ModelError::InvalidContract(format!( + "{} semantic-HRESULT evidence applies to a non-HRESULT return", + method.name + ))); + } + let mut method = ComMethodContract::new( + raw.projected_name.clone(), + interface_iid, + raw.vtable_index, + CallingConvention::System, + params, + return_kind, + )?; + if let Some(contract) = dynamic_iid { + method = method.with_dynamic_iid_contract(contract)?; + } + Ok( + match raw.exact_contract.as_ref().map(|contract| contract.kind) { + Some(RawExactMethodContractKind::FixedCapacityBytes) => { + method.with_special_contract(ComMethodSpecialContract::FixedCapacityBytes { + guid_param: ParamIndex::new(0), + }) + } + Some(RawExactMethodContractKind::UnsafePrivateData) => { + unreachable!("unsafe private-data contracts fail before method mapping") + } + None => method, + }, + ) +} + +fn map_param( + model: &mut ComModel, + interface_namespace: &str, + interface_name: &str, + param_index: usize, + raw: &RawComParam, + raw_method: &RawComMethod, + dynamic_iid_output: bool, +) -> Result { + let effective_direction = documented_bstr_direction_override( + interface_namespace, + interface_name, + &raw_method.metadata_name, + &raw.name, + ) + .or_else(|| { + raw_method.enumerator_next.as_ref().and_then(|enumerator| { + (enumerator.values_param_index == param_index + || enumerator.fetched_param_index == param_index) + .then_some(RawParamDirection::Out) + }) + }) + .or_else(|| { + raw.native_array + .as_ref() + .is_some_and(|array| array.two_call && raw.direction == RawParamDirection::InOut) + .then_some(RawParamDirection::Out) + }) + .unwrap_or(raw.direction); + let (abi_type, count) = if let Some(array) = &raw.native_array { + if effective_direction == RawParamDirection::InOut { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "in/out counted-buffer contents require a dedicated preserve-input storage plan" + .into(), + ))); + } + let count_param = array.count_param_index.ok_or(ModelError::Unsupported( + UnsupportedReason::MissingCountRelationship, + ))?; + let callee_allocated = raw_method + .params + .get(count_param) + .is_some_and(|count| count.direction == RawParamDirection::Out) + && effective_direction == RawParamDirection::Out; + let (element, element_ownership) = map_buffer_element( + model, + raw, + callee_allocated, + array.unit == RawCountUnit::Bytes, + )?; + let buffer = model.types_mut().insert(ComTypeDefinition::new( + raw_native_name(&raw.typ)?, + None, + ComAbiType::CountedBuffer { + element, + element_ownership, + pointer_depth: nonzero_pointer_depth(raw.typ.pointer_depth.max(1))?, + constness: array + .constness + .map(|constness| map_constness(constness, false)) + .unwrap_or_else(|| buffer_constness(raw)), + }, + ))?; + let count_param = ParamIndex::new(count_param); + let count_direction = raw_method + .params + .get(count_param.index()) + .ok_or_else(|| { + ModelError::InvalidContract(format!( + "NativeArrayInfo count index {} is outside the method", + count_param.index() + )) + })? + .direction; + let actual_length_param = array.actual_length_param_index.map(ParamIndex::new); + let unit = match array.unit { + RawCountUnit::Elements => CountUnit::Elements, + RawCountUnit::Bytes => CountUnit::Bytes, + }; + let mut relation = map_count_relation( + effective_direction, + count_direction, + count_param, + actual_length_param, + unit, + array.two_call, + array.projected_capacity, + ); + if let Some(enumerator) = &raw_method.enumerator_next + && param_index == enumerator.values_param_index + { + if count_param.index() != enumerator.capacity_param_index + || effective_direction != RawParamDirection::Out + || actual_length_param.is_some() + || unit != CountUnit::Elements + || array.two_call + { + return Err(ModelError::InvalidContract( + "EnumeratorNext metadata count relation does not match the exact override" + .into(), + )); + } + relation = CountRelation::EnumeratorNext { + capacity_param: ParamIndex::new(enumerator.capacity_param_index), + fetched_param: ParamIndex::new(enumerator.fetched_param_index), + fetched_optional_for_single: enumerator.fetched_optional_for_single, + }; + } + (buffer, Some(relation)) + } else { + (map_parameter_type(model, raw)?, None) + }; + let direction = map_direction(effective_direction); + if direction == Direction::In && terminal_pointer_pointee_is_bstr(model, abi_type)? { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "input BSTR pointer chains have no proven pointee allocation or borrow contract".into(), + ))); + } + if raw.optional + && direction == Direction::In + && matches!(model.types().get(abi_type)?.abi(), ComAbiType::Variant) + { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "optional by-value VARIANT input has no proven native null/default semantics".into(), + ))); + } + + fn terminal_pointer_pointee_is_bstr( + model: &ComModel, + abi_type: TypeId, + ) -> Result { + let ComAbiType::Pointer { pointee, .. } = model.types().get(abi_type)?.abi() else { + return Ok(false); + }; + Ok(match model.types().get(*pointee)?.abi() { + ComAbiType::Bstr => true, + ComAbiType::Pointer { .. } => terminal_pointer_pointee_is_bstr(model, *pointee)?, + _ => false, + }) + } + let (ownership, cleanup) = map_ownership( + model, + abi_type, + direction, + raw, + raw_method, + param_index, + dynamic_iid_output, + )?; + let nullable = if (raw.optional + || known_nullable_param_override( + interface_namespace, + interface_name, + &raw_method.metadata_name, + &raw.name, + ) + || raw + .safe_array_evidence + .as_ref() + .is_some_and(crate::com_safe_array_registry::safe_array_output_allows_null)) + && is_nullable_type(model, abi_type)? + { + Nullability::Nullable + } else { + Nullability::Required + }; + ComParamContract::new( + raw.name.clone(), + abi_type, + direction, + raw.optional, + nullable, + count, + ownership, + cleanup, + ) +} + +fn documented_bstr_direction_override( + namespace: &str, + interface: &str, + method: &str, + parameter: &str, +) -> Option { + // The Win32 API declarations are authoritative where win32metadata's + // OptionalAttribute-derived direction disagrees: + // https://learn.microsoft.com/windows/win32/api/photoacquire/nf-photoacquire-iphotoacquiredeviceselectiondialog-domodal + // https://learn.microsoft.com/windows/win32/api/imapi/nf-imapi-idiscrecorder-getdisplaynames + let documented_out = (namespace == "Windows.Win32.Media.PictureAcquisition" + && interface == "IPhotoAcquireDeviceSelectionDialog" + && method == "DoModal" + && parameter == "pbstrDeviceId") + || (namespace == "Windows.Win32.Storage.Imapi" + && interface == "IDiscRecorder" + && method == "GetDisplayNames" + && matches!( + parameter, + "pbstrVendorID" | "pbstrProductID" | "pbstrRevision" + )); + documented_out.then_some(RawParamDirection::Out) +} + +fn known_nullable_param_override( + namespace: &str, + interface: &str, + method: &str, + parameter: &str, +) -> bool { + namespace == "Windows.Win32.UI.Shell" + && ((matches!(interface, "ITaskbarList3" | "ITaskbarList4") + && method == "SetThumbnailClip" + && parameter == "prcClip") + || (interface == "IShellLinkW" && method == "GetPath" && parameter == "pfd")) +} + +fn map_parameter_type(model: &mut ComModel, raw: &RawComParam) -> Result { + if is_raw_named_type(&raw.typ, "Windows.Win32.System.Com", "SAFEARRAY") { + let element = known_safe_array_element(model, raw)?; + let base = insert_abi( + model, + Some(QualifiedName::new("Windows.Win32.System.Com", "SAFEARRAY")?), + None, + ComAbiType::SafeArray { + element: Some(element), + }, + )?; + if raw.typ.pointer_depth == 0 { + return Ok(base); + } + return insert_abi( + model, + None, + None, + ComAbiType::Pointer { + pointee: base, + depth: nonzero_pointer_depth(raw.typ.pointer_depth)?, + constness: map_constness(raw.typ.constness, raw.const_attribute), + }, + ); + } + map_type(model, &raw.typ, raw.const_attribute) +} + +fn known_safe_array_element(model: &mut ComModel, raw: &RawComParam) -> Result { + let evidence = raw + .safe_array_evidence + .as_ref() + .ok_or(ModelError::Unsupported( + UnsupportedReason::UnsupportedSafeArrayElement, + ))?; + match (evidence.ownership, raw.direction, raw.typ.pointer_depth) { + (RawSafeArrayOwnership::BorrowedInput, RawParamDirection::In, 1) + | (RawSafeArrayOwnership::OwnedOutput, RawParamDirection::Out, 2) => {} + _ => { + return Err(ModelError::InvalidContract( + "SAFEARRAY ownership evidence does not match parameter shape".into(), + )); + } + } + match evidence.element_vartype { + RawSafeArrayVartype::I4 => { + insert_abi(model, None, None, ComAbiType::Scalar(ScalarType::I32)) + } + RawSafeArrayVartype::Ui1 => { + insert_abi(model, None, None, ComAbiType::Scalar(ScalarType::U8)) + } + RawSafeArrayVartype::Ui4 => { + insert_abi(model, None, None, ComAbiType::Scalar(ScalarType::U32)) + } + RawSafeArrayVartype::R8 => { + insert_abi(model, None, None, ComAbiType::Scalar(ScalarType::F64)) + } + RawSafeArrayVartype::Bstr => insert_abi( + model, + Some(QualifiedName::new("Windows.Win32.Foundation", "BSTR")?), + None, + ComAbiType::Bstr, + ), + RawSafeArrayVartype::Variant => insert_abi( + model, + Some(QualifiedName::new( + "Windows.Win32.System.Variant", + "VARIANT", + )?), + None, + ComAbiType::Variant, + ), + RawSafeArrayVartype::Unknown => { + let iid = evidence.element_iid.ok_or_else(|| { + ModelError::InvalidContract( + "VT_UNKNOWN SAFEARRAY evidence requires an exact interface IID".into(), + ) + })?; + insert_abi( + model, + None, + None, + ComAbiType::ComInterface { + iid: ComGuid::parse(iid)?, + }, + ) + } + } +} + +fn is_raw_named_type(raw: &RawComType, namespace: &str, name: &str) -> bool { + matches!( + &raw.native_type, + RawNativeType::Named { + namespace: candidate_namespace, + name: candidate_name, + .. + } if candidate_namespace == namespace && candidate_name == name + ) +} + +fn map_return(model: &mut ComModel, raw: &RawComMethod) -> Result { + if matches!(raw.return_type.native_type, RawNativeType::Void) + && raw.return_type.pointer_depth == 0 + { + return Ok(ComReturnKind::Void); + } + let abi_type = map_type(model, &raw.return_type, false)?; + if is_hresult(model, abi_type)? { + return Ok(if raw.enumerator_next.is_some() { + ComReturnKind::EnumeratorNextHResult + } else if raw.semantic_hresult.is_some() { + ComReturnKind::SemanticHResult + } else { + ComReturnKind::HResult + }); + } + if matches!(model.types().get(abi_type)?.abi(), ComAbiType::Handle(_)) { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "direct handle returns require explicit resource ownership and cleanup".into(), + ))); + } + if model + .types() + .get(abi_type)? + .abi() + .requires_pointer_return_convention() + { + Ok(ComReturnKind::DirectPointer(abi_type)) + } else { + Ok(ComReturnKind::DirectValue(abi_type)) + } +} + +fn map_type( + model: &mut ComModel, + raw: &RawComType, + const_attribute: bool, +) -> Result { + if raw.pointer_depth > 0 + && matches!(raw.native_type, RawNativeType::Object | RawNativeType::Void) + { + let depth = nonzero_pointer_depth(raw.pointer_depth)?; + return model.types_mut().insert(ComTypeDefinition::new( + None, + None, + ComAbiType::DataPointer { + pointee: DataPointee::Opaque(None), + depth, + constness: map_constness(raw.constness, const_attribute), + }, + )); + } + if raw.pointer_depth > 0 && is_opaque_named_pointee(raw) { + let depth = nonzero_pointer_depth(raw.pointer_depth)?; + return model.types_mut().insert(ComTypeDefinition::new( + raw_native_name(raw)?, + None, + ComAbiType::DataPointer { + pointee: DataPointee::Opaque(raw_native_name(raw)?), + depth, + constness: map_constness(raw.constness, const_attribute), + }, + )); + } + let base = map_raw_base_type(model, raw)?; + if raw.pointer_depth == 0 { + return Ok(base); + } + let depth = nonzero_pointer_depth(raw.pointer_depth)?; + model.types_mut().insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: base, + depth, + constness: map_constness(raw.constness, const_attribute), + }, + )) +} + +fn is_opaque_named_pointee(raw: &RawComType) -> bool { + let RawNativeType::Named { + namespace, + name, + kind: RawNamedKind::Struct, + .. + } = &raw.native_type + else { + return false; + }; + if (namespace == "System" && matches!(name.as_str(), "Guid" | "IntPtr" | "UIntPtr")) + || (namespace == "Windows.Win32.Foundation" + && matches!(name.as_str(), "BOOL" | "HRESULT" | "BSTR")) + || (namespace == "Windows.Win32.System.Variant" + && matches!(name.as_str(), "VARIANT" | "VARIANTARG")) + || (namespace == "Windows.Win32.System.Com" && name == "SAFEARRAY") + || (namespace == "Windows.Win32.System.Com.StructuredStorage" && name == "PROPVARIANT") + || (namespace == "Windows.Win32.System.WinRT" && name == "HSTRING") + { + return false; + } + // ITEMIDLIST ends in SHITEMID's variable-length abID payload, so only its + // documented pointer/allocator contract is usable; it has no fixed layout. + if namespace == "Windows.Win32.UI.Shell.Common" && name == "ITEMIDLIST" { + return true; + } + if matches!( + raw.native_type, + RawNativeType::Named { + layout: Some(_), + .. + } + ) { + return false; + } + match raw.underlying.as_deref() { + Some(underlying) + if raw_scalar_alias(underlying, namespace, name).is_some() + || underlying.pointer_depth > 0 => + { + false + } + _ => true, + } +} + +fn map_raw_base_type(model: &mut ComModel, raw: &RawComType) -> Result { + let scalar = match raw.native_type { + RawNativeType::Bool => Some(ScalarType::Bool), + RawNativeType::I8 => Some(ScalarType::I8), + RawNativeType::U8 => Some(ScalarType::U8), + RawNativeType::I16 => Some(ScalarType::I16), + RawNativeType::U16 => Some(ScalarType::U16), + RawNativeType::I32 => Some(ScalarType::I32), + RawNativeType::U32 => Some(ScalarType::U32), + RawNativeType::I64 => Some(ScalarType::I64), + RawNativeType::U64 => Some(ScalarType::U64), + RawNativeType::F32 => Some(ScalarType::F32), + RawNativeType::F64 => Some(ScalarType::F64), + RawNativeType::Char16 => Some(ScalarType::Char16), + RawNativeType::ISize => Some(ScalarType::NativeIsize), + RawNativeType::USize => Some(ScalarType::NativeUsize), + _ => None, + }; + if let Some(scalar) = scalar { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::Scalar(scalar), + ); + } + match &raw.native_type { + RawNativeType::Named { + namespace, name, .. + } if namespace == "System" && name == "Guid" => { + insert_abi(model, raw_native_name(raw)?, None, ComAbiType::Guid) + } + RawNativeType::Named { + namespace, name, .. + } if namespace == "Windows.Win32.System.WinRT" && name == "HSTRING" => { + insert_abi(model, raw_native_name(raw)?, None, ComAbiType::HString) + } + RawNativeType::Named { + namespace, + name, + kind: RawNamedKind::Interface | RawNamedKind::RuntimeClass, + iid, + .. + } => insert_abi( + model, + Some(QualifiedName::new(namespace, name)?), + None, + ComAbiType::ComInterface { + iid: ComGuid::parse(iid.as_deref().ok_or(ModelError::Unsupported( + UnsupportedReason::MissingInterfaceIid, + ))?)?, + }, + ), + RawNativeType::Named { + namespace, + name, + kind: RawNamedKind::Enum, + .. + } => { + let underlying = raw.underlying.as_deref().ok_or(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + ))?; + let scalar = raw_scalar(underlying).ok_or(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + ))?; + let enum_id = model.enums_mut().insert(ComEnumDefinition::new( + QualifiedName::new(namespace, name)?, + scalar, + )?)?; + insert_abi( + model, + Some(QualifiedName::new(namespace, name)?), + None, + ComAbiType::Enum(enum_id), + ) + } + RawNativeType::Named { + kind: RawNamedKind::Delegate, + .. + } => Err(ModelError::Unsupported( + UnsupportedReason::UnsupportedFunctionPointer, + )), + RawNativeType::Named { + kind: RawNamedKind::Unknown, + .. + } => Err(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + )), + RawNativeType::Named { + namespace, name, .. + } => map_raw_named_struct(model, namespace, name, raw), + RawNativeType::String => insert_abi(model, None, None, ComAbiType::HString), + RawNativeType::Object => Err(ModelError::Unsupported( + UnsupportedReason::UnknownPointerMeaning, + )), + RawNativeType::Array(_) | RawNativeType::FixedArray { .. } => { + Err(ModelError::Unsupported(UnsupportedReason::UnsupportedArray)) + } + RawNativeType::Unknown(_) | RawNativeType::Void => Err(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + )), + _ => unreachable!("scalar raw types returned above"), + } +} + +fn map_raw_named_struct( + model: &mut ComModel, + namespace: &str, + name: &str, + raw: &RawComType, +) -> Result { + if namespace == "System" && name == "IntPtr" { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::Scalar(ScalarType::NativeIsize), + ); + } + if namespace == "System" && name == "UIntPtr" { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::Scalar(ScalarType::NativeUsize), + ); + } + if namespace == "Windows.Win32.Foundation" { + match name { + "BOOL" => { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::Scalar(ScalarType::Win32Bool), + ); + } + "HRESULT" => { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::Scalar(ScalarType::HResult), + ); + } + "BSTR" => return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::Bstr), + _ => {} + } + } + if namespace == "Windows.Win32.System.WinRT" && name == "HSTRING" { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::HString); + } + if namespace == "Windows.Win32.System.Variant" && matches!(name, "VARIANT" | "VARIANTARG") { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::Variant); + } + if namespace == "Windows.Win32.System.Com" && name == "SAFEARRAY" { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::SafeArray { element: None }, + ); + } + if namespace == "Windows.Win32.System.Com" && name == "DISPPARAMS" { + return insert_abi( + model, + raw_native_name(raw)?, + None, + ComAbiType::DispatchParams, + ); + } + if namespace == "Windows.Win32.System.Com" && name == "EXCEPINFO" { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::ExcepInfo); + } + if namespace == "Windows.Win32.System.Com.StructuredStorage" && name == "PROPVARIANT" { + return insert_abi(model, raw_native_name(raw)?, None, ComAbiType::PropVariant); + } + if is_explicit_pointer_alias(namespace, name) { + return map_pointer_alias(model, namespace, name); + } + if let Some(underlying) = raw.underlying.as_deref() { + if let Some(scalar) = raw_scalar_alias(underlying, namespace, name) { + let underlying_id = insert_abi(model, None, None, ComAbiType::Scalar(scalar))?; + return insert_abi( + model, + Some(QualifiedName::new(namespace, name)?), + Some(underlying_id), + ComAbiType::Scalar(scalar), + ); + } + if underlying.pointer_depth > 0 { + return map_pointer_alias(model, namespace, name); + } + } + if let RawNativeType::Named { + layout: Some(layout), + .. + } = &raw.native_type + { + return map_native_struct(model, namespace, name, layout); + } + Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)) +} + +fn map_native_struct( + model: &mut ComModel, + namespace: &str, + name: &str, + raw: &RawNativeLayoutSet, +) -> Result { + if raw.recursive { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "recursive by-value native layout {namespace}.{name}" + )))); + } + let layout_id = model.layouts_mut().reserve()?; + let is_union = raw.variants.first().is_some_and(|variant| variant.is_union); + if raw + .variants + .iter() + .any(|variant| variant.is_union != is_union) + { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "architecture variants disagree whether {namespace}.{name} is a union" + )))); + } + let type_id = insert_abi( + model, + Some(QualifiedName::new(namespace, name)?), + None, + if is_union { + ComAbiType::NativeUnion(layout_id) + } else { + ComAbiType::NativeStruct(layout_id) + }, + )?; + let x86 = compute_native_layout(model, raw, Architecture::X86) + .map_err(|error| error.context(format!("{namespace}.{name} (x86)")))?; + let x64 = compute_native_layout(model, raw, Architecture::X64) + .map_err(|error| error.context(format!("{namespace}.{name} (x64)")))?; + let arm64 = compute_native_layout(model, raw, Architecture::Arm64) + .map_err(|error| error.context(format!("{namespace}.{name} (ARM64)")))?; + model + .layouts_mut() + .define(layout_id, NativeLayoutSet::new(x86, x64, arm64))?; + Ok(type_id) +} + +fn compute_native_layout( + model: &mut ComModel, + raw: &RawNativeLayoutSet, + architecture: Architecture, +) -> Result { + let candidates = raw + .variants + .iter() + .filter(|variant| variant.architectures & architecture.metadata_mask() != 0) + .collect::>(); + let [raw] = candidates.as_slice() else { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + if candidates.is_empty() { + format!("missing {:?} native layout facts", architecture) + } else { + format!("ambiguous {:?} native layout facts", architecture) + }, + ))); + }; + compute_native_layout_variant(model, raw, architecture) +} + +fn compute_native_layout_variant( + model: &mut ComModel, + raw: &RawNativeLayout, + architecture: Architecture, +) -> Result { + let kind = if raw.is_union { + LayoutKind::Union + } else { + match raw.kind { + RawLayoutKind::Sequential => LayoutKind::Struct(StructLayout::Sequential), + RawLayoutKind::Explicit => LayoutKind::Struct(StructLayout::Explicit), + RawLayoutKind::Unknown => { + return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); + } + } + }; + let packing = match raw.packing { + RawPacking::Default => 8usize, + RawPacking::Explicit(value) if value.is_power_of_two() => usize::from(value), + RawPacking::Explicit(_) | RawPacking::Unknown => { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "unknown or invalid native packing".into(), + ))); + } + }; + if raw.fields.is_empty() { + return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); + } + + let mut fields = Vec::with_capacity(raw.fields.len()); + let mut intervals = Vec::with_capacity(raw.fields.len()); + let mut cursor = 0usize; + let mut structure_alignment = 1usize; + for raw_field in &raw.fields { + if raw_field.bitfield { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "bitfield `{}` is not supported", + raw_field.name + )))); + } + if raw_field.flexible_array { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "flexible array `{}` is not supported", + raw_field.name + )))); + } + let field_type = map_type(model, &raw_field.typ, false)?; + validate_pod_field_type( + model, + field_type, + raw_field.fixed_count.is_some(), + raw.is_union, + )?; + let (element_size, element_alignment) = + abi_size_alignment(model, field_type, architecture, &mut HashSet::new())?; + let count = match raw_field.fixed_count { + Some(count) => Some( + NonZeroU32::new(u32::try_from(count).map_err(|_| { + ModelError::InvalidLayout(format!( + "fixed array `{}` length exceeds u32", + raw_field.name + )) + })?) + .ok_or_else(|| { + ModelError::InvalidLayout(format!( + "fixed array `{}` has zero length", + raw_field.name + )) + })?, + ), + None => None, + }; + let field_size = element_size + .checked_mul(count.map_or(1, |count| count.get() as usize)) + .ok_or_else(|| { + ModelError::InvalidLayout(format!("field `{}` size overflows", raw_field.name)) + })?; + let effective_alignment = element_alignment.min(packing); + structure_alignment = structure_alignment.max(effective_alignment); + let offset = match kind { + LayoutKind::Struct(StructLayout::Sequential) => { + if raw_field.explicit_offset.is_some() { + return Err(ModelError::InvalidLayout(format!( + "sequential field `{}` unexpectedly has an explicit offset", + raw_field.name + ))); + } + align_up(cursor, effective_alignment)? + } + LayoutKind::Struct(StructLayout::Explicit) => { + let offset = raw_field.explicit_offset.ok_or_else(|| { + ModelError::Unsupported(UnsupportedReason::Other(format!( + "explicit field `{}` has no authoritative offset", + raw_field.name + ))) + })?; + if offset % effective_alignment != 0 { + return Err(ModelError::InvalidLayout(format!( + "explicit field `{}` offset {offset} violates alignment {effective_alignment}", + raw_field.name + ))); + } + offset + } + LayoutKind::Union => { + if raw_field.explicit_offset.is_some_and(|offset| offset != 0) { + return Err(ModelError::InvalidLayout(format!( + "union field `{}` must start at offset zero", + raw_field.name + ))); + } + 0 + } + }; + let end = offset.checked_add(field_size).ok_or_else(|| { + ModelError::InvalidLayout(format!("field `{}` end overflows", raw_field.name)) + })?; + if kind != LayoutKind::Union + && intervals.iter().any(|(existing_start, existing_end)| { + offset < *existing_end && *existing_start < end + }) + { + return Err(ModelError::Unsupported(UnsupportedReason::Other(format!( + "overlapping explicit field `{}` requires union support", + raw_field.name + )))); + } + intervals.push((offset, end)); + cursor = cursor.max(end); + fields.push(FieldLayout::new( + &raw_field.name, + field_type, + offset, + count, + )?); + } + let natural_size = align_up(cursor, structure_alignment)?; + let size = match raw.declared_size { + Some(size) if size < cursor || size % structure_alignment != 0 => { + return Err(ModelError::InvalidLayout(format!( + "declared size {size} cannot contain {cursor} bytes at alignment {structure_alignment}" + ))); + } + Some(size) => size, + None => natural_size, + }; + NativeLayout::new(size, structure_alignment, packing, kind, fields) +} + +fn validate_pod_field_type( + model: &ComModel, + field_type: TypeId, + fixed_array: bool, + enclosing_union: bool, +) -> Result<(), ModelError> { + let abi = model.types().get(field_type)?.abi(); + if fixed_array && !matches!(abi, ComAbiType::Scalar(_) | ComAbiType::Enum(_)) { + return Err(ModelError::Unsupported(UnsupportedReason::Other( + "fixed POD arrays currently require primitive or enum elements".into(), + ))); + } + match abi { + ComAbiType::Scalar(_) + | ComAbiType::Guid + | ComAbiType::Enum(_) + | ComAbiType::DataPointer { .. } + | ComAbiType::Handle(_) + | ComAbiType::StringPointer { .. } + | ComAbiType::NativeStruct(_) => Ok(()), + ComAbiType::NativeUnion(_) if enclosing_union => { + Err(ModelError::Unsupported(UnsupportedReason::Other( + "nested native unions require an explicit nested active-field contract".into(), + ))) + } + ComAbiType::Pointer { pointee, .. } => match model.types().get(*pointee)?.abi() { + ComAbiType::ComInterface { .. } + | ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::Handle(_) => Err(ModelError::Unsupported(UnsupportedReason::Other( + "nested interface, string, or resource pointer ownership is not supported".into(), + ))), + _ => Ok(()), + }, + ComAbiType::Bstr | ComAbiType::HString | ComAbiType::ComInterface { .. } => { + Err(ModelError::Unsupported(UnsupportedReason::Other( + "nested string/interface ownership is not supported".into(), + ))) + } + ComAbiType::NativeUnion(_) => Err(ModelError::Unsupported(UnsupportedReason::Other( + "native unions may not be nested in structs without a discriminant contract".into(), + ))), + ComAbiType::CountedBuffer { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + | ComAbiType::FunctionPointer(_) + | ComAbiType::Unknown(_) => Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)), + } +} + +fn abi_size_alignment( + model: &ComModel, + type_id: TypeId, + architecture: Architecture, + visiting: &mut HashSet, +) -> Result<(usize, usize), ModelError> { + if !visiting.insert(type_id) { + return Err(ModelError::InvalidLayout( + "recursive by-value native layout".into(), + )); + } + let result = match model.types().get(type_id)?.abi() { + ComAbiType::Scalar(scalar) => match scalar { + ScalarType::Bool | ScalarType::I8 | ScalarType::U8 => (1, 1), + ScalarType::I16 | ScalarType::U16 | ScalarType::Char16 => (2, 2), + ScalarType::I32 + | ScalarType::U32 + | ScalarType::F32 + | ScalarType::Win32Bool + | ScalarType::HResult => (4, 4), + ScalarType::I64 | ScalarType::U64 | ScalarType::F64 => (8, 8), + ScalarType::NativeIsize | ScalarType::NativeUsize => ( + architecture.pointer_size(), + architecture.pointer_alignment(), + ), + }, + ComAbiType::Guid => (16, 4), + ComAbiType::Enum(enum_id) => { + let scalar = model.enums.get(*enum_id)?.underlying(); + match scalar { + ScalarType::I8 | ScalarType::U8 => (1, 1), + ScalarType::I16 | ScalarType::U16 => (2, 2), + ScalarType::I32 | ScalarType::U32 => (4, 4), + ScalarType::I64 | ScalarType::U64 => (8, 8), + _ => { + return Err(ModelError::InvalidLayout( + "enum has a non-integral ABI".into(), + )); + } + } + } + ComAbiType::NativeStruct(layout_id) | ComAbiType::NativeUnion(layout_id) => { + let layout = model.layouts.get(*layout_id)?.get(architecture); + (layout.size(), layout.alignment()) + } + ComAbiType::Pointer { .. } + | ComAbiType::Handle(_) + | ComAbiType::DataPointer { .. } + | ComAbiType::StringPointer { .. } + | ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::ComInterface { .. } + | ComAbiType::CountedBuffer { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::FunctionPointer(_) => ( + architecture.pointer_size(), + architecture.pointer_alignment(), + ), + ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + | ComAbiType::Unknown(_) => { + return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); + } + }; + visiting.remove(&type_id); + Ok(result) +} + +fn align_up(value: usize, alignment: usize) -> Result { + value + .checked_add(alignment - 1) + .map(|value| value & !(alignment - 1)) + .ok_or_else(|| ModelError::InvalidLayout("alignment overflow".into())) +} + +fn map_pointer_alias( + model: &mut ComModel, + namespace: &str, + name: &str, +) -> Result { + let native_name = QualifiedName::new(namespace, name)?; + if namespace == "Windows.Win32.Foundation" + && matches!(name, "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR") + { + return insert_abi( + model, + Some(native_name), + None, + ComAbiType::StringPointer { + encoding: StringEncoding::Utf16, + constness: if matches!(name, "PCWSTR" | "LPCWSTR") { + Constness::Const + } else { + Constness::Mutable + }, + }, + ); + } + if namespace == "Windows.Win32.Foundation" + && matches!(name, "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR") + { + return insert_abi( + model, + Some(native_name), + None, + ComAbiType::StringPointer { + encoding: StringEncoding::Ansi, + constness: if matches!(name, "PCSTR" | "LPCSTR") { + Constness::Const + } else { + Constness::Mutable + }, + }, + ); + } + if is_known_data_pointer_alias(namespace, name) { + let underlying = insert_abi( + model, + None, + None, + ComAbiType::DataPointer { + pointee: DataPointee::Opaque(None), + depth: NonZeroU8::new(1).unwrap(), + constness: if matches!(name, "PCVOID" | "LPCVOID") { + Constness::Const + } else { + Constness::Mutable + }, + }, + )?; + return insert_abi( + model, + Some(native_name.clone()), + Some(underlying), + ComAbiType::DataPointer { + pointee: DataPointee::Opaque(Some(native_name)), + depth: NonZeroU8::new(1).unwrap(), + constness: if matches!(name, "PCVOID" | "LPCVOID") { + Constness::Const + } else { + Constness::Mutable + }, + }, + ); + } + if is_known_handle_alias(namespace, name) { + return insert_abi( + model, + Some(native_name.clone()), + None, + ComAbiType::Handle(HandleKind::new(native_name)), + ); + } + Err(ModelError::Unsupported( + UnsupportedReason::UnknownPointerMeaning, + )) +} + +fn map_buffer_element( + model: &mut ComModel, + param: &RawComParam, + callee_allocated: bool, + byte_counted: bool, +) -> Result<(BufferElement, BufferElementOwnership), ModelError> { + let raw = ¶m.typ; + if let Some(string) = ¶m.string_pointer_array { + let encoding = match string.encoding { + RawStringEncoding::Utf16 => StringEncoding::Utf16, + RawStringEncoding::Ansi => StringEncoding::Ansi, + RawStringEncoding::Unknown => { + return Err(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + )); + } + }; + let ownership = match string.ownership { + RawElementOwnership::Borrowed => BufferElementOwnership::Borrowed, + RawElementOwnership::CoTaskMemOwned => BufferElementOwnership::CoTaskMemStringOwned, + RawElementOwnership::Unknown => BufferElementOwnership::Unknown, + }; + return Ok(( + BufferElement::StringPointer { + encoding, + pointer_depth: nonzero_pointer_depth(string.pointer_depth)?, + constness: map_constness(string.constness, false), + }, + ownership, + )); + } + if raw.pointer_depth == 0 + && let RawNativeType::Named { + namespace, name, .. + } = &raw.native_type + { + if namespace == "Windows.Win32.Foundation" + && matches!(name.as_str(), "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR") + { + return Ok(( + BufferElement::Character(StringEncoding::Utf16), + BufferElementOwnership::Plain, + )); + } + if namespace == "Windows.Win32.Foundation" + && matches!(name.as_str(), "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR") + { + return Ok(( + BufferElement::Character(StringEncoding::Ansi), + BufferElementOwnership::Plain, + )); + } + } + if let RawNativeType::Array(raw_element) = &raw.native_type { + let element = map_type(model, raw_element, false)?; + let ownership = buffer_element_ownership(model, element)?; + return Ok((BufferElement::Typed(element), ownership)); + } + let mut element_raw = raw.clone(); + let pointer_layers = if callee_allocated { 2 } else { 1 }; + while element_raw.pointer_depth < pointer_layers { + let Some(underlying) = element_raw.underlying.as_deref() else { + break; + }; + let mut expanded = underlying.clone(); + expanded.pointer_depth = expanded + .pointer_depth + .saturating_add(element_raw.pointer_depth); + element_raw = expanded; + } + if element_raw.pointer_depth < pointer_layers { + return Err(ModelError::Unsupported( + UnsupportedReason::UnknownNativeType, + )); + } + element_raw.pointer_depth -= pointer_layers; + if byte_counted && matches!(element_raw.native_type, RawNativeType::Void) { + let element = insert_abi(model, None, None, ComAbiType::Scalar(ScalarType::U8))?; + return Ok((BufferElement::Typed(element), BufferElementOwnership::Plain)); + } + let element = map_type(model, &element_raw, false)?; + let ownership = buffer_element_ownership(model, element)?; + Ok((BufferElement::Typed(element), ownership)) +} + +fn buffer_element_ownership( + model: &ComModel, + element: TypeId, +) -> Result { + let definition = model.types().get(element)?; + let ownership = match definition.abi() { + ComAbiType::Scalar(_) + | ComAbiType::Guid + | ComAbiType::Enum(_) + | ComAbiType::NativeStruct(_) => BufferElementOwnership::Plain, + ComAbiType::Bstr => BufferElementOwnership::BstrOwned, + ComAbiType::ComInterface { .. } => BufferElementOwnership::ComOwned, + ComAbiType::Variant => BufferElementOwnership::VariantOwned, + ComAbiType::Pointer { pointee, .. } + if matches!( + model.types().get(*pointee)?.abi(), + ComAbiType::ComInterface { .. } + ) => + { + BufferElementOwnership::ComOwned + } + ComAbiType::StringPointer { .. } + | ComAbiType::Pointer { .. } + | ComAbiType::Handle(_) + | ComAbiType::DataPointer { .. } + | ComAbiType::HString + | ComAbiType::NativeUnion(_) + | ComAbiType::CountedBuffer { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + | ComAbiType::FunctionPointer(_) + | ComAbiType::Unknown(_) => BufferElementOwnership::Unknown, + }; + Ok(ownership) +} + +fn map_ownership( + model: &mut ComModel, + abi_type: TypeId, + direction: Direction, + raw: &RawComParam, + raw_method: &RawComMethod, + param_index: usize, + dynamic_iid_output: bool, +) -> Result<(ComOwnership, Cleanup), ModelError> { + if !direction.is_output() { + if raw.free_with.is_some() { + return Err(ModelError::InvalidOwnership(format!( + "input parameter `{}` declares output cleanup", + raw.name + ))); + } + return Ok((ComOwnership::Borrowed, Cleanup::None)); + } + if let ComAbiType::CountedBuffer { + element_ownership, .. + } = model.types().get(abi_type)?.abi() + { + if matches!(element_ownership, BufferElementOwnership::Plain) + && raw.typ.pointer_depth == 2 + && raw + .free_with + .as_ref() + .is_some_and(|free_with| free_with.function == "CoTaskMemFree") + { + return Ok((ComOwnership::CoTaskMemOwned, Cleanup::CoTaskMemFree)); + } + match (element_ownership, raw.free_with.as_ref()) { + (BufferElementOwnership::BstrOwned, Some(free_with)) + if free_with.function == "SysFreeString" => {} + ( + BufferElementOwnership::Plain + | BufferElementOwnership::ComOwned + | BufferElementOwnership::VariantOwned + | BufferElementOwnership::CoTaskMemStringOwned, + None, + ) => {} + _ => return Err(ModelError::Unsupported(UnsupportedReason::UnknownCleanup)), + } + return Ok((ComOwnership::Borrowed, Cleanup::None)); + } + let bstr_in_out = direction == Direction::InOut + && raw + .free_with + .as_ref() + .is_some_and(|free_with| free_with.function == "SysFreeString") + && matches!(output_value_type(model, abi_type)?, ComAbiType::Bstr); + if direction == Direction::InOut && raw.free_with.is_some() && !bstr_in_out { + return Err(ModelError::InvalidOwnership(format!( + "in/out parameter `{}` transfers allocator ownership", + raw.name + ))); + } + if let Some(free_with) = &raw.free_with { + return match free_with.function.as_str() { + "CoTaskMemFree" => Ok((ComOwnership::CoTaskMemOwned, Cleanup::CoTaskMemFree)), + "SysFreeString" if bstr_in_out => { + Ok((ComOwnership::BstrReplaced, Cleanup::SysFreeString)) + } + "SysFreeString" => Ok((ComOwnership::BstrOwned, Cleanup::SysFreeString)), + "WindowsDeleteString" => Ok((ComOwnership::HStringOwned, Cleanup::WindowsDeleteString)), + "LocalFree" => Ok((ComOwnership::LocalOwned, Cleanup::LocalFree)), + function if handle_cleanup_namespace(function).is_some() => { + let cleanup = HandleCleanup::new(QualifiedName::new( + handle_cleanup_namespace(function).unwrap(), + function, + )?); + Ok(( + ComOwnership::HandleOwned(cleanup.clone()), + Cleanup::Handle(cleanup), + )) + } + _ => Err(ModelError::Unsupported(UnsupportedReason::UnknownCleanup)), + }; + } + let output = output_value_type(model, abi_type)?; + match output { + ComAbiType::ComInterface { .. } if direction == Direction::Out => { + Ok((ComOwnership::ComOwned, Cleanup::ComRelease)) + } + ComAbiType::HString if direction == Direction::Out => { + Ok((ComOwnership::HStringOwned, Cleanup::WindowsDeleteString)) + } + ComAbiType::Handle(handle) + if direction == Direction::Out + && handle.native_name().namespace() == "Windows.Win32.Foundation" + && handle.native_name().name() == "HWND" + && crate::com_metadata::is_registered_borrowed_hwnd_output( + raw_method, + param_index, + ) => + { + Ok((ComOwnership::Borrowed, Cleanup::None)) + } + ComAbiType::Handle(handle) if direction == Direction::Out => Err( + ModelError::Unsupported(UnsupportedReason::Other(format!( + "owned handle output `{}` requires an explicit projected cleanup owner", + handle.native_name().name() + ))), + ), + ComAbiType::Scalar(_) + | ComAbiType::Guid + | ComAbiType::Enum(_) + | ComAbiType::NativeStruct(_) + | ComAbiType::CountedBuffer { .. } => Ok((ComOwnership::Borrowed, Cleanup::None)), + ComAbiType::Handle(_) => Ok((ComOwnership::Borrowed, Cleanup::None)), + ComAbiType::NativeUnion(_) if direction == Direction::Out => Err( + ModelError::Unsupported(UnsupportedReason::Other( + "native union outputs require an explicit active-field/discriminant contract" + .into(), + )), + ), + ComAbiType::NativeUnion(_) => Ok((ComOwnership::Borrowed, Cleanup::None)), + ComAbiType::Variant if direction == Direction::Out => { + Ok((ComOwnership::VariantOwned, Cleanup::VariantClear)) + } + ComAbiType::PropVariant if direction == Direction::Out => Ok(( + ComOwnership::PropVariantOwned, + Cleanup::PropVariantClear, + )), + ComAbiType::ExcepInfo if direction == Direction::Out => { + Ok((ComOwnership::ExcepInfoOwned, Cleanup::ExcepInfoClear)) + } + ComAbiType::DispatchParams if direction == Direction::Out => Err( + ModelError::Unsupported(UnsupportedReason::Other( + "DISPPARAMS is input-only".into(), + )), + ), + ComAbiType::SafeArray { .. } if direction == Direction::Out => { + Ok((ComOwnership::SafeArrayOwned, Cleanup::SafeArrayDestroy)) + } + ComAbiType::Pointer { pointee, depth, .. } + if direction == Direction::Out + && depth.get() == 1 + && matches!( + model.types().get(pointee)?.abi(), + ComAbiType::SafeArray { .. } + ) => + { + Ok((ComOwnership::SafeArrayOwned, Cleanup::SafeArrayDestroy)) + } + ComAbiType::Variant + | ComAbiType::SafeArray { .. } + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + if direction == Direction::InOut => + { + Err(ModelError::Unsupported(UnsupportedReason::Other( + "Automation BYREF/InOut parameters require an explicit borrow, replacement, and cleanup contract" + .into(), + ))) + } + ComAbiType::DataPointer { .. } if dynamic_iid_output && direction == Direction::Out => { + Ok((ComOwnership::ComOwned, Cleanup::ComRelease)) + } + ComAbiType::DataPointer { .. } if direction == Direction::InOut => { + if output_value_type_id(model, abi_type).is_some_and(|output| { + model + .types() + .get(output) + .is_ok_and(|definition| definition.underlying().is_some()) + }) { + Ok((ComOwnership::Borrowed, Cleanup::None)) + } else { + Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)) + } + } + ComAbiType::Pointer { .. } + | ComAbiType::DataPointer { .. } + | ComAbiType::StringPointer { .. } + | ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::ComInterface { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + | ComAbiType::FunctionPointer(_) + | ComAbiType::Unknown(_) => { + Err(ModelError::Unsupported(UnsupportedReason::UnknownOwnership)) + } + } +} + +fn output_value_type(model: &ComModel, abi_type: TypeId) -> Result { + let abi = model.types().get(abi_type)?.abi(); + if let ComAbiType::Pointer { + pointee, + depth, + constness, + } = abi + { + if depth.get() == 1 { + return Ok(model.types().get(*pointee)?.abi().clone()); + } + return Ok(ComAbiType::Pointer { + pointee: *pointee, + depth: NonZeroU8::new(depth.get() - 1).unwrap(), + constness: *constness, + }); + } + if let ComAbiType::DataPointer { + pointee, + depth, + constness, + } = abi + { + if depth.get() > 1 { + return Ok(ComAbiType::DataPointer { + pointee: pointee.clone(), + depth: NonZeroU8::new(depth.get() - 1).unwrap(), + constness: *constness, + }); + } + } + Ok(abi.clone()) +} + +fn output_value_type_id(model: &ComModel, abi_type: TypeId) -> Option { + match model.types().get(abi_type).ok()?.abi() { + ComAbiType::Pointer { pointee, depth, .. } if depth.get() == 1 => Some(*pointee), + _ => Some(abi_type), + } +} + +fn dynamic_iid_contract(method: &RawComMethod) -> Result, ModelError> { + let iid_like = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| is_iid_like_parameter(param).then_some(index)) + .collect::>(); + let output_like = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| is_dynamic_output_like(param).then_some(index)) + .collect::>(); + let iid_candidates = iid_like + .iter() + .copied() + .filter(|index| is_exact_iid_parameter(&method.params[*index])) + .collect::>(); + let output_candidates = output_like + .iter() + .copied() + .filter(|index| is_exact_dynamic_output(&method.params[*index])) + .collect::>(); + + if iid_like.is_empty() || output_like.is_empty() { + return Ok(None); + } + if iid_candidates.is_empty() && output_candidates.is_empty() { + return Ok(None); + } + if iid_candidates.len() != 1 + || output_candidates.len() != 1 + || iid_like.len() != 1 + || output_like.len() != 1 + { + return Err(ModelError::InvalidContract(format!( + "{} has an ambiguous or unsupported dynamic-IID parameter contract", + method.projected_name + ))); + } + if !is_plain_hresult_return(method) { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID methods require an HRESULT return", + method.projected_name + ))); + } + if method + .params + .iter() + .any(|param| param.direction == RawParamDirection::InOut) + { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID methods cannot contain [in, out] parameters", + method.projected_name + ))); + } + DynamicIidContract::new( + ParamIndex::new(iid_candidates[0]), + ParamIndex::new(output_candidates[0]), + ) + .map(Some) +} + +fn is_plain_hresult_return(method: &RawComMethod) -> bool { + method.semantic_hresult.is_none() + && method.enumerator_next.is_none() + && method.return_type.pointer_depth == 0 + && matches!( + &method.return_type.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Foundation" && name == "HRESULT" + ) +} + +fn is_iid_like_parameter(param: &RawComParam) -> bool { + matches!(param.name.to_ascii_lowercase().as_str(), "iid" | "riid") + && matches!( + ¶m.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "System" && name == "Guid" + ) +} + +fn is_exact_iid_parameter(param: &RawComParam) -> bool { + if param.direction != RawParamDirection::In + || param.optional + || !matches!(param.name.to_ascii_lowercase().as_str(), "iid" | "riid") + || param.typ.pointer_depth != 1 + || !(param.const_attribute || param.typ.constness == RawConstness::Const) + || param.native_array.is_some() + || param.free_with.is_some() + { + return false; + } + matches!( + ¶m.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "System" && name == "Guid" + ) +} + +fn is_dynamic_output_like(param: &RawComParam) -> bool { + param.direction != RawParamDirection::In + && param.typ.pointer_depth > 0 + && matches!( + param.typ.native_type, + RawNativeType::Object | RawNativeType::Void + ) +} + +fn is_exact_dynamic_output(param: &RawComParam) -> bool { + param.direction == RawParamDirection::Out + && !param.optional + && param.typ.pointer_depth == 2 + && param.typ.constness == RawConstness::Mutable + && matches!( + param.typ.native_type, + RawNativeType::Object | RawNativeType::Void + ) + && param.native_array.is_none() + && param.free_with.is_none() +} + +fn is_hresult(model: &ComModel, abi_type: TypeId) -> Result { + Ok(matches!( + model.types().get(abi_type)?.abi(), + ComAbiType::Scalar(ScalarType::HResult) + )) +} + +fn is_nullable_type(model: &ComModel, abi_type: TypeId) -> Result { + Ok(matches!( + model.types().get(abi_type)?.abi(), + ComAbiType::Pointer { .. } + | ComAbiType::Handle(_) + | ComAbiType::DataPointer { .. } + | ComAbiType::StringPointer { .. } + | ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::ComInterface { .. } + | ComAbiType::CountedBuffer { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::FunctionPointer(_) + )) +} + +fn raw_native_name(raw: &RawComType) -> Result, ModelError> { + match &raw.native_type { + RawNativeType::Named { + namespace, name, .. + } => Ok(Some(QualifiedName::new(namespace, name)?)), + _ => Ok(None), + } +} + +fn insert_abi( + model: &mut ComModel, + native_name: Option, + underlying: Option, + abi: ComAbiType, +) -> Result { + model + .types_mut() + .insert(ComTypeDefinition::new(native_name, underlying, abi)) +} + +fn map_direction(direction: RawParamDirection) -> Direction { + match direction { + RawParamDirection::In => Direction::In, + RawParamDirection::Out => Direction::Out, + RawParamDirection::InOut => Direction::InOut, + } +} + +fn map_count_relation( + buffer_direction: RawParamDirection, + count_direction: RawParamDirection, + count_param: ParamIndex, + actual_length_param: Option, + unit: CountUnit, + two_call: bool, + projected_capacity: bool, +) -> CountRelation { + match buffer_direction { + RawParamDirection::In => CountRelation::InputCount { + count_param, + actual_length_param, + unit, + }, + RawParamDirection::Out | RawParamDirection::InOut => match count_direction { + RawParamDirection::In => CountRelation::CallerCapacity { + capacity_param: count_param, + actual_length_param, + unit, + sizing: if two_call { + BufferSizing::TwoCall { max_retries: 2 } + } else if projected_capacity { + BufferSizing::FixedCapacity + } else { + BufferSizing::SingleCall + }, + }, + RawParamDirection::InOut => CountRelation::CallerCapacity { + capacity_param: count_param, + actual_length_param: Some(actual_length_param.unwrap_or(count_param)), + unit, + sizing: if two_call { + BufferSizing::TwoCall { max_retries: 2 } + } else if projected_capacity { + BufferSizing::FixedCapacity + } else { + BufferSizing::SingleCall + }, + }, + RawParamDirection::Out => CountRelation::CalleeAllocated { count_param, unit }, + }, + } +} + +fn map_constness(constness: RawConstness, const_attribute: bool) -> Constness { + if const_attribute { + Constness::Const + } else { + match constness { + RawConstness::Const => Constness::Const, + RawConstness::Mutable => Constness::Mutable, + RawConstness::Unspecified => Constness::Unspecified, + } + } +} + +fn buffer_constness(raw: &RawComParam) -> Constness { + if raw.const_attribute { + return Constness::Const; + } + match raw.typ.constness { + RawConstness::Const => return Constness::Const, + RawConstness::Mutable => return Constness::Mutable, + RawConstness::Unspecified => {} + } + if raw.typ.pointer_depth > 0 { + return Constness::Unspecified; + } + if let RawNativeType::Named { name, .. } = &raw.typ.native_type { + if matches!(name.as_str(), "PCWSTR" | "LPCWSTR" | "PCSTR" | "LPCSTR") { + return Constness::Const; + } + } + Constness::Mutable +} + +fn nonzero_pointer_depth(depth: usize) -> Result { + u8::try_from(depth) + .ok() + .and_then(NonZeroU8::new) + .ok_or_else(|| ModelError::InvalidContract(format!("unsupported pointer depth {depth}"))) +} + +fn raw_scalar(typ: &RawComType) -> Option { + if typ.pointer_depth != 0 { + return None; + } + match typ.native_type { + RawNativeType::Bool => Some(ScalarType::Bool), + RawNativeType::I8 => Some(ScalarType::I8), + RawNativeType::U8 => Some(ScalarType::U8), + RawNativeType::I16 => Some(ScalarType::I16), + RawNativeType::U16 => Some(ScalarType::U16), + RawNativeType::I32 => Some(ScalarType::I32), + RawNativeType::U32 => Some(ScalarType::U32), + RawNativeType::I64 => Some(ScalarType::I64), + RawNativeType::U64 => Some(ScalarType::U64), + RawNativeType::F32 => Some(ScalarType::F32), + RawNativeType::F64 => Some(ScalarType::F64), + RawNativeType::Char16 => Some(ScalarType::Char16), + RawNativeType::ISize => Some(ScalarType::NativeIsize), + RawNativeType::USize => Some(ScalarType::NativeUsize), + _ => None, + } +} + +fn raw_scalar_alias(typ: &RawComType, namespace: &str, alias_name: &str) -> Option { + match (namespace, alias_name) { + ("Windows.Win32.Foundation", "LPARAM" | "LRESULT") => Some(ScalarType::NativeIsize), + ("Windows.Win32.Foundation", "WPARAM") => Some(ScalarType::NativeUsize), + _ => raw_scalar(typ), + } +} + +fn handle_cleanup_namespace(function: &str) -> Option<&'static str> { + match function { + "CloseHandle" | "DestroyIcon" => Some("Windows.Win32.Foundation"), + "RegCloseKey" => Some("Windows.Win32.System.Registry"), + _ => None, + } +} + +fn is_known_handle_alias(namespace: &str, name: &str) -> bool { + match namespace { + "Windows.Win32.Foundation" => matches!( + name, + "HANDLE" | "HWND" | "HGLOBAL" | "HINSTANCE" | "HLOCAL" | "HMODULE" | "HRSRC" + ), + "Windows.Win32.Graphics.Gdi" => matches!( + name, + "HBITMAP" + | "HBRUSH" + | "HDC" + | "HENHMETAFILE" + | "HFONT" + | "HGDIOBJ" + | "HMETAFILE" + | "HPALETTE" + | "HPEN" + | "HRGN" + ), + "Windows.Win32.UI.WindowsAndMessaging" => matches!( + name, + "HWND" + | "HACCEL" + | "HCURSOR" + | "HDESK" + | "HDWP" + | "HHOOK" + | "HICON" + | "HMENU" + | "HMONITOR" + | "HWINSTA" + ), + "Windows.Win32.System.Registry" => name == "HKEY", + "Windows.Win32.UI.Controls" => matches!(name, "HIMAGELIST" | "HTHEME"), + "Windows.Win32.UI.Input.KeyboardAndMouse" => name == "HKL", + "Windows.Win32.System.Services" => { + matches!(name, "SC_HANDLE" | "SERVICE_STATUS_HANDLE") + } + "Windows.Win32.UI.HiDpi" => name == "DPI_AWARENESS_CONTEXT", + _ => false, + } +} + +fn is_known_data_pointer_alias(namespace: &str, name: &str) -> bool { + matches!( + (namespace, name), + ("Windows.Win32.Security", "PSID" | "PSECURITY_DESCRIPTOR") + | ("Windows.Win32.System.Memory", "MEMORY_MAPPED_VIEW_ADDRESS") + | ( + "Windows.Win32.System.Threading", + "LPPROC_THREAD_ATTRIBUTE_LIST" + ) + | ( + "Windows.Win32.Foundation", + "PVOID" | "PCVOID" | "LPVOID" | "LPCVOID" + ) + ) +} + +fn is_explicit_pointer_alias(namespace: &str, name: &str) -> bool { + (namespace == "Windows.Win32.Foundation" + && matches!( + name, + "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR" | "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR" + )) + || is_known_data_pointer_alias(namespace, name) + || is_known_handle_alias(namespace, name) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn win32_winmd() -> Option { + std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + } + + fn raw_string_alias(name: &str, pointer_depth: usize) -> RawComType { + RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: name.into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth, + constness: RawConstness::Mutable, + } + } + + fn raw_guid_param(name: &str, pointer_depth: usize) -> RawComParam { + RawComParam { + name: name.into(), + typ: RawComType { + native_type: RawNativeType::Named { + namespace: "System".into(), + name: "Guid".into(), + kind: RawNamedKind::Unknown, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth, + constness: RawConstness::Mutable, + }, + direction: RawParamDirection::In, + optional: false, + const_attribute: true, + native_array: None, + string_pointer_array: None, + free_with: None, + safe_array_evidence: None, + } + } + + fn raw_void_output(name: &str, pointer_depth: usize) -> RawComParam { + RawComParam { + name: name.into(), + typ: RawComType { + native_type: RawNativeType::Void, + underlying: None, + pointer_depth, + constness: RawConstness::Mutable, + }, + direction: RawParamDirection::Out, + optional: false, + const_attribute: false, + native_array: None, + string_pointer_array: None, + free_with: None, + safe_array_evidence: None, + } + } + + fn raw_dynamic_method(params: Vec) -> RawComMethod { + RawComMethod { + declaring_namespace: "Test".into(), + declaring_interface: "ITest".into(), + declaring_iid: "00000000-0000-0000-c000-000000000046".into(), + metadata_name: "Resolve".into(), + projected_name: "Resolve".into(), + vtable_index: 3, + params, + return_type: RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: "HRESULT".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: Some(Box::new(RawComType { + native_type: RawNativeType::I32, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + })), + pointer_depth: 0, + constness: RawConstness::Unspecified, + }, + semantic_hresult: None, + enumerator_next: None, + exact_contract: None, + safe_array_contract_error: None, + } + } + + #[test] + fn dynamic_iid_contract_uses_explicit_non_positional_indices() { + let scalar = RawComParam { + name: "flags".into(), + typ: RawComType { + native_type: RawNativeType::U32, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + }, + direction: RawParamDirection::In, + optional: false, + const_attribute: false, + native_array: None, + string_pointer_array: None, + free_with: None, + safe_array_evidence: None, + }; + let method = raw_dynamic_method(vec![ + scalar.clone(), + raw_guid_param("riid", 1), + scalar.clone(), + raw_void_output("object", 2), + scalar, + ]); + let contract = dynamic_iid_contract(&method).unwrap().unwrap(); + assert_eq!(contract.iid_param_index().index(), 1); + assert_eq!(contract.output_param_index().index(), 3); + } + + #[test] + fn dynamic_iid_contract_fails_closed_on_nearest_unsafe_shapes() { + let assert_rejected = |params: Vec| { + assert!(dynamic_iid_contract(&raw_dynamic_method(params)).is_err()); + }; + + let mut by_value = raw_guid_param("iid", 0); + by_value.const_attribute = false; + assert_rejected(vec![by_value, raw_void_output("object", 2)]); + + let mut mutable = raw_guid_param("iid", 1); + mutable.const_attribute = false; + assert_rejected(vec![mutable, raw_void_output("object", 2)]); + assert_rejected(vec![raw_guid_param("iid", 2), raw_void_output("object", 2)]); + assert_rejected(vec![raw_guid_param("iid", 1), raw_void_output("object", 1)]); + assert_rejected(vec![raw_guid_param("iid", 1), raw_void_output("object", 3)]); + + let mut optional_iid = raw_guid_param("iid", 1); + optional_iid.optional = true; + assert_rejected(vec![optional_iid, raw_void_output("object", 2)]); + let mut optional_output = raw_void_output("object", 2); + optional_output.optional = true; + assert_rejected(vec![raw_guid_param("iid", 1), optional_output]); + + let mut array_iid = raw_guid_param("iid", 1); + array_iid.native_array = Some(crate::com_metadata::RawArrayRelation { + count_param_index: Some(0), + actual_length_param_index: None, + unit: RawCountUnit::Elements, + two_call: false, + projected_capacity: false, + constness: None, + evidence: Vec::new(), + }); + assert_rejected(vec![array_iid, raw_void_output("object", 2)]); + + let mut free_output = raw_void_output("object", 2); + free_output.free_with = Some(crate::com_metadata::RawFreeWith { + function: "CoTaskMemFree".into(), + evidence: crate::com_metadata::RawEvidence::MetadataAttribute("FreeWithAttribute"), + }); + assert_rejected(vec![raw_guid_param("iid", 1), free_output]); + + assert_rejected(vec![ + raw_guid_param("iid", 1), + raw_guid_param("riid", 1), + raw_void_output("object", 2), + ]); + assert_rejected(vec![ + raw_guid_param("iid", 1), + raw_void_output("first", 2), + raw_void_output("second", 2), + ]); + + let mut in_out = RawComParam { + name: "count".into(), + typ: RawComType { + native_type: RawNativeType::U32, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Mutable, + }, + direction: RawParamDirection::InOut, + optional: false, + const_attribute: false, + native_array: None, + string_pointer_array: None, + free_with: None, + safe_array_evidence: None, + }; + assert_rejected(vec![ + raw_guid_param("iid", 1), + raw_void_output("object", 2), + in_out.clone(), + ]); + in_out.native_array = Some(crate::com_metadata::RawArrayRelation { + count_param_index: Some(2), + actual_length_param_index: None, + unit: RawCountUnit::Elements, + two_call: false, + projected_capacity: false, + constness: None, + evidence: Vec::new(), + }); + assert_rejected(vec![ + raw_guid_param("iid", 1), + raw_void_output("objects", 2), + in_out, + ]); + + let mut non_hresult = + raw_dynamic_method(vec![raw_guid_param("iid", 1), raw_void_output("object", 2)]); + non_hresult.return_type = RawComType { + native_type: RawNativeType::U32, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + }; + assert!(dynamic_iid_contract(&non_hresult).is_err()); + } + + #[test] + fn string_pointer_arrays_are_distinct_from_character_buffers() { + let mut model = ComModel::default(); + let string_array = RawComParam { + name: "names".into(), + typ: raw_string_alias("PCWSTR", 1), + direction: RawParamDirection::In, + optional: false, + const_attribute: false, + native_array: None, + string_pointer_array: Some(crate::com_metadata::RawStringPointerArray { + encoding: RawStringEncoding::Utf16, + pointer_depth: 1, + constness: RawConstness::Const, + ownership: RawElementOwnership::Borrowed, + }), + free_with: None, + safe_array_evidence: None, + }; + assert_eq!( + map_buffer_element(&mut model, &string_array, false, false).unwrap(), + ( + BufferElement::StringPointer { + encoding: StringEncoding::Utf16, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + BufferElementOwnership::Borrowed, + ) + ); + + let character_buffer = RawComParam { + name: "text".into(), + typ: raw_string_alias("PWSTR", 0), + direction: RawParamDirection::Out, + string_pointer_array: None, + ..string_array.clone() + }; + assert_eq!( + map_buffer_element(&mut model, &character_buffer, false, false).unwrap(), + ( + BufferElement::Character(StringEncoding::Utf16), + BufferElementOwnership::Plain, + ) + ); + + let counted_nonterminated = RawComParam { + name: "characters".into(), + typ: RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: "PWCHAR".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: Some(Box::new(RawComType { + native_type: RawNativeType::Char16, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Mutable, + })), + pointer_depth: 0, + constness: RawConstness::Mutable, + }, + direction: RawParamDirection::Out, + string_pointer_array: None, + ..character_buffer.clone() + }; + assert!(map_type(&mut model, &counted_nonterminated.typ, false).is_err()); + let (element, ownership) = + map_buffer_element(&mut model, &counted_nonterminated, false, false).unwrap(); + let BufferElement::Typed(element) = element else { + panic!("counted PWCHAR must remain a typed character buffer"); + }; + assert_eq!( + model.types().get(element).unwrap().abi(), + &ComAbiType::Scalar(ScalarType::Char16) + ); + assert_eq!(ownership, BufferElementOwnership::Plain); + + let unknown = RawComParam { + string_pointer_array: Some(crate::com_metadata::RawStringPointerArray { + encoding: RawStringEncoding::Unknown, + pointer_depth: 1, + constness: RawConstness::Const, + ownership: RawElementOwnership::Borrowed, + }), + ..string_array + }; + assert!(map_buffer_element(&mut model, &unknown, false, false).is_err()); + } + + #[test] + fn taskbar_metadata_maps_to_complete_semantic_contracts() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let semantic = map_interface(&interface).unwrap(); + + assert_eq!( + semantic.iid, + ComGuid::parse(&interface.interface.iid).unwrap() + ); + assert_eq!(semantic.methods.len(), interface.interface.methods.len()); + semantic.validate().unwrap(); + assert_windows_rs_iid::(&semantic); + + let add_buttons = semantic + .methods() + .iter() + .find(|method| method.name() == "ThumbBarAddButtons") + .unwrap(); + let buttons = semantic + .type_definition(add_buttons.params()[2].abi_type()) + .unwrap(); + let ComAbiType::CountedBuffer { + element: BufferElement::Typed(element), + .. + } = buttons.abi() + else { + panic!("THUMBBUTTON input must be a typed counted buffer"); + }; + let ComAbiType::NativeStruct(layout_id) = semantic.type_definition(*element).unwrap().abi() + else { + panic!("THUMBBUTTON element must be a native POD"); + }; + assert_windows_rs_host_layout::( + &semantic, *layout_id, + ); + assert_windows_rs_field_offsets( + &semantic, + *layout_id, + &[ + ( + "dwMask", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, dwMask), + ), + ( + "iId", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, iId), + ), + ( + "iBitmap", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, iBitmap), + ), + ( + "hIcon", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, hIcon), + ), + ( + "szTip", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, szTip), + ), + ( + "dwFlags", + std::mem::offset_of!(windows::Win32::UI::Shell::THUMBBUTTON, dwFlags), + ), + ], + ); + + let set_clip = semantic + .methods() + .iter() + .find(|method| method.name() == "SetThumbnailClip") + .unwrap(); + let clip = semantic + .type_definition(set_clip.params()[1].abi_type()) + .unwrap(); + let ComAbiType::Pointer { pointee, .. } = clip.abi() else { + panic!("RECT input must be pointer-shaped"); + }; + let ComAbiType::NativeStruct(layout_id) = semantic.type_definition(*pointee).unwrap().abi() + else { + panic!("RECT pointee must be a native POD"); + }; + assert_windows_rs_host_layout::(&semantic, *layout_id); + assert_windows_rs_field_offsets( + &semantic, + *layout_id, + &[ + ( + "left", + std::mem::offset_of!(windows::Win32::Foundation::RECT, left), + ), + ( + "top", + std::mem::offset_of!(windows::Win32::Foundation::RECT, top), + ), + ( + "right", + std::mem::offset_of!(windows::Win32::Foundation::RECT, right), + ), + ( + "bottom", + std::mem::offset_of!(windows::Win32::Foundation::RECT, bottom), + ), + ], + ); + } + + #[test] + fn raw_pointer_depth_distinguishes_refiid_and_void_double_pointer() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "IDataTransferManagerInterop", + ) + .unwrap(); + let method = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetForWindow") + .unwrap(); + let iid = &method.params[method.params.len() - 2]; + let result = &method.params[method.params.len() - 1]; + + assert_eq!(iid.typ.pointer_depth, 1); + assert!(iid.const_attribute); + assert_eq!(result.typ.pointer_depth, 2); + map_interface(&interface).unwrap(); + } + + #[test] + fn shell_link_find_data_has_exact_nested_fixed_array_layouts() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "IShellLinkW", + ) + .unwrap(); + let semantic = map_interface(&interface).unwrap(); + assert_windows_rs_iid::(&semantic); + let get_path = semantic + .methods() + .iter() + .find(|method| method.name() == "GetPath") + .unwrap(); + let pfd = semantic + .type_definition(get_path.params()[2].abi_type()) + .unwrap(); + let ComAbiType::Pointer { pointee, depth, .. } = pfd.abi() else { + panic!("WIN32_FIND_DATAW must be pointer-shaped"); + }; + assert_eq!(depth.get(), 1); + let ComAbiType::NativeStruct(layout_id) = semantic.type_definition(*pointee).unwrap().abi() + else { + panic!("WIN32_FIND_DATAW pointee must be a native POD"); + }; + for architecture in Architecture::ALL { + let layout = semantic + .layout_definition(*layout_id) + .unwrap() + .get(architecture); + assert_eq!(layout.size(), 592); + assert_eq!(layout.alignment(), 4); + assert_eq!(layout.fields().len(), 10); + assert_eq!(layout.fields()[1].offset(), 4); + assert_eq!(layout.fields()[8].offset(), 44); + assert_eq!(layout.fields()[8].fixed_count().unwrap().get(), 260); + assert_eq!(layout.fields()[9].offset(), 564); + assert_eq!(layout.fields()[9].fixed_count().unwrap().get(), 14); + } + assert_windows_rs_host_layout::( + &semantic, *layout_id, + ); + assert_windows_rs_field_offsets( + &semantic, + *layout_id, + &[ + ( + "dwFileAttributes", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + dwFileAttributes + ), + ), + ( + "ftCreationTime", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + ftCreationTime + ), + ), + ( + "ftLastAccessTime", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + ftLastAccessTime + ), + ), + ( + "ftLastWriteTime", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + ftLastWriteTime + ), + ), + ( + "nFileSizeHigh", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + nFileSizeHigh + ), + ), + ( + "nFileSizeLow", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + nFileSizeLow + ), + ), + ( + "dwReserved0", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + dwReserved0 + ), + ), + ( + "dwReserved1", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + dwReserved1 + ), + ), + ( + "cFileName", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + cFileName + ), + ), + ( + "cAlternateFileName", + std::mem::offset_of!( + windows::Win32::Storage::FileSystem::WIN32_FIND_DATAW, + cAlternateFileName + ), + ), + ], + ); + } + + #[test] + fn windows_rs_interface_iids_match_dynamic_win32_metadata() { + let Some(winmd) = win32_winmd() else { + return; + }; + assert_interface_iid::( + &winmd, + "Windows.Win32.System.Com", + "IPersistFile", + true, + ); + assert_interface_iid::( + &winmd, + "Windows.Win32.System.Com", + "ISequentialStream", + true, + ); + assert_interface_iid::( + &winmd, + "Windows.Win32.UI.Shell", + "IDataTransferManagerInterop", + true, + ); + assert_interface_iid::( + &winmd, + "Windows.Win32.System.WinRT", + "ISystemMediaTransportControlsInterop", + false, + ); + } + + fn assert_interface_iid( + winmd: &str, + namespace: &str, + name: &str, + is_iunknown_rooted: bool, + ) { + let interface = crate::com_metadata::parse_com_interface(winmd, namespace, name).unwrap(); + let semantic = map_interface(&interface).unwrap(); + assert_eq!(semantic.is_iunknown_rooted(), is_iunknown_rooted); + assert_windows_rs_iid::(&semantic); + } + + fn assert_windows_rs_iid(semantic: &SemanticComInterface) { + assert_eq!( + semantic.iid(), + ComGuid::from_bytes(T::IID.to_u128().to_be_bytes()) + ); + } + + fn assert_windows_rs_host_layout( + semantic: &SemanticComInterface, + layout_id: super::super::ids::LayoutId, + ) { + let architecture = host_architecture(); + let layout = semantic + .layout_definition(layout_id) + .unwrap() + .get(architecture); + assert_eq!(layout.size(), std::mem::size_of::()); + assert_eq!(layout.alignment(), std::mem::align_of::()); + } + + fn assert_windows_rs_field_offsets( + semantic: &SemanticComInterface, + layout_id: super::super::ids::LayoutId, + expected: &[(&str, usize)], + ) { + let architecture = host_architecture(); + let layout = semantic + .layout_definition(layout_id) + .unwrap() + .get(architecture); + assert_eq!(layout.fields().len(), expected.len()); + for (name, offset) in expected { + let field = layout + .fields() + .iter() + .find(|field| field.name() == *name) + .unwrap_or_else(|| panic!("semantic layout has no `{name}` field")); + assert_eq!(field.offset(), *offset, "offset mismatch for `{name}`"); + } + } + + fn host_architecture() -> Architecture { + if cfg!(target_arch = "x86") { + Architecture::X86 + } else if cfg!(target_arch = "x86_64") { + Architecture::X64 + } else if cfg!(target_arch = "aarch64") { + Architecture::Arm64 + } else { + panic!("unsupported Windows architecture for ABI oracle"); + } + } + + fn raw_scalar_type(native_type: RawNativeType) -> RawComType { + RawComType { + native_type, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + } + } + + fn raw_field(name: &str, native_type: RawNativeType) -> crate::com_metadata::RawNativeField { + crate::com_metadata::RawNativeField { + name: name.into(), + typ: raw_scalar_type(native_type), + explicit_offset: None, + fixed_count: None, + bitfield: false, + flexible_array: false, + } + } + + fn raw_named_type(namespace: &str, name: &str, pointer_depth: usize) -> RawComType { + RawComType { + native_type: RawNativeType::Named { + namespace: namespace.into(), + name: name.into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth, + constness: RawConstness::Unspecified, + } + } + + #[test] + fn automation_families_map_to_dedicated_semantic_types() { + let cases = [ + ("Windows.Win32.System.Variant", "VARIANT", "VARIANT"), + ("Windows.Win32.System.Com", "SAFEARRAY", "SAFEARRAY"), + ("Windows.Win32.System.Com", "DISPPARAMS", "DISPPARAMS"), + ("Windows.Win32.System.Com", "EXCEPINFO", "EXCEPINFO"), + ( + "Windows.Win32.System.Com.StructuredStorage", + "PROPVARIANT", + "PROPVARIANT", + ), + ]; + for (namespace, name, expected) in cases { + let mut model = ComModel::default(); + let typ = map_type(&mut model, &raw_named_type(namespace, name, 0), false).unwrap(); + let abi = model.types().get(typ).unwrap().abi(); + assert!( + matches!( + (expected, abi), + ("VARIANT", ComAbiType::Variant) + | ("SAFEARRAY", ComAbiType::SafeArray { .. }) + | ("PROPVARIANT", ComAbiType::PropVariant) + | ("DISPPARAMS", ComAbiType::DispatchParams) + | ("EXCEPINFO", ComAbiType::ExcepInfo) + ), + "{name} mapped to {abi:?}" + ); + } + } + + #[test] + fn sequential_and_explicit_layouts_are_architecture_exact() { + let sequential = RawNativeLayout { + architectures: 0b111, + kind: RawLayoutKind::Sequential, + packing: RawPacking::Default, + declared_size: None, + fields: vec![ + raw_field("tag", RawNativeType::U32), + raw_field("address", RawNativeType::USize), + ], + is_union: false, + }; + let mut x86_model = ComModel::default(); + let x86 = + compute_native_layout_variant(&mut x86_model, &sequential, Architecture::X86).unwrap(); + assert_eq!((x86.size(), x86.alignment()), (8, 4)); + assert_eq!(x86.fields()[1].offset(), 4); + + let mut x64_model = ComModel::default(); + let x64 = + compute_native_layout_variant(&mut x64_model, &sequential, Architecture::X64).unwrap(); + assert_eq!((x64.size(), x64.alignment()), (16, 8)); + assert_eq!(x64.fields()[1].offset(), 8); + + let mut explicit = sequential.clone(); + explicit.kind = RawLayoutKind::Explicit; + explicit.declared_size = Some(16); + explicit.fields[0].explicit_offset = Some(0); + explicit.fields[1].explicit_offset = Some(8); + let mut model = ComModel::default(); + let layout = + compute_native_layout_variant(&mut model, &explicit, Architecture::Arm64).unwrap(); + assert_eq!((layout.size(), layout.alignment()), (16, 8)); + assert_eq!(layout.fields()[1].offset(), 8); + } + + #[test] + fn unions_are_overlapping_and_nearest_unsupported_pod_shapes_fail_closed() { + let base = RawNativeLayout { + architectures: 0b111, + kind: RawLayoutKind::Sequential, + packing: RawPacking::Default, + declared_size: None, + fields: vec![raw_field("value", RawNativeType::U32)], + is_union: false, + }; + let assert_rejected = |layout: RawNativeLayout, expected: &str| { + let error = + compute_native_layout_variant(&mut ComModel::default(), &layout, Architecture::X64) + .unwrap_err() + .to_string(); + assert!(error.contains(expected), "{error}"); + }; + + let mut union = base.clone(); + union.kind = RawLayoutKind::Explicit; + union.is_union = true; + union.fields[0].explicit_offset = Some(0); + union.fields.push(raw_field("other", RawNativeType::U16)); + union.fields[1].explicit_offset = Some(0); + let union = + compute_native_layout_variant(&mut ComModel::default(), &union, Architecture::X64) + .unwrap(); + assert_eq!(union.kind(), LayoutKind::Union); + assert!(union.fields().iter().all(|field| field.offset() == 0)); + + let mut bitfield = base.clone(); + bitfield.fields[0].bitfield = true; + assert_rejected(bitfield.clone(), "bitfield"); + + let mut flexible = base.clone(); + flexible.fields[0].flexible_array = true; + assert_rejected(flexible, "flexible array"); + + let pointer_to_defined_bitfield = RawComType { + native_type: RawNativeType::Named { + namespace: "Test".into(), + name: "BITFIELD".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: Some(Box::new(RawNativeLayoutSet { + recursive: false, + variants: vec![bitfield], + })), + }, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Mutable, + }; + let error = map_type( + &mut ComModel::default(), + &pointer_to_defined_bitfield, + false, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("bitfield"), "{error}"); + + let mut unknown_packing = base.clone(); + unknown_packing.packing = RawPacking::Unknown; + assert_rejected(unknown_packing, "packing"); + + let mut misaligned = base.clone(); + misaligned.kind = RawLayoutKind::Explicit; + misaligned.fields[0].explicit_offset = Some(2); + assert_rejected(misaligned, "alignment"); + + let mut overlap = base.clone(); + overlap.kind = RawLayoutKind::Explicit; + overlap.fields[0].explicit_offset = Some(0); + let mut second = raw_field("other", RawNativeType::U32); + second.explicit_offset = Some(0); + overlap.fields.push(second); + assert_rejected(overlap, "overlapping"); + + let mut out_of_bounds = base.clone(); + out_of_bounds.declared_size = Some(2); + assert_rejected(out_of_bounds, "cannot contain"); + + let mut overflow = base.clone(); + overflow.kind = RawLayoutKind::Explicit; + overflow.fields[0].explicit_offset = Some(usize::MAX - 3); + assert_rejected(overflow, "overflows"); + + let mut owned = base.clone(); + owned.fields[0].typ = RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: "BSTR".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + }; + assert_rejected(owned, "ownership"); + + let mut interface_pointer = base; + interface_pointer.fields[0].typ = RawComType { + native_type: RawNativeType::Named { + namespace: "Test".into(), + name: "IFoo".into(), + kind: RawNamedKind::Interface, + iid: Some("00000000-0000-0000-c000-000000000046".into()), + layout: None, + }, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Mutable, + }; + assert_rejected(interface_pointer, "ownership"); + } + + #[test] + fn hfile_preserves_its_signed_32_bit_abi() { + let raw = RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: "HFILE".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: Some(Box::new(raw_scalar_type(RawNativeType::I32))), + pointer_depth: 0, + constness: RawConstness::Unspecified, + }; + let mut model = ComModel::default(); + let typ = map_type(&mut model, &raw, false).unwrap(); + assert!(matches!( + model.types().get(typ).unwrap().abi(), + ComAbiType::Scalar(ScalarType::I32) + )); + } + + #[test] + fn pointer_aliases_require_exact_qualified_identity() { + let mut model = ComModel::default(); + assert!(map_pointer_alias(&mut model, "Windows.Win32.Foundation", "HWND").is_ok()); + assert!(map_pointer_alias(&mut model, "Contoso", "HWND").is_err()); + assert!(map_pointer_alias(&mut model, "Contoso", "PWSTR").is_err()); + let u32_type = raw_scalar_type(RawNativeType::U32); + assert_eq!( + raw_scalar_alias(&u32_type, "Windows.Win32.Foundation", "WPARAM"), + Some(ScalarType::NativeUsize) + ); + assert_eq!( + raw_scalar_alias(&u32_type, "Contoso", "WPARAM"), + Some(ScalarType::U32) + ); + } + + #[test] + fn recursive_and_missing_architecture_layouts_fail_closed() { + let variant = RawNativeLayout { + architectures: Architecture::X64.metadata_mask(), + kind: RawLayoutKind::Sequential, + packing: RawPacking::Default, + declared_size: None, + fields: vec![raw_field("value", RawNativeType::U32)], + is_union: false, + }; + let recursive = RawNativeLayoutSet { + recursive: true, + variants: vec![variant.clone()], + }; + let error = map_native_struct(&mut ComModel::default(), "Test", "Recursive", &recursive) + .unwrap_err() + .to_string(); + assert!(error.contains("recursive"), "{error}"); + + let missing = RawNativeLayoutSet { + recursive: false, + variants: vec![variant], + }; + let error = compute_native_layout(&mut ComModel::default(), &missing, Architecture::X86) + .unwrap_err() + .to_string(); + assert!(error.contains("missing X86"), "{error}"); + } + + #[test] + fn every_live_codegen_interface_maps_to_semantic_contracts() { + let Some(winmd) = win32_winmd() else { + return; + }; + for (namespace, name) in [ + ("Windows.Win32.UI.Shell", "ITaskbarList4"), + ("Windows.Win32.UI.Shell", "IDataTransferManagerInterop"), + ("Windows.Win32.UI.Shell", "IFileOperation"), + ("Windows.Win32.UI.Shell", "IFileOpenDialog"), + ("Windows.Win32.System.Com", "IPersistFile"), + ( + "Windows.Win32.System.WinRT", + "ISystemMediaTransportControlsInterop", + ), + ("Windows.Win32.Graphics.Imaging", "IWICImagingFactory"), + ] { + let interface = + crate::com_metadata::parse_com_interface(&winmd, namespace, name).unwrap(); + map_interface(&interface) + .unwrap_or_else(|error| panic!("{namespace}.{name} failed to map: {error}")); + } + } + + #[test] + fn automation_bstr_contracts_follow_metadata_direction_and_ownership() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Web.InternetExplorer", + "ITargetNotify2", + ) + .unwrap(); + let semantic = map_interface(&interface).unwrap(); + let method = semantic + .methods() + .iter() + .find(|method| method.name() == "GetOptionString") + .unwrap(); + + let input_interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.TaskScheduler", + "IExecAction2", + ) + .unwrap(); + let input_semantic = map_interface(&input_interface).unwrap(); + let input = input_semantic + .methods() + .iter() + .flat_map(ComMethodContract::params) + .find(|param| { + param.direction() == Direction::In + && matches!( + input_semantic + .type_definition(param.abi_type()) + .unwrap() + .abi(), + ComAbiType::Bstr + ) + }) + .unwrap(); + assert_eq!(input.ownership(), &ComOwnership::Borrowed); + assert_eq!(input.cleanup(), &Cleanup::None); + + let replacement = method + .params() + .iter() + .find(|param| param.direction() == Direction::InOut) + .unwrap(); + assert_eq!(replacement.ownership(), &ComOwnership::BstrReplaced); + assert_eq!(replacement.cleanup(), &Cleanup::SysFreeString); + assert_eq!(replacement.nullability(), Nullability::Required); + } + + #[test] + fn documented_optional_bstr_outputs_override_incorrect_in_out_metadata() { + let Some(winmd) = win32_winmd() else { + return; + }; + for (namespace, interface_name, method_name, parameter_names) in [ + ( + "Windows.Win32.Media.PictureAcquisition", + "IPhotoAcquireDeviceSelectionDialog", + "DoModal", + &["pbstrDeviceId"][..], + ), + ( + "Windows.Win32.Storage.Imapi", + "IDiscRecorder", + "GetDisplayNames", + &["pbstrVendorID", "pbstrProductID", "pbstrRevision"][..], + ), + ] { + let interface = + crate::com_metadata::parse_com_interface(&winmd, namespace, interface_name) + .unwrap(); + let semantic = map_interface(&interface).unwrap_or_else(|error| { + panic!("{namespace}.{interface_name} failed to map: {error}") + }); + let method = semantic + .methods() + .iter() + .find(|method| method.name() == method_name) + .unwrap(); + for parameter_name in parameter_names { + let parameter = method + .params() + .iter() + .find(|parameter| parameter.name() == *parameter_name) + .unwrap(); + assert_eq!(parameter.direction(), Direction::Out); + assert_eq!(parameter.ownership(), &ComOwnership::BstrOwned); + assert_eq!(parameter.cleanup(), &Cleanup::SysFreeString); + } + } + } + + #[test] + fn inherited_bstr_replacement_contracts_are_preserved() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.TaskScheduler", + "IExecAction2", + ) + .unwrap(); + let inherited = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| { + method.vtable_index < interface.own_methods_start + && method.params.iter().any(|parameter| { + parameter.direction == RawParamDirection::InOut + && parameter.typ.pointer_depth == 1 + && is_raw_named_type(¶meter.typ, "Windows.Win32.Foundation", "BSTR") + }) + }) + .unwrap(); + let semantic = map_interface(&interface).unwrap(); + let method = semantic + .methods() + .iter() + .find(|method| method.vtable_slot() == inherited.vtable_index) + .unwrap(); + assert!(method.params().iter().any(|parameter| { + parameter.ownership() == &ComOwnership::BstrReplaced + && parameter.cleanup() == &Cleanup::SysFreeString + })); + } + + #[test] + fn bstr_arrays_map_while_double_pointers_and_unknown_cleanup_fail_closed() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IPMExtensionFileSavePickerInfo", + ) + .unwrap(); + let error = map_interface(&interface).unwrap_err().to_string(); + assert!(error.contains("unknown ownership"), "{error}"); + + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.RemoteDesktop", + "ITSGPolicyEngine", + ) + .unwrap(); + let semantic = map_interface(&interface).unwrap(); + let resource_names = semantic + .methods() + .iter() + .find(|method| method.name() == "AuthorizeResource") + .unwrap() + .params() + .iter() + .find(|parameter| parameter.name() == "resourceNames") + .unwrap(); + assert!(matches!( + semantic + .type_definition(resource_names.abi_type()) + .unwrap() + .abi(), + ComAbiType::CountedBuffer { + element_ownership: BufferElementOwnership::BstrOwned, + .. + } + )); + + let mut interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Web.InternetExplorer", + "ITargetNotify2", + ) + .unwrap(); + let parameter = interface + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .flat_map(|method| &mut method.params) + .find(|parameter| { + parameter.direction == RawParamDirection::InOut + && is_raw_named_type(¶meter.typ, "Windows.Win32.Foundation", "BSTR") + }) + .unwrap(); + parameter.free_with.as_mut().unwrap().function = "CustomBstrFree".into(); + let error = map_interface(&interface).unwrap_err().to_string(); + assert!(error.contains("transfers allocator ownership"), "{error}"); + } + + #[test] + fn every_live_coclass_associated_interface_maps() { + let Some(winmd) = win32_winmd() else { + return; + }; + for coclass_name in ["TaskbarList", "FileOperation", "FileOpenDialog"] { + let coclass = crate::com_metadata::parse_com_coclass( + &winmd, + "Windows.Win32.UI.Shell", + coclass_name, + ) + .unwrap() + .unwrap(); + for interface in &coclass.associated_interfaces { + map_interface(interface).unwrap_or_else(|error| { + panic!( + "{}.{} associated interface {} failed to map: {error}", + coclass.namespace, coclass.name, interface.interface.name + ) + }); + } + } + } + + #[test] + fn override_evidence_is_exact_and_cited() { + let Some(winmd) = win32_winmd() else { + return; + }; + let interface = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.Com", + "IPersistFile", + ) + .unwrap(); + let get_cur_file = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetCurFile") + .unwrap(); + let output = get_cur_file.params.last().unwrap(); + let free_with = output.free_with.as_ref().unwrap(); + + assert_eq!(free_with.function, "CoTaskMemFree"); + assert!(matches!( + free_with.evidence, + crate::com_metadata::RawEvidence::Override { citation, .. } + if citation.contains("ipersistfile-getcurfile") + )); + assert!(matches!( + get_cur_file.semantic_hresult, + Some(crate::com_metadata::RawEvidence::Override { citation, .. }) + if citation.contains("ipersistfile-getcurfile") + )); + } + + #[test] + fn in_out_count_is_both_capacity_and_actual_length() { + let count_param = ParamIndex::new(2); + assert_eq!( + map_count_relation( + RawParamDirection::Out, + RawParamDirection::InOut, + count_param, + None, + CountUnit::Elements, + false, + false, + ), + CountRelation::CallerCapacity { + capacity_param: count_param, + actual_length_param: Some(count_param), + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + } + ); + assert_eq!( + map_count_relation( + RawParamDirection::Out, + RawParamDirection::In, + ParamIndex::new(2), + Some(ParamIndex::new(3)), + CountUnit::Bytes, + false, + true, + ), + CountRelation::CallerCapacity { + capacity_param: ParamIndex::new(2), + actual_length_param: Some(ParamIndex::new(3)), + unit: CountUnit::Bytes, + sizing: BufferSizing::FixedCapacity, + } + ); + } + + #[test] + fn bind_opts_detection_depends_on_qualified_type_identity() { + let raw = RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.System.Com".into(), + name: "BIND_OPTS".into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Mutable, + }; + assert!(raw_contains_named_type( + &raw, + "Windows.Win32.System.Com", + "BIND_OPTS" + )); + assert!(!raw_contains_named_type(&raw, "Contoso.Com", "BIND_OPTS")); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs new file mode 100644 index 00000000..40f2dc24 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -0,0 +1,1648 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::ComModel; +use super::abi::{ + BufferElement, BufferElementOwnership, CallingConvention, ComAbiType, Constness, ScalarType, +}; +use super::contract::{BufferSizing, ComParamContract, CountRelation}; +use super::diagnostics::ModelError; +use super::ids::{ComGuid, ParamIndex, TypeId}; +use super::ownership::{Cleanup, ComOwnership}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum ComReturnKind { + HResult, + SemanticHResult, + EnumeratorNextHResult, + DirectValue(TypeId), + DirectPointer(TypeId), + Void, +} + +impl ComReturnKind { + fn abi_type(self) -> Option { + match self { + Self::DirectValue(abi_type) | Self::DirectPointer(abi_type) => Some(abi_type), + Self::HResult | Self::SemanticHResult | Self::EnumeratorNextHResult | Self::Void => { + None + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) enum ComMethodSpecialContract { + FixedCapacityBytes { guid_param: ParamIndex }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::codegen::com) struct DynamicIidContract { + iid_param_index: ParamIndex, + output_param_index: ParamIndex, +} + +impl DynamicIidContract { + pub(super) fn new( + iid_param_index: ParamIndex, + output_param_index: ParamIndex, + ) -> Result { + if iid_param_index == output_param_index { + return Err(ModelError::InvalidContract( + "dynamic-IID source and output parameters must be distinct".into(), + )); + } + Ok(Self { + iid_param_index, + output_param_index, + }) + } + + pub(in crate::codegen::com) const fn iid_param_index(self) -> ParamIndex { + self.iid_param_index + } + + pub(in crate::codegen::com) const fn output_param_index(self) -> ParamIndex { + self.output_param_index + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct ComMethodContract { + name: String, + interface_iid: ComGuid, + vtable_slot: usize, + calling_convention: CallingConvention, + params: Vec, + return_kind: ComReturnKind, + special_contract: Option, + dynamic_iid_contract: Option, +} + +impl ComMethodContract { + pub(super) fn new( + name: impl Into, + interface_iid: ComGuid, + vtable_slot: usize, + calling_convention: CallingConvention, + params: Vec, + return_kind: ComReturnKind, + ) -> Result { + let name = name.into(); + if name.trim().is_empty() { + return Err(ModelError::InvalidContract( + "method name must not be empty".into(), + )); + } + if interface_iid.is_zero() { + return Err(ModelError::InvalidContract( + "interface IID must not be zero".into(), + )); + } + if vtable_slot < 3 { + return Err(ModelError::InvalidContract(format!( + "COM method `{name}` cannot occupy reserved IUnknown slot {vtable_slot}" + ))); + } + for (index, param) in params.iter().enumerate() { + param.validate_param_references(ParamIndex::new(index), params.len())?; + } + validate_relationship_directions(¶ms)?; + Ok(Self { + name, + interface_iid, + vtable_slot, + calling_convention, + params, + return_kind, + special_contract: None, + dynamic_iid_contract: None, + }) + } + + pub(super) fn validate(&self, model: &ComModel) -> Result<(), ModelError> { + for param in &self.params { + (|| { + model.require_supported_type(param.abi_type())?; + let abi = model.types().get(param.abi_type())?.abi(); + let is_counted_buffer = matches!(abi, ComAbiType::CountedBuffer { .. }); + if is_counted_buffer != param.count().is_some() { + return Err(ModelError::InvalidContract( + "CountedBuffer ABI semantics require exactly one count relationship".into(), + )); + } + if param.direction().is_output() + && !matches!( + abi, + ComAbiType::Pointer { + constness: Constness::Mutable, + .. + } | ComAbiType::DataPointer { + constness: Constness::Mutable, + .. + } | ComAbiType::CountedBuffer { + constness: Constness::Mutable, + .. + } + ) + { + return Err(ModelError::InvalidContract(format!( + "[out] or [in, out] parameter `{}` requires writable native pointer indirection", + param.name() + ))); + } + if matches!( + abi, + ComAbiType::CountedBuffer { + element: BufferElement::Opaque(_), + .. + } + ) { + return Err(ModelError::Unsupported( + super::diagnostics::UnsupportedReason::UnknownLayout, + )); + } + if let ComAbiType::CountedBuffer { + element, + element_ownership, + pointer_depth, + constness, + .. + } = model.types().get(param.abi_type())?.abi() + { + match (element, element_ownership, param.count(), param.direction()) { + ( + BufferElement::StringPointer { .. }, + BufferElementOwnership::Borrowed, + Some(CountRelation::InputCount { .. }), + super::contract::Direction::In, + ) => {} + ( + BufferElement::Typed(_), + BufferElementOwnership::ComOwned + | BufferElementOwnership::BstrOwned + | BufferElementOwnership::VariantOwned, + Some(CountRelation::EnumeratorNext { .. }), + super::contract::Direction::Out, + ) => {} + ( + BufferElement::StringPointer { .. }, + BufferElementOwnership::CoTaskMemStringOwned, + Some(CountRelation::EnumeratorNext { .. }), + super::contract::Direction::Out, + ) => {} + ( + BufferElement::Typed(_), + BufferElementOwnership::ComOwned + | BufferElementOwnership::BstrOwned + | BufferElementOwnership::VariantOwned, + Some(CountRelation::InputCount { .. }), + super::contract::Direction::In, + ) => {} + ( + BufferElement::Typed(_), + BufferElementOwnership::ComOwned + | BufferElementOwnership::BstrOwned + | BufferElementOwnership::VariantOwned, + Some(CountRelation::CallerCapacity { .. }), + super::contract::Direction::Out, + ) => {} + (_, BufferElementOwnership::Plain, _, _) => {} + _ => { + return Err(ModelError::Unsupported( + super::diagnostics::UnsupportedReason::Other(format!( + "owned counted-buffer elements or unknown element ownership ({element_ownership:?}) require explicit initialized-range cleanup" + )), + )); + } + } + if let BufferElement::Typed(element) = element + && matches!(model.types().get(*element)?.abi(), ComAbiType::NativeStruct(_)) + && !matches!( + param.count(), + Some( + CountRelation::InputCount { .. } + | CountRelation::EnumeratorNext { .. } + ) + ) + { + return Err(ModelError::Unsupported( + super::diagnostics::UnsupportedReason::Other( + "native struct counted buffers currently support input contracts only" + .into(), + ), + )); + } + if let BufferElement::StringPointer { + pointer_depth, + constness: element_constness, + .. + } = element + && (pointer_depth.get() != 1 + || *element_constness == Constness::Unspecified) + { + return Err(ModelError::InvalidContract( + "string array elements require one pointer level with explicit constness" + .into(), + )); + } + match param.count().expect("counted buffer relation") { + CountRelation::InputCount { .. } => { + if pointer_depth.get() != 1 { + return Err(ModelError::InvalidContract( + "input counted buffers require an authoritative T* contract" + .into(), + )); + } + if !matches!( + (param.ownership(), param.cleanup()), + (ComOwnership::Borrowed, Cleanup::None) + ) { + return Err(ModelError::InvalidOwnership( + "input counted buffers must be borrowed".into(), + )); + } + } + CountRelation::CallerCapacity { .. } => { + if pointer_depth.get() != 1 || *constness != Constness::Mutable { + return Err(ModelError::InvalidContract( + "caller-owned output buffers require an authoritative mutable T* contract" + .into(), + )); + } + if !matches!( + (param.ownership(), param.cleanup()), + (ComOwnership::Borrowed, Cleanup::None) + ) { + return Err(ModelError::InvalidOwnership( + "caller-owned output buffers cannot transfer allocator ownership" + .into(), + )); + } + } + CountRelation::EnumeratorNext { .. } => { + if pointer_depth.get() != 1 || *constness != Constness::Mutable { + return Err(ModelError::InvalidContract( + "IEnum::Next values require an authoritative mutable T* contract" + .into(), + )); + } + if !matches!( + (param.ownership(), param.cleanup()), + (ComOwnership::Borrowed, Cleanup::None) + ) { + return Err(ModelError::InvalidOwnership( + "IEnum::Next transfers element ownership, not buffer ownership" + .into(), + )); + } + } + CountRelation::CalleeAllocated { .. } => { + if pointer_depth.get() != 2 || *constness != Constness::Mutable { + return Err(ModelError::InvalidContract( + "callee-allocated buffers require an authoritative mutable T** contract" + .into(), + )); + } + if !matches!( + (param.ownership(), param.cleanup()), + ( + ComOwnership::CoTaskMemOwned, + Cleanup::CoTaskMemFree + ) + ) { + return Err(ModelError::Unsupported( + super::diagnostics::UnsupportedReason::UnknownOwnership, + )); + } + if !matches!(element_ownership, BufferElementOwnership::Plain) { + return Err(ModelError::Unsupported( + super::diagnostics::UnsupportedReason::UnknownOwnership, + )); + } + } + } + if matches!(element, BufferElement::Typed(_)) { + for count_index in + count_param_indices(param.count().expect("counted buffer relation")) + { + require_integer_count_type( + model, + &self.params[count_index.index()], + )?; + } + } + } + if let Cleanup::Custom(cleanup_id) = param.cleanup() { + model.cleanups().get(*cleanup_id)?; + } + Ok(()) + })() + .map_err(|error: ModelError| error.context(param.name()))?; + } + validate_shared_count_groups(model, &self.params)?; + self.validate_enumerator_next(model)?; + self.validate_dynamic_iid(model)?; + if let Some(abi_type) = self.return_kind.abi_type() { + model.require_supported_type(abi_type)?; + let pointer_return = model + .types() + .get(abi_type)? + .abi() + .requires_pointer_return_convention(); + match self.return_kind { + ComReturnKind::DirectPointer(_) if !pointer_return => { + return Err(ModelError::InvalidContract(format!( + "{} direct pointer return uses a non-pointer ABI type", + self.name + ))); + } + ComReturnKind::DirectValue(_) if pointer_return => { + return Err(ModelError::InvalidContract(format!( + "{} direct value return uses a pointer-return ABI type", + self.name + ))); + } + _ => {} + } + } + Ok(()) + } + + pub(in crate::codegen::com) fn name(&self) -> &str { + &self.name + } + + pub(super) const fn interface_iid(&self) -> ComGuid { + self.interface_iid + } + + pub(in crate::codegen::com) const fn vtable_slot(&self) -> usize { + self.vtable_slot + } + + pub(super) const fn calling_convention(&self) -> CallingConvention { + self.calling_convention + } + + pub(in crate::codegen::com) fn params(&self) -> &[ComParamContract] { + &self.params + } + + pub(in crate::codegen::com) const fn return_kind(&self) -> ComReturnKind { + self.return_kind + } + + pub(in crate::codegen::com) const fn special_contract( + &self, + ) -> Option { + self.special_contract + } + + pub(in crate::codegen::com) const fn dynamic_iid_contract(&self) -> Option { + self.dynamic_iid_contract + } + + pub(super) fn with_special_contract( + mut self, + special_contract: ComMethodSpecialContract, + ) -> Self { + self.special_contract = Some(special_contract); + self + } + + pub(super) fn with_dynamic_iid_contract( + mut self, + contract: DynamicIidContract, + ) -> Result { + if contract.iid_param_index().index() >= self.params.len() + || contract.output_param_index().index() >= self.params.len() + { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID parameter indices are outside its {} parameters", + self.name, + self.params.len() + ))); + } + self.dynamic_iid_contract = Some(contract); + Ok(self) + } + + fn validate_dynamic_iid(&self, model: &ComModel) -> Result<(), ModelError> { + let Some(contract) = self.dynamic_iid_contract else { + return Ok(()); + }; + if self.return_kind != ComReturnKind::HResult { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID methods require an HRESULT return", + self.name + ))); + } + if self + .params + .iter() + .any(|param| param.direction() == super::contract::Direction::InOut) + { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID methods cannot contain [in, out] parameters", + self.name + ))); + } + + let iid_index = contract.iid_param_index().index(); + let output_index = contract.output_param_index().index(); + let iid = &self.params[iid_index]; + let output = &self.params[output_index]; + if iid.direction() != super::contract::Direction::In + || iid.optional() + || iid.nullability() != super::contract::Nullability::Required + || iid.count().is_some() + || !matches!( + (iid.ownership(), iid.cleanup()), + (ComOwnership::Borrowed, Cleanup::None) + ) + || !matches!(iid.name().to_ascii_lowercase().as_str(), "iid" | "riid") + { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID source `{}` must be one required borrowed iid/riid input", + self.name, + iid.name() + ))); + } + let iid_type = model.types().get(iid.abi_type())?.abi(); + let ComAbiType::Pointer { + pointee, + depth, + constness: Constness::Const, + } = iid_type + else { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID source `{}` must be a const GUID*", + self.name, + iid.name() + ))); + }; + if depth.get() != 1 || !matches!(model.types().get(*pointee)?.abi(), ComAbiType::Guid) { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID source `{}` must be a const GUID*", + self.name, + iid.name() + ))); + } + + if output.direction() != super::contract::Direction::Out + || output.optional() + || output.nullability() != super::contract::Nullability::Required + || output.count().is_some() + || !matches!( + (output.ownership(), output.cleanup()), + (ComOwnership::ComOwned, Cleanup::ComRelease) + ) + { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID output `{}` must be one required +1 COM output", + self.name, + output.name() + ))); + } + if !matches!( + model.types().get(output.abi_type())?.abi(), + ComAbiType::DataPointer { + pointee: super::abi::DataPointee::Opaque(_), + depth, + constness: Constness::Mutable, + } if depth.get() == 2 + ) { + return Err(ModelError::InvalidContract(format!( + "{} dynamic-IID output `{}` must be a mutable void**/Object**", + self.name, + output.name() + ))); + } + + for (index, param) in self.params.iter().enumerate() { + if index != iid_index + && matches!(param.name().to_ascii_lowercase().as_str(), "iid" | "riid") + && matches!( + model.types().get(param.abi_type())?.abi(), + ComAbiType::Pointer { pointee, .. } + if matches!(model.types().get(*pointee)?.abi(), ComAbiType::Guid) + ) + { + return Err(ModelError::InvalidContract(format!( + "{} has a competing IID parameter `{}`", + self.name, + param.name() + ))); + } + if index != output_index + && param.direction().is_output() + && matches!( + model.types().get(param.abi_type())?.abi(), + ComAbiType::DataPointer { + pointee: super::abi::DataPointee::Opaque(_), + depth, + .. + } if depth.get() == 2 + ) + { + return Err(ModelError::InvalidContract(format!( + "{} has a competing void**/Object** output `{}`", + self.name, + param.name() + ))); + } + } + Ok(()) + } + + fn validate_enumerator_next(&self, model: &ComModel) -> Result<(), ModelError> { + let relation = self.params.iter().enumerate().find_map(|(index, param)| { + matches!(param.count(), Some(CountRelation::EnumeratorNext { .. })) + .then_some((index, param)) + }); + let Some((values_index, values)) = relation else { + if self.return_kind == ComReturnKind::EnumeratorNextHResult { + return Err(ModelError::InvalidContract( + "EnumeratorNext HRESULT requires an EnumeratorNext values parameter".into(), + )); + } + return Ok(()); + }; + let CountRelation::EnumeratorNext { + capacity_param, + fetched_param, + fetched_optional_for_single, + } = values.count().expect("matched EnumeratorNext") + else { + unreachable!() + }; + if self.return_kind != ComReturnKind::EnumeratorNextHResult + || self.name != "Next" + || self.params.len() != 3 + || values_index != 1 + || capacity_param.index() != 0 + || fetched_param.index() != 2 + || values.direction() != super::contract::Direction::Out + { + return Err(ModelError::InvalidContract( + "EnumeratorNext is restricted to an exact proven IEnum*::Next ABI shape".into(), + )); + } + let capacity = &self.params[capacity_param.index()]; + let fetched = &self.params[fetched_param.index()]; + if capacity.direction() != super::contract::Direction::In + || fetched.direction() != super::contract::Direction::Out + || fetched.optional() != *fetched_optional_for_single + { + return Err(ModelError::InvalidContract( + "IEnum::Next capacity/fetched directions or optionality do not match the proven contract" + .into(), + )); + } + require_exact_u32(model, capacity)?; + require_exact_u32_pointer(model, fetched)?; + Ok(()) + } +} + +fn validate_relationship_directions(params: &[ComParamContract]) -> Result<(), ModelError> { + for param in params { + match param.count() { + Some(CountRelation::InputCount { + count_param, + actual_length_param, + .. + }) => { + require_input(params, *count_param, "count")?; + if let Some(actual_length_param) = actual_length_param { + let actual = ¶ms[actual_length_param.index()]; + let valid_direction = if actual_length_param == count_param { + actual.direction() == super::contract::Direction::InOut + } else { + actual.direction() == super::contract::Direction::Out + }; + if !valid_direction { + return Err(ModelError::InvalidContract(format!( + "actual-length parameter `{}` must be Out, or InOut only when it is the shared input-count/actual slot", + actual.name(), + ))); + } + } + } + Some(CountRelation::CalleeAllocated { count_param, .. }) => { + require_output(params, *count_param, "callee-allocated count")?; + } + Some(CountRelation::CallerCapacity { + capacity_param, + actual_length_param, + sizing, + .. + }) => { + require_input(params, *capacity_param, "capacity")?; + if let Some(actual_length_param) = actual_length_param { + let actual = ¶ms[actual_length_param.index()]; + let valid_direction = if actual_length_param == capacity_param { + actual.direction() == super::contract::Direction::InOut + } else { + actual.direction() == super::contract::Direction::Out + }; + if !valid_direction { + return Err(ModelError::InvalidContract(format!( + "actual-length parameter `{}` must be Out, or InOut only when it is the shared capacity/actual slot", + actual.name(), + ))); + } + } + if matches!(sizing, BufferSizing::TwoCall { max_retries: 0 }) { + return Err(ModelError::InvalidContract( + "two-call sizing requires at least one bounded retry".into(), + )); + } + } + Some(CountRelation::EnumeratorNext { + capacity_param, + fetched_param, + .. + }) => { + require_input(params, *capacity_param, "enumerator capacity")?; + require_output(params, *fetched_param, "enumerator fetched count")?; + } + None => {} + } + } + Ok(()) +} + +fn validate_shared_count_groups( + model: &ComModel, + params: &[ComParamContract], +) -> Result<(), ModelError> { + let mut owners = vec![Vec::new(); params.len()]; + for (buffer_index, param) in params.iter().enumerate() { + let Some(relation) = param.count() else { + continue; + }; + let mut local = std::collections::BTreeSet::new(); + for index in count_param_indices(relation) { + if local.insert(index.index()) { + owners[index.index()].push(buffer_index); + } + } + } + for (count_index, buffers) in owners.iter().enumerate() { + if buffers.len() <= 1 { + continue; + } + let shared_input_unit = buffers + .iter() + .map(|&buffer_index| { + let param = ¶ms[buffer_index]; + match (param.direction(), param.count()) { + ( + super::contract::Direction::In, + Some(CountRelation::InputCount { + count_param, + actual_length_param: None, + unit, + }), + ) if count_param.index() == count_index => Some(*unit), + _ => None, + } + }) + .collect::>>(); + if shared_input_unit.is_some_and(|units| { + units + .first() + .is_some_and(|first| units.iter().all(|unit| unit == first)) + }) { + continue; + } + let mut parallel_inputs = 0usize; + let mut parallel_outputs = 0usize; + let parallel = buffers.iter().all(|&buffer_index| { + let param = ¶ms[buffer_index]; + match (param.direction(), param.count()) { + ( + super::contract::Direction::In, + Some(CountRelation::InputCount { + count_param, + actual_length_param: None, + unit: super::contract::CountUnit::Elements, + }), + ) if count_param.index() == count_index => { + parallel_inputs += 1; + true + } + ( + super::contract::Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param, + actual_length_param: None, + unit: super::contract::CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + ) if capacity_param.index() == count_index => { + parallel_outputs += 1; + true + } + _ => false, + } + }); + if parallel && parallel_inputs != 0 && parallel_outputs != 0 { + continue; + } + if buffers.len() != 2 { + return Err(ModelError::InvalidContract(format!( + "count parameter {count_index} describes an ambiguous buffer group" + ))); + } + let mut string_input = false; + let mut scalar_output = false; + for &buffer_index in buffers { + let param = ¶ms[buffer_index]; + let ComAbiType::CountedBuffer { + element, + element_ownership, + pointer_depth, + constness, + } = model.types().get(param.abi_type())?.abi() + else { + return Err(ModelError::InvalidContract( + "shared count owner is not a counted buffer".into(), + )); + }; + match (param.direction(), param.count(), element, element_ownership) { + ( + super::contract::Direction::In, + Some(CountRelation::InputCount { + count_param, + actual_length_param: None, + unit: super::contract::CountUnit::Elements, + }), + BufferElement::StringPointer { .. }, + BufferElementOwnership::Borrowed, + ) if count_param.index() == count_index + && pointer_depth.get() == 1 + && !string_input => + { + string_input = true; + } + ( + super::contract::Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param, + actual_length_param: None, + unit: super::contract::CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + BufferElement::Typed(element), + BufferElementOwnership::Plain, + ) if capacity_param.index() == count_index + && pointer_depth.get() == 1 + && *constness == Constness::Mutable + && matches!( + model.types().get(*element)?.abi(), + ComAbiType::Scalar(_) | ComAbiType::Enum(_) + ) + && !scalar_output => + { + scalar_output = true; + } + _ => { + return Err(ModelError::InvalidContract(format!( + "count parameter {count_index} describes unrelated buffers" + ))); + } + } + } + if !(string_input && scalar_output) { + return Err(ModelError::InvalidContract(format!( + "count parameter {count_index} does not form one string-input/scalar-output group" + ))); + } + } + Ok(()) +} + +fn count_param_indices(relation: &CountRelation) -> impl Iterator { + let (first, second) = match relation { + CountRelation::InputCount { + count_param, + actual_length_param, + .. + } => (*count_param, *actual_length_param), + CountRelation::CallerCapacity { + capacity_param, + actual_length_param, + .. + } => (*capacity_param, *actual_length_param), + CountRelation::EnumeratorNext { + capacity_param, + fetched_param, + .. + } => (*capacity_param, Some(*fetched_param)), + CountRelation::CalleeAllocated { count_param, .. } => (*count_param, None), + }; + std::iter::once(first).chain(second) +} + +fn require_integer_count_type( + model: &ComModel, + param: &ComParamContract, +) -> Result<(), ModelError> { + let mut abi = model.types().get(param.abi_type())?.abi(); + if param.direction().is_output() + && let ComAbiType::Pointer { pointee, depth, .. } = abi + && depth.get() == 1 + { + abi = model.types().get(*pointee)?.abi(); + } + + if matches!( + abi, + ComAbiType::Scalar( + ScalarType::I8 + | ScalarType::U8 + | ScalarType::I16 + | ScalarType::U16 + | ScalarType::I32 + | ScalarType::U32 + | ScalarType::I64 + | ScalarType::U64 + | ScalarType::NativeIsize + | ScalarType::NativeUsize + ) + ) { + Ok(()) + } else { + Err(ModelError::InvalidContract(format!( + "count parameter `{}` must use an integer scalar ABI", + param.name() + ))) + } +} + +fn require_exact_u32(model: &ComModel, param: &ComParamContract) -> Result<(), ModelError> { + if matches!( + model.types().get(param.abi_type())?.abi(), + ComAbiType::Scalar(ScalarType::U32) + ) { + Ok(()) + } else { + Err(ModelError::InvalidContract(format!( + "IEnum::Next capacity `{}` must use ULONG/u32", + param.name() + ))) + } +} + +fn require_exact_u32_pointer(model: &ComModel, param: &ComParamContract) -> Result<(), ModelError> { + let ComAbiType::Pointer { + pointee, + depth, + constness, + } = model.types().get(param.abi_type())?.abi() + else { + return Err(ModelError::InvalidContract(format!( + "IEnum::Next fetched count `{}` must use ULONG*", + param.name() + ))); + }; + if depth.get() == 1 + && *constness == Constness::Mutable + && matches!( + model.types().get(*pointee)?.abi(), + ComAbiType::Scalar(ScalarType::U32) + ) + { + Ok(()) + } else { + Err(ModelError::InvalidContract(format!( + "IEnum::Next fetched count `{}` must use mutable ULONG*", + param.name() + ))) + } +} + +fn require_input( + params: &[ComParamContract], + index: ParamIndex, + role: &str, +) -> Result<(), ModelError> { + let param = ¶ms[index.index()]; + if !param.direction().is_input() { + return Err(ModelError::InvalidContract(format!( + "{role} parameter `{}` must be an input", + param.name() + ))); + } + Ok(()) +} + +fn require_output( + params: &[ComParamContract], + index: ParamIndex, + role: &str, +) -> Result<(), ModelError> { + let param = ¶ms[index.index()]; + if !param.direction().is_output() { + return Err(ModelError::InvalidContract(format!( + "{role} parameter `{}` must be an output", + param.name() + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroU8; + + use super::*; + use crate::codegen::com::model::abi::{ + ComTypeDefinition, Constness, HandleKind, QualifiedName, ScalarType, + }; + use crate::codegen::com::model::contract::{CountUnit, Direction, Nullability}; + use crate::codegen::com::model::ownership::{Cleanup, ComOwnership}; + + fn param( + name: &str, + abi_type: TypeId, + direction: Direction, + count: Option, + ) -> ComParamContract { + ComParamContract::new( + name, + abi_type, + direction, + false, + Nullability::Required, + count, + ComOwnership::Borrowed, + Cleanup::None, + ) + .unwrap() + } + + #[test] + fn method_contract_validates_count_directions_and_types() { + let mut model = ComModel::default(); + let byte = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::U8), + )) + .unwrap(); + let buffer = model + .types_mut() + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Example", "BYTE_BUFFER").unwrap()), + None, + ComAbiType::CountedBuffer { + element: BufferElement::Typed(byte), + element_ownership: BufferElementOwnership::Plain, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + let count = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::U32), + )) + .unwrap(); + let method = ComMethodContract::new( + "Write", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer, + Direction::In, + Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Bytes, + }), + ), + param("count", count, Direction::In, None), + ], + ComReturnKind::HResult, + ) + .unwrap(); + + method.validate(&model).unwrap(); + assert_eq!(method.name(), "Write"); + assert_eq!(method.interface_iid(), ComGuid::from_bytes([1; 16])); + assert_eq!(method.vtable_slot(), 3); + assert_eq!(method.calling_convention(), CallingConvention::System); + assert_eq!(method.params().len(), 2); + assert_eq!(method.return_kind(), ComReturnKind::HResult); + } + + #[test] + fn direct_pointer_returns_require_pointer_semantics() { + let mut model = ComModel::default(); + let scalar = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::NativeUsize), + )) + .unwrap(); + let pointer = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: scalar, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let pointer_method = ComMethodContract::new( + "Alloc", + ComGuid::from_bytes([2; 16]), + 3, + CallingConvention::Stdcall, + vec![], + ComReturnKind::DirectPointer(pointer), + ) + .unwrap(); + pointer_method.validate(&model).unwrap(); + + let invalid = ComMethodContract::new( + "Invalid", + ComGuid::from_bytes([2; 16]), + 4, + CallingConvention::Stdcall, + vec![], + ComReturnKind::DirectPointer(scalar), + ) + .unwrap(); + assert!(invalid.validate(&model).is_err()); + + let hwnd = model + .types_mut() + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Windows.Win32.Foundation", "HWND").unwrap()), + None, + ComAbiType::Handle(HandleKind::new( + QualifiedName::new("Windows.Win32.Foundation", "HWND").unwrap(), + )), + )) + .unwrap(); + let handle_method = ComMethodContract::new( + "GetWindow", + ComGuid::from_bytes([2; 16]), + 5, + CallingConvention::Stdcall, + vec![], + ComReturnKind::DirectValue(hwnd), + ) + .unwrap(); + handle_method.validate(&model).unwrap(); + } + + #[test] + fn dynamic_iid_semantics_require_const_guid_and_owned_com_output() { + let mut model = ComModel::default(); + let guid = model + .types_mut() + .insert(ComTypeDefinition::new(None, None, ComAbiType::Guid)) + .unwrap(); + let guid_pointer = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: guid, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + let object_output = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::DataPointer { + pointee: super::super::abi::DataPointee::Opaque(None), + depth: NonZeroU8::new(2).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let iid = ComParamContract::new( + "riid", + guid_pointer, + Direction::In, + false, + Nullability::Required, + None, + ComOwnership::Borrowed, + Cleanup::None, + ) + .unwrap(); + let output = ComParamContract::new( + "object", + object_output, + Direction::Out, + false, + Nullability::Required, + None, + ComOwnership::ComOwned, + Cleanup::ComRelease, + ) + .unwrap(); + let contract = DynamicIidContract::new(ParamIndex::new(0), ParamIndex::new(1)).unwrap(); + let method = ComMethodContract::new( + "Resolve", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![iid.clone(), output], + ComReturnKind::HResult, + ) + .unwrap() + .with_dynamic_iid_contract(contract) + .unwrap(); + method.validate(&model).unwrap(); + + let borrowed_output = ComParamContract::new( + "object", + object_output, + Direction::Out, + false, + Nullability::Required, + None, + ComOwnership::Borrowed, + Cleanup::None, + ) + .unwrap(); + let borrowed = ComMethodContract::new( + "ResolveBorrowed", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![iid, borrowed_output], + ComReturnKind::HResult, + ) + .unwrap() + .with_dynamic_iid_contract(contract) + .unwrap(); + assert!(borrowed.validate(&model).is_err()); + } + + #[test] + fn counted_buffers_cannot_lose_their_count_contract() { + let mut model = ComModel::default(); + let byte = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::U8), + )) + .unwrap(); + let buffer = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::CountedBuffer { + element: BufferElement::Typed(byte), + element_ownership: BufferElementOwnership::Plain, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + let method = ComMethodContract::new( + "Invalid", + ComGuid::from_bytes([2; 16]), + 3, + CallingConvention::System, + vec![param("buffer", buffer, Direction::In, None)], + ComReturnKind::HResult, + ) + .unwrap(); + + assert!(method.validate(&model).is_err()); + } + + #[test] + fn shared_count_groups_accept_parallel_inputs_and_outputs_with_exact_relations() { + let mut model = ComModel::default(); + let count = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::U32), + )) + .unwrap(); + let output_element = model + .types_mut() + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Tests", "DISPID").unwrap()), + None, + ComAbiType::Scalar(ScalarType::I32), + )) + .unwrap(); + let string_array = model + .types_mut() + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Windows.Win32.Foundation", "PCWSTR").unwrap()), + None, + ComAbiType::CountedBuffer { + element: BufferElement::StringPointer { + encoding: super::super::abi::StringEncoding::Utf16, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + element_ownership: BufferElementOwnership::Borrowed, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + let output_array = model + .types_mut() + .insert(ComTypeDefinition::new( + Some(QualifiedName::new("Tests", "DISPID").unwrap()), + None, + ComAbiType::CountedBuffer { + element: BufferElement::Typed(output_element), + element_ownership: BufferElementOwnership::Plain, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let make_method = |input_type| { + ComMethodContract::new( + "Resolve", + ComGuid::from_bytes([4; 16]), + 3, + CallingConvention::System, + vec![ + param( + "names", + input_type, + Direction::In, + Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Elements, + }), + ), + param("count", count, Direction::In, None), + param( + "ids", + output_array, + Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + ), + ], + ComReturnKind::HResult, + ) + .unwrap() + }; + + make_method(string_array).validate(&model).unwrap(); + + let unrelated_input = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::CountedBuffer { + element: BufferElement::Typed(output_element), + element_ownership: BufferElementOwnership::Plain, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + make_method(unrelated_input).validate(&model).unwrap(); + + let owning_strings = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::CountedBuffer { + element: BufferElement::StringPointer { + encoding: super::super::abi::StringEncoding::Utf16, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + element_ownership: BufferElementOwnership::BstrOwned, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + assert!(make_method(owning_strings).validate(&model).is_err()); + + let pointer_element = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: output_element, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let pointer_output = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::CountedBuffer { + element: BufferElement::Typed(pointer_element), + element_ownership: BufferElementOwnership::Unknown, + pointer_depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let pointer_method = ComMethodContract::new( + "ResolvePointers", + ComGuid::from_bytes([4; 16]), + 4, + CallingConvention::System, + vec![ + param( + "names", + string_array, + Direction::In, + Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Elements, + }), + ), + param("count", count, Direction::In, None), + param( + "outputs", + pointer_output, + Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param: ParamIndex::new(1), + actual_length_param: None, + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + ), + ], + ComReturnKind::HResult, + ) + .unwrap(); + assert!(pointer_method.validate(&model).is_err()); + } + + #[test] + fn output_directions_require_writable_pointer_indirection() { + let mut model = ComModel::default(); + let scalar = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Scalar(ScalarType::U32), + )) + .unwrap(); + let writable_pointer = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: scalar, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Mutable, + }, + )) + .unwrap(); + let const_pointer = model + .types_mut() + .insert(ComTypeDefinition::new( + None, + None, + ComAbiType::Pointer { + pointee: scalar, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Const, + }, + )) + .unwrap(); + let method = |typ| { + ComMethodContract::new( + "GetValue", + ComGuid::from_bytes([3; 16]), + 3, + CallingConvention::System, + vec![param("value", typ, Direction::Out, None)], + ComReturnKind::HResult, + ) + .unwrap() + }; + + assert!(method(writable_pointer).validate(&model).is_ok()); + assert!(method(scalar).validate(&model).is_err()); + assert!(method(const_pointer).validate(&model).is_err()); + } + + #[test] + fn callee_allocated_buffer_counts_are_outputs() { + let buffer_type = TypeId::from_index(0).unwrap(); + let count_type = TypeId::from_index(1).unwrap(); + let make_method = |count_direction| { + ComMethodContract::new( + "Read", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer_type, + Direction::Out, + Some(CountRelation::CalleeAllocated { + count_param: ParamIndex::new(1), + unit: CountUnit::Elements, + }), + ), + param("count", count_type, count_direction, None), + ], + ComReturnKind::HResult, + ) + }; + + assert!(make_method(Direction::Out).is_ok()); + assert!(make_method(Direction::In).is_err()); + } + + #[test] + fn caller_capacity_actual_direction_depends_on_slot_sharing() { + let buffer_type = TypeId::from_index(0).unwrap(); + let count_type = TypeId::from_index(1).unwrap(); + let distinct = |actual_direction| { + ComMethodContract::new( + "Read", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer_type, + Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param: ParamIndex::new(1), + actual_length_param: Some(ParamIndex::new(2)), + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + ), + param("capacity", count_type, Direction::In, None), + param("actual", count_type, actual_direction, None), + ], + ComReturnKind::HResult, + ) + }; + assert!(distinct(Direction::Out).is_ok()); + assert!(distinct(Direction::InOut).is_err()); + + let shared = |count_direction| { + ComMethodContract::new( + "Read", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer_type, + Direction::Out, + Some(CountRelation::CallerCapacity { + capacity_param: ParamIndex::new(1), + actual_length_param: Some(ParamIndex::new(1)), + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }), + ), + param("capacityAndActual", count_type, count_direction, None), + ], + ComReturnKind::HResult, + ) + }; + assert!(shared(Direction::InOut).is_ok()); + assert!(shared(Direction::Out).is_err()); + } + + #[test] + fn input_count_actual_direction_depends_on_slot_sharing() { + let buffer_type = TypeId::from_index(0).unwrap(); + let count_type = TypeId::from_index(1).unwrap(); + let distinct = |actual_direction| { + ComMethodContract::new( + "Write", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer_type, + Direction::In, + Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: Some(ParamIndex::new(2)), + unit: CountUnit::Elements, + }), + ), + param("count", count_type, Direction::In, None), + param("actual", count_type, actual_direction, None), + ], + ComReturnKind::HResult, + ) + }; + assert!(distinct(Direction::Out).is_ok()); + assert!(distinct(Direction::InOut).is_err()); + + let shared = |count_direction| { + ComMethodContract::new( + "Write", + ComGuid::from_bytes([1; 16]), + 3, + CallingConvention::System, + vec![ + param( + "buffer", + buffer_type, + Direction::In, + Some(CountRelation::InputCount { + count_param: ParamIndex::new(1), + actual_length_param: Some(ParamIndex::new(1)), + unit: CountUnit::Elements, + }), + ), + param("countAndActual", count_type, count_direction, None), + ], + ComReturnKind::HResult, + ) + }; + assert!(shared(Direction::InOut).is_ok()); + assert!(shared(Direction::Out).is_err()); + } + + #[test] + fn iunknown_slots_and_zero_iids_are_rejected() { + assert!( + ComMethodContract::new( + "Reserved", + ComGuid::from_bytes([1; 16]), + 2, + CallingConvention::System, + vec![], + ComReturnKind::Void, + ) + .is_err() + ); + assert!( + ComMethodContract::new( + "NoIdentity", + ComGuid::ZERO, + 3, + CallingConvention::System, + vec![], + ComReturnKind::SemanticHResult, + ) + .is_err() + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs new file mode 100644 index 00000000..bbebc171 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/mod.rs @@ -0,0 +1,390 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Classic COM ABI semantics. +//! +//! This model is independent from both WinRT metadata and language +//! projections. Metadata adapters must fully describe a contract here before +//! it can be lowered to a native call or rendered for JavaScript. + +// The closed model intentionally includes categories that later rewrite +// phases will wire into production one at a time. +#![allow(dead_code)] + +pub(super) mod abi; +pub(super) mod contract; +pub(super) mod diagnostics; +pub(super) mod ids; +pub(super) mod layout; +mod metadata; +pub(super) mod method; +pub(super) mod ownership; + +pub(super) use metadata::SemanticComInterface; + +use std::collections::HashSet; + +use abi::{ComAbiType, ComTypeTable, Constness, EnumTable, FunctionReturn, SignatureTable}; +use diagnostics::{ModelError, UnsupportedReason}; +use ids::TypeId; +use layout::{Architecture, LayoutKind, LayoutTable}; +use ownership::CleanupTable; + +pub(super) struct ValidatedComInterface<'a> { + meta: &'a crate::com_metadata::ComInterfaceMeta, + semantic: metadata::SemanticComInterface, +} + +impl<'a> ValidatedComInterface<'a> { + pub(super) const fn metadata(&self) -> &'a crate::com_metadata::ComInterfaceMeta { + self.meta + } + + pub(super) const fn semantic(&self) -> &metadata::SemanticComInterface { + &self.semantic + } +} + +pub(super) struct ValidatedComCoclass<'a> { + meta: &'a crate::com_metadata::ComCoclassMeta, + clsid: ids::ComGuid, +} + +impl<'a> ValidatedComCoclass<'a> { + pub(super) const fn metadata(&self) -> &'a crate::com_metadata::ComCoclassMeta { + self.meta + } + + pub(super) const fn clsid(&self) -> ids::ComGuid { + self.clsid + } +} + +pub(super) fn validate_coclass( + meta: &crate::com_metadata::ComCoclassMeta, +) -> Result, String> { + let clsid = ids::ComGuid::parse(&meta.clsid).map_err(|error| error.to_string())?; + if clsid.is_zero() { + return Err(format!("{}.{} has a zero CLSID", meta.namespace, meta.name)); + } + Ok(ValidatedComCoclass { meta, clsid }) +} + +pub(super) fn validate_interface( + meta: &crate::com_metadata::ComInterfaceMeta, +) -> Result, String> { + let semantic = metadata::map_interface(meta).map_err(|error| error.to_string())?; + Ok(ValidatedComInterface { meta, semantic }) +} + +#[derive(Debug, Default)] +struct ComModel { + types: ComTypeTable, + layouts: LayoutTable, + enums: EnumTable, + signatures: SignatureTable, + cleanups: CleanupTable, +} + +impl ComModel { + const fn types(&self) -> &ComTypeTable { + &self.types + } + + const fn types_mut(&mut self) -> &mut ComTypeTable { + &mut self.types + } + + const fn layouts_mut(&mut self) -> &mut LayoutTable { + &mut self.layouts + } + + const fn enums_mut(&mut self) -> &mut EnumTable { + &mut self.enums + } + + const fn signatures_mut(&mut self) -> &mut SignatureTable { + &mut self.signatures + } + + const fn cleanups(&self) -> &CleanupTable { + &self.cleanups + } + + const fn cleanups_mut(&mut self) -> &mut CleanupTable { + &mut self.cleanups + } + + fn validate_complete(&self) -> Result<(), ModelError> { + self.types.validate_complete()?; + self.layouts.validate_complete()?; + self.signatures.validate_complete()?; + for id in self.types.ids() { + self.require_supported_type(id)?; + } + Ok(()) + } + + fn require_supported_type(&self, root: TypeId) -> Result<(), ModelError> { + self.validate_underlying_chain(root)?; + let mut visited = HashSet::new(); + self.validate_type_graph(root, &mut visited) + } + + fn validate_underlying_chain(&self, root: TypeId) -> Result<(), ModelError> { + let mut current = Some(root); + let mut visited = HashSet::new(); + while let Some(id) = current { + if !visited.insert(id) { + return Err(ModelError::InvalidContract(format!( + "COM type {} has a cyclic underlying-type chain", + root.index() + ))); + } + current = self.types.get(id)?.underlying(); + } + Ok(()) + } + + fn validate_type_graph( + &self, + id: TypeId, + visited: &mut HashSet, + ) -> Result<(), ModelError> { + if !visited.insert(id) { + return Ok(()); + } + let definition = self.types.get(id)?; + match definition.abi() { + ComAbiType::Unknown(reason) => { + return Err(ModelError::Unsupported(reason.clone())); + } + ComAbiType::Pointer { + constness: Constness::Unspecified, + .. + } + | ComAbiType::DataPointer { + constness: Constness::Unspecified, + .. + } + | ComAbiType::StringPointer { + constness: Constness::Unspecified, + .. + } + | ComAbiType::CountedBuffer { + constness: Constness::Unspecified, + .. + } => { + return Err(ModelError::Unsupported( + UnsupportedReason::UnknownPointerMeaning, + )); + } + ComAbiType::ComInterface { iid } if iid.is_zero() => { + return Err(ModelError::Unsupported( + UnsupportedReason::MissingInterfaceIid, + )); + } + ComAbiType::SafeArray { element: None } => { + return Err(ModelError::Unsupported( + UnsupportedReason::UnsupportedSafeArrayElement, + )); + } + ComAbiType::Enum(enum_id) => { + self.enums.get(*enum_id)?; + } + ComAbiType::NativeStruct(layout_id) => { + let layouts = self.layouts.get(*layout_id)?; + for architecture in Architecture::ALL { + let layout = layouts.get(architecture); + if !matches!(layout.kind(), LayoutKind::Struct(_)) { + return Err(ModelError::InvalidLayout(format!( + "COM struct type {} references a union layout", + id.index() + ))); + } + for field in layout.fields() { + self.validate_type_graph(field.abi_type(), visited)?; + } + } + } + ComAbiType::NativeUnion(layout_id) => { + let layouts = self.layouts.get(*layout_id)?; + for architecture in Architecture::ALL { + let layout = layouts.get(architecture); + if layout.kind() != LayoutKind::Union { + return Err(ModelError::InvalidLayout(format!( + "COM union type {} references a struct layout", + id.index() + ))); + } + for field in layout.fields() { + self.validate_type_graph(field.abi_type(), visited)?; + } + } + } + ComAbiType::FunctionPointer(signature_id) => { + let signature = self.signatures.get(*signature_id)?; + for param in signature.params() { + self.validate_type_graph(*param, visited)?; + } + if let Some(return_type) = signature.return_kind().abi_type() { + self.validate_type_graph(return_type, visited)?; + let pointer_return = self + .types + .get(return_type)? + .abi() + .requires_pointer_return_convention(); + match signature.return_kind() { + FunctionReturn::Pointer(_) if !pointer_return => { + return Err(ModelError::InvalidContract( + "function pointer uses a non-pointer direct return".into(), + )); + } + FunctionReturn::Value(_) if pointer_return => { + return Err(ModelError::InvalidContract( + "function pointer uses a pointer ABI as a direct value".into(), + )); + } + _ => {} + } + } + } + _ => {} + } + for referenced in definition.referenced_types() { + self.validate_type_graph(referenced, visited)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroU8; + + use super::*; + use abi::{ + CallingConvention, ComEnumDefinition, ComTypeDefinition, FunctionSignature, QualifiedName, + ScalarType, + }; + use ids::{ComGuid, EnumId, LayoutId, SignatureId}; + + fn unnamed(abi: ComAbiType) -> ComTypeDefinition { + ComTypeDefinition::new(None, None, abi) + } + + #[test] + fn unresolved_cross_table_ids_fail_closed() { + let mut enum_model = ComModel::default(); + let enum_type = enum_model + .types_mut() + .insert(unnamed(ComAbiType::Enum(EnumId::from_index(0).unwrap()))) + .unwrap(); + assert!(matches!( + enum_model.require_supported_type(enum_type), + Err(ModelError::UnknownId { kind: "enum", .. }) + )); + + let mut layout_model = ComModel::default(); + let struct_type = layout_model + .types_mut() + .insert(unnamed(ComAbiType::NativeStruct( + LayoutId::from_index(0).unwrap(), + ))) + .unwrap(); + assert!(matches!( + layout_model.require_supported_type(struct_type), + Err(ModelError::UnknownId { + kind: "native layout", + .. + }) + )); + + let mut signature_model = ComModel::default(); + let callback = signature_model + .types_mut() + .insert(unnamed(ComAbiType::FunctionPointer( + SignatureId::from_index(0).unwrap(), + ))) + .unwrap(); + assert!(matches!( + signature_model.require_supported_type(callback), + Err(ModelError::UnknownId { + kind: "function signature", + .. + }) + )); + } + + #[test] + fn complete_enum_and_function_pointer_graphs_validate() { + let mut model = ComModel::default(); + let u32_type = model + .types_mut() + .insert(unnamed(ComAbiType::Scalar(ScalarType::U32))) + .unwrap(); + let enum_id = model + .enums_mut() + .insert( + ComEnumDefinition::new( + QualifiedName::new("Example", "FLAGS").unwrap(), + ScalarType::U32, + ) + .unwrap(), + ) + .unwrap(); + let enum_type = model + .types_mut() + .insert(unnamed(ComAbiType::Enum(enum_id))) + .unwrap(); + let signature = model + .signatures_mut() + .insert(FunctionSignature::new( + CallingConvention::System, + vec![enum_type], + FunctionReturn::Value(u32_type), + )) + .unwrap(); + let callback = model + .types_mut() + .insert(unnamed(ComAbiType::FunctionPointer(signature))) + .unwrap(); + + model.validate_complete().unwrap(); + model.require_supported_type(callback).unwrap(); + } + + #[test] + fn incomplete_pointer_and_interface_facts_fail_closed() { + let mut model = ComModel::default(); + let byte = model + .types_mut() + .insert(unnamed(ComAbiType::Scalar(ScalarType::U8))) + .unwrap(); + let pointer = model + .types_mut() + .insert(unnamed(ComAbiType::Pointer { + pointee: byte, + depth: NonZeroU8::new(1).unwrap(), + constness: Constness::Unspecified, + })) + .unwrap(); + let interface = model + .types_mut() + .insert(unnamed(ComAbiType::ComInterface { iid: ComGuid::ZERO })) + .unwrap(); + + assert_eq!( + model.require_supported_type(pointer), + Err(ModelError::Unsupported( + UnsupportedReason::UnknownPointerMeaning + )) + ); + assert_eq!( + model.require_supported_type(interface), + Err(ModelError::Unsupported( + UnsupportedReason::MissingInterfaceIid + )) + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs new file mode 100644 index 00000000..9ee6103a --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::abi::QualifiedName; +use super::diagnostics::{ModelError, UnsupportedReason}; +use super::ids::CleanupId; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) struct HandleCleanup { + function: QualifiedName, +} + +impl HandleCleanup { + pub(super) const fn new(function: QualifiedName) -> Self { + Self { function } + } + + pub(super) const fn function(&self) -> &QualifiedName { + &self.function + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum ComOwnership { + Borrowed, + ComOwned, + CoTaskMemOwned, + BstrOwned, + BstrReplaced, + HStringOwned, + VariantOwned, + SafeArrayOwned, + PropVariantOwned, + ExcepInfoOwned, + LocalOwned, + HandleOwned(HandleCleanup), + CustomOwned(CleanupId), + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::codegen::com) enum Cleanup { + None, + ComRelease, + CoTaskMemFree, + SysFreeString, + WindowsDeleteString, + VariantClear, + SafeArrayDestroy, + PropVariantClear, + ExcepInfoClear, + LocalFree, + Handle(HandleCleanup), + Custom(CleanupId), + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct CustomCleanup { + function: QualifiedName, +} + +impl CustomCleanup { + pub(super) const fn new(function: QualifiedName) -> Self { + Self { function } + } + + pub(super) const fn function(&self) -> &QualifiedName { + &self.function + } +} + +#[derive(Debug, Default)] +pub(super) struct CleanupTable { + definitions: Vec, +} + +impl CleanupTable { + pub(super) fn insert(&mut self, definition: CustomCleanup) -> Result { + let id = CleanupId::from_index(self.definitions.len()) + .ok_or(ModelError::CapacityExceeded("custom cleanup"))?; + self.definitions.push(definition); + Ok(id) + } + + pub(super) fn get(&self, id: CleanupId) -> Result<&CustomCleanup, ModelError> { + self.definitions + .get(id.index()) + .ok_or(ModelError::UnknownId { + kind: "custom cleanup", + index: id.index(), + }) + } +} + +pub(super) fn validate_ownership_cleanup( + ownership: &ComOwnership, + cleanup: &Cleanup, +) -> Result<(), ModelError> { + let valid = match (ownership, cleanup) { + (ComOwnership::Borrowed, Cleanup::None) + | (ComOwnership::ComOwned, Cleanup::ComRelease) + | (ComOwnership::CoTaskMemOwned, Cleanup::CoTaskMemFree) + | (ComOwnership::BstrOwned, Cleanup::SysFreeString) + | (ComOwnership::BstrReplaced, Cleanup::SysFreeString) + | (ComOwnership::HStringOwned, Cleanup::WindowsDeleteString) + | (ComOwnership::VariantOwned, Cleanup::VariantClear) + | (ComOwnership::SafeArrayOwned, Cleanup::SafeArrayDestroy) + | (ComOwnership::PropVariantOwned, Cleanup::PropVariantClear) + | (ComOwnership::ExcepInfoOwned, Cleanup::ExcepInfoClear) + | (ComOwnership::LocalOwned, Cleanup::LocalFree) => true, + (ComOwnership::HandleOwned(expected), Cleanup::Handle(actual)) => expected == actual, + (ComOwnership::CustomOwned(expected), Cleanup::Custom(actual)) => expected == actual, + _ => false, + }; + if valid { + Ok(()) + } else if matches!(ownership, ComOwnership::Unknown) { + Err(ModelError::Unsupported(UnsupportedReason::UnknownOwnership)) + } else if matches!(cleanup, Cleanup::Unknown) { + Err(ModelError::Unsupported(UnsupportedReason::UnknownCleanup)) + } else { + Err(ModelError::InvalidOwnership(format!( + "{ownership:?} cannot use {cleanup:?}" + ))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allocator_pairs_are_exact() { + validate_ownership_cleanup(&ComOwnership::BstrOwned, &Cleanup::SysFreeString).unwrap(); + validate_ownership_cleanup(&ComOwnership::BstrReplaced, &Cleanup::SysFreeString).unwrap(); + assert!( + validate_ownership_cleanup(&ComOwnership::BstrOwned, &Cleanup::CoTaskMemFree).is_err() + ); + assert!(validate_ownership_cleanup(&ComOwnership::BstrReplaced, &Cleanup::None).is_err()); + assert!( + validate_ownership_cleanup(&ComOwnership::CoTaskMemOwned, &Cleanup::SysFreeString) + .is_err() + ); + } + + #[test] + fn handle_cleanup_requires_exact_identity() { + let close_handle = HandleCleanup::new( + QualifiedName::new("Windows.Win32.Foundation", "CloseHandle").unwrap(), + ); + let reg_close = HandleCleanup::new( + QualifiedName::new("Windows.Win32.System.Registry", "RegCloseKey").unwrap(), + ); + + validate_ownership_cleanup( + &ComOwnership::HandleOwned(close_handle.clone()), + &Cleanup::Handle(close_handle), + ) + .unwrap(); + assert!( + validate_ownership_cleanup( + &ComOwnership::HandleOwned(reg_close), + &Cleanup::Handle(HandleCleanup::new( + QualifiedName::new("Windows.Win32.Foundation", "CloseHandle").unwrap() + )), + ) + .is_err() + ); + } + + #[test] + fn unknown_ownership_fails_closed() { + assert_eq!( + validate_ownership_cleanup(&ComOwnership::Unknown, &Cleanup::Unknown), + Err(ModelError::Unsupported(UnsupportedReason::UnknownOwnership)) + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs new file mode 100644 index 00000000..2a1aec58 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_diagnostics.rs @@ -0,0 +1,937 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Legacy projection retained only to preserve established unsupported-shape +//! diagnostics and to support synthetic tests without raw COM facts. A +//! successful production projection never consumes this module's IR. + +use crate::com_metadata::{ComEnumValue, ComInterfaceMeta, MethodMeta, ParamDirection}; +use crate::types::TypeMeta; + +use super::super::ir::{ + ActivationPlan, ComParamDirection, ComReturnConvention, ComType, OverloadDispatch, + OverloadInfo, ProjectedComEnum, ProjectedComEnumMember, ProjectedComInterface, + ProjectedComMethod, ProjectedComMethodKind, ProjectedComParam, ProjectedComResult, + ProjectedEnumValue, ResultConversion, ResultSource, StringBufferPlan, StringEncoding, + UnsupportedComType, dispatch_shape, +}; +use super::super::javascript::naming::camel_case; +use super::interop::resolve_projected_default_iid; +use super::legacy_types::{ + is_scalar_in_out, is_supported_direct_return, project_enum_underlying, project_type, +}; + +fn project_legacy_interface( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result { + let interop_target = detect_interop_target(meta, winmd_paths)?; + let methods = meta + .interface + .methods + .iter() + .map(|method| project_method(meta, method, interop_target.as_ref())) + .collect::, _>>()?; + let methods = group_overloads(methods, &meta.interface.name)?; + let activation = if let Some((class_name, class_namespace, target_iid)) = interop_target { + ActivationPlan::WinRtFactory { + class_name, + class_namespace, + target_iid, + } + } else if let Some(clsid) = &meta.coclass_clsid { + ActivationPlan::Coclass { + clsid: clsid.clone(), + coclass_name: meta + .coclass_name + .clone() + .unwrap_or_else(|| "Coclass".into()), + } + } else { + ActivationPlan::None + }; + let referenced_enums = meta + .referenced_enums + .iter() + .map(|en| { + Ok(ProjectedComEnum { + namespace: en.namespace.clone(), + name: en.name.clone(), + underlying: project_enum_underlying(&en.underlying).map_err(|unsupported| { + unsupported_error(unsupported, "enum underlying type") + })?, + members: en + .members + .iter() + .map(|member| ProjectedComEnumMember { + name: member.name.clone(), + value: match member.value { + ComEnumValue::Signed(value) => ProjectedEnumValue::Signed(value), + ComEnumValue::Unsigned(value) => ProjectedEnumValue::Unsigned(value), + }, + }) + .collect(), + }) + }) + .collect::, String>>()?; + let projected = ProjectedComInterface { + name: meta.interface.name.clone(), + namespace: meta.interface.namespace.clone(), + iid: meta.interface.iid.clone(), + is_iunknown_rooted: meta.is_iunknown_rooted, + methods, + activation, + referenced_enums, + }; + Ok(projected) +} + +pub(super) fn diagnostic_preflight( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result<(), String> { + project_legacy_interface(meta, winmd_paths).map(drop) +} + +#[cfg(test)] +pub(in crate::codegen::com) fn project_com_interface_for_test( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result { + project_legacy_interface(meta, winmd_paths) +} + +/// Counts the JS-surfaced ("input" direction) parameters of a method — this +/// is the argument count a caller actually sees and the value overload +/// dispatch bucketing keys off of. +fn input_arity(method: &ProjectedComMethod) -> usize { + method + .params + .iter() + .filter(|param| param.direction.is_input()) + .count() +} + +/// Groups same-name COM methods (real, metadata-driven overloads — e.g. +/// `IDCompositionEffectGroup::SetOpacity(float)` vs +/// `SetOpacity(IDCompositionAnimation*)`) into a single public JS method with +/// a validated runtime dispatcher, per the classic-COM-ABI skill's mandate to +/// resolve overloads in the projected IR rather than with renderer +/// heuristics. +/// +/// Grouping never merges methods by *name* alone: it computes, for every +/// group with more than one member, whether the members are safely +/// distinguishable at a call site (same-arity siblings must have one +/// parameter position with mutually distinct, unambiguous JS dispatch +/// shapes). If they cannot be safely distinguished, this fails closed with a +/// diagnostic naming the interface, method, and reason, rather than silently +/// keeping only the last-declared overload (the pre-existing bug) or +/// guessing at a heuristic disambiguation. +fn group_overloads( + methods: Vec, + interface_name: &str, +) -> Result, String> { + // Preserve first-seen order of each public name so `.d.ts`/`.js` render + // overload signatures contiguously even if metadata interleaves them with + // other members. + let mut order: Vec = Vec::new(); + let mut groups: std::collections::HashMap> = + std::collections::HashMap::new(); + for (index, method) in methods.iter().enumerate() { + groups + .entry(method.camel_name.clone()) + .or_insert_with(|| { + order.push(method.camel_name.clone()); + Vec::new() + }) + .push(index); + } + + let mut overloads: Vec> = vec![None; methods.len()]; + for name in &order { + let indices = &groups[name]; + if indices.len() < 2 { + continue; + } + for &index in indices { + let method = &methods[index]; + if method.kind != ProjectedComMethodKind::Normal { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one is a synthesized/dynamic-IID method, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } + if method.string_buffer.is_some() { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one uses a caller-allocated string buffer, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } + } + + let mut arity_buckets: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for &index in indices { + arity_buckets + .entry(input_arity(&methods[index])) + .or_default() + .push(index); + } + + for (arity, bucket) in arity_buckets { + if bucket.len() == 1 { + overloads[bucket[0]] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), + dispatch: OverloadDispatch::Arity, + }); + continue; + } + let key_param_index = (0..arity).find(|&key_index| { + let mut seen = Vec::new(); + bucket.iter().all(|&index| { + let (_, param) = input_params_of(&methods[index])[key_index]; + match dispatch_shape(¶m.typ) { + Some(shape) if !seen.contains(&shape) => { + seen.push(shape); + true + } + _ => false, + } + }) + }); + let Some(key_param_index) = key_param_index else { + return Err(format!( + "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ + position has mutually distinguishable JS shapes (arity/type/category); \ + overload dispatch cannot be safely generated", + bucket.len() + )); + }; + for &index in &bucket { + let (_, param) = input_params_of(&methods[index])[key_param_index]; + let shape = + dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); + overloads[index] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[index].vtable_index), + dispatch: OverloadDispatch::ArityAndShape { + key_param_index, + shape, + }, + }); + } + } + } + + Ok(methods + .into_iter() + .zip(overloads) + .map(|(mut method, overload)| { + method.overload = overload; + method + }) + .collect()) +} + +fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> { + method + .params + .iter() + .enumerate() + .filter(|(_, param)| param.direction.is_input()) + .collect() +} + +fn project_method( + interface: &ComInterfaceMeta, + method: &MethodMeta, + interop_target: Option<&(String, String, String)>, +) -> Result { + let context = || format!("{}.{}", interface.interface.name, method.name); + let dynamic_iid = dynamic_iid_param_indices(method); + if dynamic_iid.is_some() && method.preserve_hresult { + return Err(format!( + "{}: semantic HRESULT dynamic-IID methods are not supported", + context() + )); + } + let kind = match (interop_target, method.name.as_str(), dynamic_iid) { + (Some((_, _, target_iid)), "GetForWindow", Some((iid_param_index, output_param_index))) => { + ProjectedComMethodKind::SynthesizedGetForWindow { + iid_param_index, + output_param_index, + target_iid: target_iid.clone(), + } + } + (_, _, Some((iid_param_index, output_param_index))) => { + ProjectedComMethodKind::CallerSuppliedDynamicIid { + iid_param_index, + output_param_index, + } + } + _ => ProjectedComMethodKind::Normal, + }; + + let mut params = Vec::with_capacity(method.params.len()); + for (index, param) in method.params.iter().enumerate() { + match param.direction { + ParamDirection::UnsupportedNativeArray { count_param_index } => { + let count = count_param_index + .map(|index| format!("parameter index {index}")) + .unwrap_or_else(|| "metadata-defined size".into()); + return Err(format!( + "{}: caller-sized native buffers are not supported (`{}` uses {count})", + context(), + param.name + )); + } + ParamDirection::OutFill => { + return Err(format!( + "{}: caller-allocated array outputs are not supported", + context() + )); + } + _ => {} + } + let typ = project_type(¶m.typ).map_err(|unsupported| { + unsupported_error( + unsupported, + &format!("{} parameter `{}`", context(), param.name), + ) + })?; + let cleanup = cleanup_for_param(method, index, &context())?; + if cleanup.is_some() + && dynamic_iid.is_some_and(|(_, output_param_index)| output_param_index == index) + { + return Err(format!( + "{}: dynamic-IID interface output cannot declare an allocator cleanup contract", + context() + )); + } + if cleanup.is_some() && param.direction == ParamDirection::InOut { + return Err(format!( + "{}: allocator ownership transfer for [in, out] parameter `{}` is not supported", + context(), + param.name + )); + } + if param.direction == ParamDirection::InOut && !is_scalar_in_out(&typ) { + return Err(format!( + "{}: unsupported [in, out] parameter `{}` of type {:?}", + context(), + param.name, + param.typ + )); + } + if param.direction == ParamDirection::Out + && typ == ComType::RawPointer + && dynamic_iid.is_none() + && cleanup != Some(CleanupKind::CoTaskMemFree) + && cleanup.is_none() + { + return Err(unsupported_error( + UnsupportedComType::UnknownOwnership { + type_name: "untyped pointer output".into(), + }, + &context(), + )); + } + if param.direction == ParamDirection::Out + && typ == ComType::Bstr + && cleanup != Some(CleanupKind::SysFreeString) + && cleanup.is_none() + { + return Err(unsupported_error( + UnsupportedComType::UnknownOwnership { + type_name: "BSTR output".into(), + }, + &context(), + )); + } + if matches!(param.direction, ParamDirection::Out | ParamDirection::InOut) + && matches!( + typ, + ComType::PointerAlias { + kind: super::super::ir::PointerAliasKind::StringPointer(_), + .. + } + ) + && cleanup != Some(CleanupKind::CoTaskMemFree) + && cleanup.is_none() + { + return Err(unsupported_error( + UnsupportedComType::UnknownOwnership { + type_name: format!("string pointer output `{}`", param.name), + }, + &context(), + )); + } + let direction = match param.direction { + ParamDirection::In => ComParamDirection::In, + ParamDirection::Out => ComParamDirection::Out, + ParamDirection::InOut => ComParamDirection::InOut, + ParamDirection::OutStringBuffer { .. } => ComParamDirection::OutStringBuffer, + ParamDirection::OutFill | ParamDirection::UnsupportedNativeArray { .. } => { + unreachable!("unsupported directions returned above") + } + }; + params.push(ProjectedComParam { + name: param.name.clone(), + typ, + direction, + surface_input: direction.is_input(), + surface_result: matches!(direction, ComParamDirection::Out | ComParamDirection::InOut), + nullable: false, + }); + } + validate_owned_outputs(method, ¶ms, &context())?; + + let return_convention = match &method.return_type { + None => ComReturnConvention::Void, + Some(typ) => { + let projected = project_type(typ).map_err(|unsupported| match unsupported { + UnsupportedComType::NativeStructLayout { .. } | UnsupportedComType::Unknown => { + unsupported_error( + UnsupportedComType::UnsupportedDirectReturn { + type_name: format!("{typ:?}"), + }, + &context(), + ) + } + unsupported => { + unsupported_error(unsupported, &format!("{} return value", context())) + } + })?; + if projected == ComType::HResult { + if method.preserve_hresult { + ComReturnConvention::SemanticHResult + } else { + ComReturnConvention::HResult + } + } else if is_supported_direct_return(&projected) { + ComReturnConvention::Direct(projected) + } else { + return Err(unsupported_error( + UnsupportedComType::UnsupportedDirectReturn { + type_name: format!("{typ:?}"), + }, + &context(), + )); + } + } + }; + if method.preserve_hresult && !matches!(return_convention, ComReturnConvention::SemanticHResult) + { + return Err(format!( + "{}: semantic HRESULT metadata requires an HRESULT return", + context() + )); + } + + let string_buffer = project_string_buffer(method)?; + if params + .iter() + .any(|param| param.direction == ComParamDirection::OutStringBuffer) + && string_buffer.is_none() + { + return Err(format!( + "{}: unsupported string-buffer encoding or count relationship", + context() + )); + } + let mut results = Vec::new(); + if let ComReturnConvention::SemanticHResult | ComReturnConvention::Direct(_) = + &return_convention + { + let typ = match &return_convention { + ComReturnConvention::SemanticHResult => ComType::HResult, + ComReturnConvention::Direct(typ) => typ.clone(), + ComReturnConvention::HResult + | ComReturnConvention::DispatchInvokeHResult + | ComReturnConvention::Void => unreachable!(), + }; + results.push(ProjectedComResult { + conversion: result_conversion(&typ, method, None, &kind), + typ, + source: ResultSource::DirectReturn, + }); + } + for (index, param) in params.iter().enumerate() { + if matches!( + param.direction, + ComParamDirection::Out | ComParamDirection::InOut + ) { + results.push(ProjectedComResult { + typ: param.typ.clone(), + source: ResultSource::Param(index), + conversion: result_conversion(¶m.typ, method, Some(index), &kind), + }); + } + } + + Ok(ProjectedComMethod { + name: method.name.clone(), + camel_name: camel_case(&method.name), + vtable_index: method.vtable_index, + params, + return_convention, + results, + string_buffer, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind, + doc: method.doc.clone(), + overload: None, + }) +} + +fn result_conversion( + typ: &ComType, + method: &MethodMeta, + param_index: Option, + kind: &ProjectedComMethodKind, +) -> ResultConversion { + if matches!( + kind, + ProjectedComMethodKind::CallerSuppliedDynamicIid { .. } + | ProjectedComMethodKind::SynthesizedGetForWindow { .. } + ) && param_index + == match kind { + ProjectedComMethodKind::CallerSuppliedDynamicIid { + output_param_index, .. + } + | ProjectedComMethodKind::SynthesizedGetForWindow { + output_param_index, .. + } => Some(*output_param_index), + _ => None, + } + { + return ResultConversion::DynamicIidAdoption; + } + if let Some(index) = param_index { + let cleanup = cleanup_for_param(method, index, &method.name) + .expect("cleanup contract was validated during projection"); + if cleanup == Some(CleanupKind::SysFreeString) && matches!(typ, ComType::Bstr) { + return ResultConversion::Bstr; + } + if cleanup == Some(CleanupKind::CoTaskMemFree) { + return match typ { + ComType::PointerAlias { name, .. } if name == "PWSTR" => { + ResultConversion::CoTaskMemString(StringEncoding::Wide) + } + ComType::PointerAlias { name, .. } if name == "PSTR" => { + ResultConversion::CoTaskMemString(StringEncoding::Ansi) + } + _ => ResultConversion::CoTaskMemData, + }; + } + } + match typ { + ComType::ManagedInterface { .. } => ResultConversion::ManagedCom, + ComType::HString => ResultConversion::HString, + _ => ResultConversion::Value, + } +} + +fn validate_owned_outputs( + method: &MethodMeta, + params: &[ProjectedComParam], + context: &str, +) -> Result<(), String> { + for (index, param) in params.iter().enumerate() { + let Some(cleanup) = cleanup_for_param(method, index, context)? else { + continue; + }; + if !matches!( + param.direction, + ComParamDirection::Out | ComParamDirection::InOut + ) { + return Err(format!( + "{context}: ownership metadata applies to non-output parameter `{}`", + param.name + )); + } + if cleanup == CleanupKind::SysFreeString { + if param.direction != ComParamDirection::Out || param.typ != ComType::Bstr { + return Err(format!( + "{context}: SysFreeString ownership requires a scalar Out BSTR" + )); + } + } else if cleanup == CleanupKind::CoTaskMemFree { + if param.direction != ComParamDirection::Out + || !matches!( + param.typ, + ComType::RawPointer + | ComType::PointerAlias { + kind: super::super::ir::PointerAliasKind::DataPointer + | super::super::ir::PointerAliasKind::StringPointer(_), + .. + } + ) + { + return Err(format!( + "{context}: CoTaskMemFree ownership requires an Out data or string pointer" + )); + } + } + } + for owned in &method.owned_outputs { + if owned.param_index >= params.len() { + return Err(format!( + "{context}: ownership metadata references missing parameter index {}", + owned.param_index + )); + } + } + Ok(()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CleanupKind { + SysFreeString, + CoTaskMemFree, +} + +fn cleanup_for_param( + method: &MethodMeta, + param_index: usize, + context: &str, +) -> Result, String> { + let contracts = method + .owned_outputs + .iter() + .filter(|owned| owned.param_index == param_index) + .map(|owned| owned.free_with.as_str()) + .collect::>(); + match contracts.as_slice() { + [] => Ok(None), + [contract] => parse_cleanup_contract(contract) + .map(Some) + .ok_or_else(|| format!("{context}: unsupported output cleanup contract `{contract}`")), + _ => Err(format!( + "{context}: output parameter index {param_index} has multiple cleanup contracts" + )), + } +} + +fn parse_cleanup_contract(contract: &str) -> Option { + if contract.is_empty() + || contract != contract.trim() + || contract + .chars() + .any(|character| character.is_whitespace() || matches!(character, ',' | ';')) + { + return None; + } + let identifier = contract + .rsplit_once(|character: char| matches!(character, '.' | '!' | ':')) + .map_or(contract, |(_, identifier)| identifier); + if identifier.is_empty() { + return None; + } + match identifier { + "SysFreeString" => Some(CleanupKind::SysFreeString), + "CoTaskMemFree" => Some(CleanupKind::CoTaskMemFree), + _ => None, + } +} + +fn project_string_buffer(method: &MethodMeta) -> Result, String> { + let buffers = method + .params + .iter() + .enumerate() + .filter_map(|(buffer_param_index, param)| { + let ParamDirection::OutStringBuffer { count_param_index } = param.direction else { + return None; + }; + Some((buffer_param_index, count_param_index, param)) + }) + .collect::>(); + if buffers.len() > 1 { + return Err(format!( + "{}: multiple caller-owned string buffers are not supported", + method.name + )); + } + let plan = + buffers + .into_iter() + .next() + .and_then(|(buffer_param_index, count_param_index, param)| { + let encoding = match pointer_alias_name(¶m.typ) { + Some("PWSTR") => StringEncoding::Wide, + Some("PSTR") => StringEncoding::Ansi, + _ => return None, + }; + method + .params + .get(count_param_index) + .filter(|count| count.direction == ParamDirection::In)?; + let optional_param_indices = (count_param_index..method.params.len()) + .filter(|index| string_buffer_param_is_optional(method, *index)) + .collect(); + Some(StringBufferPlan { + buffer_param_index, + count_param_index, + encoding, + optional_param_indices, + }) + }); + if plan + .as_ref() + .is_some_and(|plan| plan.encoding == StringEncoding::Ansi) + { + return Err(format!( + "{}: caller-owned ANSI output buffers are not yet decoded safely", + method.name + )); + } + Ok(plan) +} + +fn string_buffer_param_is_optional(method: &MethodMeta, param_index: usize) -> bool { + let Some(count_index) = method + .params + .iter() + .find_map(|param| match param.direction { + ParamDirection::OutStringBuffer { count_param_index } => Some(count_param_index), + _ => None, + }) + else { + return false; + }; + // The count parameter is optional (defaultable) only when no other required + // input parameter follows it — otherwise a caller could not omit it without + // also omitting later required arguments. This authoritative, metadata-driven + // count relationship replaces any name-based ("cch..."/"pfd"/find-data) shape + // guessing. + param_index == count_index + && method + .params + .iter() + .skip(param_index + 1) + .filter(|param| param.direction.is_input()) + .count() + == 0 +} + +fn pointer_alias_name(typ: &TypeMeta) -> Option<&str> { + match typ { + TypeMeta::Struct { name, .. } => Some(name), + _ => None, + } +} + +fn dynamic_iid_param_indices(method: &MethodMeta) -> Option<(usize, usize)> { + if !method + .return_type + .as_ref() + .is_some_and(|typ| matches!(project_type(typ), Ok(ComType::HResult))) + || method.params.len() < 2 + { + return None; + } + let output = method.params.last()?; + if output.direction != ParamDirection::Out || output.typ != TypeMeta::Object { + return None; + } + let iid = &method.params[method.params.len() - 2]; + let iid_name = iid.name.to_ascii_lowercase(); + if iid.direction != ParamDirection::In + || iid.typ != TypeMeta::Object + || !matches!(iid_name.as_str(), "iid" | "riid") + || method.params[..method.params.len() - 2] + .iter() + .any(|param| param.direction != ParamDirection::In) + { + return None; + } + Some((method.params.len() - 2, method.params.len() - 1)) +} + +fn detect_interop_target( + meta: &ComInterfaceMeta, + winmd_paths: &str, +) -> Result, String> { + if !meta.interface.name.ends_with("Interop") + || !meta.interface.methods.iter().any(|method| { + method.name == "GetForWindow" && dynamic_iid_param_indices(method).is_some() + }) + { + return Ok(None); + } + let stripped_i = meta + .interface + .name + .strip_prefix('I') + .unwrap_or(&meta.interface.name); + let class_name = stripped_i + .strip_suffix("Interop") + .unwrap_or(stripped_i) + .to_string(); + let Some((namespace, _, iid)) = resolve_projected_default_iid(winmd_paths, &class_name) else { + return Err(format!( + "Classic-COM interop generator: cannot resolve default IID for the projected \ + WinRT runtime class `{class_name}` (derived from `{}`). \ + Neither the winmds passed to the generator ({winmd_paths:?}) nor the newest installed \ + `C:\\Program Files (x86)\\Windows Kits\\10\\UnionMetadata\\\\Windows.winmd` \ + contains a WinRT runtime class of that name with a resolvable default interface. \ + Pass the correct Windows.winmd via --ref or install a recent Windows SDK.", + meta.interface.name + )); + }; + Ok(Some((class_name, namespace, iid))) +} + +fn unsupported_error(unsupported: UnsupportedComType, context: &str) -> String { + match unsupported { + UnsupportedComType::Array => format!( + "{context}: native arrays require an explicit count and element-ownership projection; \ + raw-pointer fallback is not allowed" + ), + UnsupportedComType::ParameterizedInterface { namespace, name } => format!( + "{context}: parameterized interface `{namespace}.{name}` requires a computed closed IID \ + and managed ownership projection; raw-pointer fallback is not allowed" + ), + UnsupportedComType::AsyncInterface => format!( + "{context}: async interface requires a computed closed IID and managed ownership \ + projection; raw-pointer fallback is not allowed" + ), + UnsupportedComType::Delegate { namespace, name } => format!( + "{context}: delegate `{namespace}.{name}` requires a managed callback projection; \ + raw-pointer fallback is not allowed" + ), + UnsupportedComType::NativeStructLayout { namespace, name } => { + format!("{context}: struct `{namespace}.{name}` requires native layout projection") + } + UnsupportedComType::UnknownPointerAlias { namespace, name } => format!( + "{context}: pointer-shaped typedef `{namespace}.{name}` has no explicit semantic \ + classification; raw-pointer fallback is not allowed" + ), + UnsupportedComType::UnresolvedInterface { namespace, name } => format!( + "{context}: interface `{namespace}.{name}` has no resolvable IID; \ + pass the metadata that defines it via --ref instead of projecting it as a raw pointer" + ), + UnsupportedComType::UnresolvedRuntimeClass { namespace, name } => format!( + "{context}: runtime class `{namespace}.{name}` has no resolvable default interface; \ + pass the metadata that defines it via --ref" + ), + UnsupportedComType::UnknownOwnership { type_name } => { + format!("{context}: {type_name} has no ownership projection") + } + UnsupportedComType::UnsupportedDirectReturn { type_name } => { + format!("{context}: unsupported direct native return type {type_name}") + } + UnsupportedComType::Unknown => { + format!("{context}: unsupported Classic-COM type") + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::com_metadata::{InterfaceMeta, MethodMeta, ParamMeta}; + + fn interface(method: MethodMeta) -> ComInterfaceMeta { + ComInterfaceMeta { + interface: InterfaceMeta { + name: "ITest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + methods: vec![method], + ..Default::default() + }, + base_offset: 3, + is_iunknown_rooted: true, + base_chain: vec!["IUnknown".into()], + coclass_clsid: None, + coclass_name: None, + own_methods_start: 3, + referenced_enums: Vec::new(), + raw_referenced_enums: None, + raw_methods: None, + } + } + + #[test] + fn unsupported_type_fails_during_projection() { + let method = MethodMeta { + name: "Bad".into(), + params: vec![ParamMeta { + name: "values".into(), + typ: TypeMeta::Array(Box::new(TypeMeta::I32)), + direction: ParamDirection::In, + }], + ..Default::default() + }; + assert!( + project_legacy_interface(&interface(method), "") + .unwrap_err() + .contains("raw-pointer fallback is not allowed") + ); + } + + #[test] + fn by_value_guid_is_not_dynamic_iid() { + let method = MethodMeta { + name: "Get".into(), + params: vec![ + ParamMeta { + name: "riid".into(), + typ: TypeMeta::Guid, + direction: ParamDirection::In, + }, + ParamMeta { + name: "result".into(), + typ: TypeMeta::Object, + direction: ParamDirection::Out, + }, + ], + return_type: Some(TypeMeta::Struct { + namespace: "Windows.Win32.Foundation".into(), + name: "HRESULT".into(), + fields: Vec::new(), + }), + ..Default::default() + }; + assert!( + project_legacy_interface(&interface(method), "") + .unwrap_err() + .contains("untyped pointer output") + ); + } + + #[test] + fn owned_output_without_a_known_cleanup_fails_before_rendering() { + let method = MethodMeta { + name: "GetName".into(), + params: vec![ParamMeta { + name: "name".into(), + typ: TypeMeta::Struct { + namespace: "Windows.Win32.Foundation".into(), + name: "BSTR".into(), + fields: Vec::new(), + }, + direction: ParamDirection::Out, + }], + return_type: Some(TypeMeta::Struct { + namespace: "Windows.Win32.Foundation".into(), + name: "HRESULT".into(), + fields: Vec::new(), + }), + ..Default::default() + }; + assert!( + project_legacy_interface(&interface(method), "") + .unwrap_err() + .contains("BSTR output has no ownership projection") + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/types.rs b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_types.rs similarity index 95% rename from tools/dynwinrt-codegen/src/codegen/com/project/types.rs rename to tools/dynwinrt-codegen/src/codegen/com/project/legacy_types.rs index 4226df10..427da382 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/legacy_types.rs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +//! TypeMeta compatibility mapping used only by diagnostic preflight and +//! synthetic renderer tests. + use crate::com_metadata::{is_native_isize, is_native_usize}; use crate::types::TypeMeta; @@ -71,8 +74,12 @@ pub(in crate::codegen::com) fn project_type(typ: &TypeMeta) -> Result Err(UnsupportedComType::AsyncInterface), TypeMeta::Array(_) => Err(UnsupportedComType::Array), TypeMeta::Enum { - name, underlying, .. + namespace, + name, + underlying, + .. } => Ok(ComType::Enum { + namespace: namespace.clone(), name: name.clone(), underlying: project_enum_underlying(underlying)?, }), @@ -95,12 +102,14 @@ pub(in crate::codegen::com) fn project_type(typ: &TypeMeta) -> Result Option } fn classify_pointer_alias(name: &str) -> Option { - if matches!( - name, - "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR" | "PWCHAR" | "PCWCHAR" | "LPWCH" | "LPCWCH" - ) { + if matches!(name, "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR") { Some(PointerAliasKind::StringPointer(StringEncoding::Wide)) - } else if matches!( - name, - "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR" | "LPCH" | "LPCCH" - ) { + } else if matches!(name, "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR") { Some(PointerAliasKind::StringPointer(StringEncoding::Ansi)) } else if matches!( name, @@ -312,6 +315,7 @@ mod tests { assert_eq!( project_type(&colorref), Ok(ComType::ScalarAlias { + namespace: "Windows.Win32.Foundation".into(), name: "COLORREF".into(), underlying: ComScalarRepr::Primitive(ComPrimitive::U32), }) @@ -328,6 +332,7 @@ mod tests { assert_eq!( project_type(&lparam), Ok(ComType::ScalarAlias { + namespace: "Windows.Win32.Foundation".into(), name: "LPARAM".into(), underlying: ComScalarRepr::NativeIsize, }) diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 17e82beb..93b6adf7 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -2,36 +2,100 @@ // Licensed under the MIT License. mod interop; -pub(super) mod types; +mod legacy_diagnostics; +mod legacy_types; -use crate::com_metadata::{ - ComCoclassMeta, ComEnumValue, ComInterfaceMeta, MethodMeta, ParamDirection, -}; -use crate::types::TypeMeta; +use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; use super::ir::{ - ActivationPlan, ComParamDirection, ComReturnConvention, ComType, OverloadDispatch, - OverloadInfo, ProjectedComCoclass, ProjectedComEnum, ProjectedComEnumMember, - ProjectedComInterface, ProjectedComMethod, ProjectedComMethodKind, ProjectedComParam, - ProjectedComResult, ProjectedEnumValue, ResultConversion, ResultSource, StringBufferPlan, - StringEncoding, UnsupportedComType, dispatch_shape, + ActivationPlan, BufferCountUnit as ProjectedBufferCountUnit, ComEnumUnderlying, + ComParamDirection, ComPrimitive, ComReturnConvention, ComScalarRepr, ComType, DispatchShape, + NativePodArchitectureLayout, NativePodField, NativePodFieldType, NativePodLayout, + NativePodScalar, NativeUnionArchitectureLayout, NativeUnionField, NativeUnionFieldType, + NativeUnionLayout, OverloadDispatch, OverloadInfo, PointerAliasKind, ProjectedComCoclass, + ProjectedComEnum, ProjectedComEnumMember, ProjectedComInterface, ProjectedComMethod, + ProjectedComMethodKind, ProjectedComParam, ProjectedComResult, ProjectedEnumValue, + ProjectedInterfaceRef, ResultConversion, ResultSource, SafeArrayElement, SharedCountPlan, + StringBufferPlan, StringEncoding, TypedBufferPlan, TypedBufferRelation, TypedBufferSizing, + dispatch_shape, }; use super::javascript::naming::camel_case; +use super::model::ValidatedComInterface; +use super::model::abi::{ + BufferElement, BufferElementOwnership, ComAbiType, ComEnumValue as SemanticEnumValue, + ComTypeDefinition, Constness, ScalarType, StringEncoding as SemanticStringEncoding, +}; +use super::model::contract::{ + BufferSizing, ComParamContract, CountRelation, CountUnit, Direction, Nullability, +}; +use super::model::layout::Architecture; +use super::model::method::{ComMethodContract, ComMethodSpecialContract, ComReturnKind}; +use super::model::ownership::{Cleanup, ComOwnership}; +use super::model::{self, SemanticComInterface}; use interop::resolve_projected_default_iid; -use types::{is_scalar_in_out, is_supported_direct_return, project_enum_underlying, project_type}; + +#[cfg(test)] +pub(super) use legacy_diagnostics::project_com_interface_for_test; +#[cfg(test)] +pub(super) use legacy_types::project_type as project_type_for_test; pub(super) fn project_com_interface( meta: &ComInterfaceMeta, winmd_paths: &str, ) -> Result { - let interop_target = detect_interop_target(meta, winmd_paths)?; - let methods = meta - .interface - .methods - .iter() - .map(|method| project_method(meta, method, interop_target.as_ref())) + let validated = model::validate_interface(meta) + .map_err(|error| diagnostic_compatibility(meta, winmd_paths, error))?; + project_validated_interface(&validated, winmd_paths) + .map_err(|error| diagnostic_compatibility(meta, winmd_paths, error)) +} + +pub(super) fn project_com_reference_interface( + meta: &ComInterfaceMeta, +) -> Result { + if meta.interface.iid.is_empty() { + return Err(format!( + "{}.{} has no exact IID for a managed array element wrapper", + meta.interface.namespace, meta.interface.name + )); + } + let projected = ProjectedComInterface { + name: meta.interface.name.clone(), + namespace: meta.interface.namespace.clone(), + iid: meta.interface.iid.clone(), + is_iunknown_rooted: meta.is_iunknown_rooted, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + }; + validate_projected_surface_names(&projected)?; + Ok(projected) +} + +fn project_validated_interface( + validated: &ValidatedComInterface<'_>, + winmd_paths: &str, +) -> Result { + let meta = validated.metadata(); + let semantic = validated.semantic(); + let interop_target = detect_interop_target(validated, winmd_paths)?; + + let mut method_indices = (0..semantic.methods().len()).collect::>(); + method_indices.sort_by_key(|index| semantic.methods()[*index].vtable_slot()); + let methods = method_indices + .into_iter() + .map(|index| { + project_method( + semantic, + &semantic.methods()[index], + meta.interface.methods[index].doc.clone(), + interop_target.as_ref(), + &meta.interface.namespace, + &meta.interface.name, + ) + }) .collect::, _>>()?; let methods = group_overloads(methods, &meta.interface.name)?; + let activation = if let Some((class_name, class_namespace, target_iid)) = interop_target { ActivationPlan::WinRtFactory { class_name, @@ -49,44 +113,192 @@ pub(super) fn project_com_interface( } else { ActivationPlan::None }; - let referenced_enums = meta - .referenced_enums - .iter() - .map(|en| { + + let referenced_enums = semantic + .referenced_enums() + .map(|definition| { Ok(ProjectedComEnum { - name: en.name.clone(), - underlying: project_enum_underlying(&en.underlying).map_err(|unsupported| { - unsupported_error(unsupported, "enum underlying type") - })?, - members: en - .members + namespace: definition.native_name().namespace().to_string(), + name: definition.native_name().name().to_string(), + underlying: project_enum_underlying(definition.underlying())?, + members: definition + .members() .iter() .map(|member| ProjectedComEnumMember { - name: member.name.clone(), - value: match member.value { - ComEnumValue::Signed(value) => ProjectedEnumValue::Signed(value), - ComEnumValue::Unsigned(value) => ProjectedEnumValue::Unsigned(value), + name: member.name().to_string(), + value: match member.value() { + SemanticEnumValue::Signed(value) => ProjectedEnumValue::Signed(*value), + SemanticEnumValue::Unsigned(value) => { + ProjectedEnumValue::Unsigned(*value) + } }, }) .collect(), }) }) .collect::, String>>()?; - Ok(ProjectedComInterface { + + let projected = ProjectedComInterface { name: meta.interface.name.clone(), namespace: meta.interface.namespace.clone(), - iid: meta.interface.iid.clone(), - is_iunknown_rooted: meta.is_iunknown_rooted, + iid: format_guid(semantic.iid().as_bytes()), + is_iunknown_rooted: semantic.is_iunknown_rooted(), methods, activation, referenced_enums, - }) + }; + validate_projected_surface_names(&projected)?; + Ok(projected) +} + +fn validate_projected_surface_names(meta: &ProjectedComInterface) -> Result<(), String> { + let mut names = std::collections::BTreeMap::::new(); + insert_surface_name( + &mut names, + &meta.name, + format!("interface {}.{}", meta.namespace, meta.name), + )?; + for definition in &meta.referenced_enums { + insert_surface_name( + &mut names, + &definition.name, + format!("enum {}.{}", definition.namespace, definition.name), + )?; + } + for method in &meta.methods { + for typ in method + .params + .iter() + .map(|param| ¶m.typ) + .chain(method.results.iter().map(|result| &result.typ)) + .chain(match &method.return_convention { + ComReturnConvention::Direct(typ) => Some(typ), + _ => None, + }) + { + match typ { + ComType::NativePod { layout } | ComType::NativePodPointer { layout } => { + insert_surface_name( + &mut names, + &layout.name, + format!("native POD {}.{}", layout.namespace, layout.name), + )?; + } + ComType::NativeUnionPointer { layout } => { + insert_surface_name( + &mut names, + &layout.name, + format!("native union {}.{}", layout.namespace, layout.name), + )?; + } + ComType::ScalarAlias { + namespace, name, .. + } => { + insert_surface_name( + &mut names, + name, + format!("scalar alias {namespace}.{name}"), + )?; + } + ComType::PointerAlias { + namespace, name, .. + } => { + insert_surface_name( + &mut names, + name, + format!("pointer alias {namespace}.{name}"), + )?; + } + ComType::Enum { + namespace, name, .. + } => { + insert_surface_name(&mut names, name, format!("enum {namespace}.{name}"))?; + } + ComType::TypedBuffer { element } => { + if let ComType::NativePod { layout } = element.as_ref() { + insert_surface_name( + &mut names, + &layout.name, + format!("native POD {}.{}", layout.namespace, layout.name), + )?; + } + } + ComType::OwningArray { .. } => {} + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Guid + | ComType::HString + | ComType::RawPointer + | ComType::Bstr + | ComType::Variant + | ComType::VariantByValue + | ComType::SafeArray { .. } + | ComType::PropVariant + | ComType::DispatchParams + | ComType::ExcepInfo + | ComType::ManagedInterface { .. } + | ComType::CoTaskMemWideString + | ComType::StringArray { .. } => {} + } + } + } + Ok(()) +} + +fn insert_surface_name( + names: &mut std::collections::BTreeMap, + name: &str, + identity: String, +) -> Result<(), String> { + if let Some(existing) = names.insert(name.to_string(), identity.clone()) + && existing != identity + { + return Err(format!( + "projected module identifier `{name}` is ambiguous between `{existing}` and `{identity}`" + )); + } + Ok(()) +} + +fn diagnostic_compatibility( + meta: &ComInterfaceMeta, + winmd_paths: &str, + semantic_error: String, +) -> String { + if semantic_error.contains("BIND_OPTS requires cbStruct") + || semantic_error.contains("Automation BYREF/InOut") + || semantic_error.contains("native union") + || semantic_error.contains("SAFEARRAY") + || semantic_error.contains("VARIANT") + || semantic_error.contains("DISPPARAMS") + || semantic_error.contains("EXCEPINFO") + || semantic_error.contains("IDispatch::Invoke") + || semantic_error.contains("optional COM outputs") + || semantic_error.contains("nested interface") + || semantic_error.contains("nested string/interface") + || semantic_error.contains("exact contract evidence") + || semantic_error.contains("AddRef'd interface pointer") + || semantic_error.contains("dynamic-IID") + || semantic_error.contains("competing IID") + || semantic_error.contains("competing void**") + { + return semantic_error; + } + match legacy_diagnostics::diagnostic_preflight(meta, winmd_paths) { + Ok(()) => semantic_error, + Err(legacy_error) => legacy_error, + } } pub(super) fn project_com_coclass( meta: &ComCoclassMeta, winmd_paths: &str, ) -> Result { + let validated_coclass = model::validate_coclass(meta)?; + let meta = validated_coclass.metadata(); let associated_interfaces = meta .associated_interfaces .iter() @@ -94,7 +306,11 @@ pub(super) fn project_com_coclass( .collect::, _>>()?; let primary_interface = associated_interfaces .iter() - .find(|interface| interface.iid == meta.primary_interface.interface.iid) + .find(|interface| { + interface + .iid + .eq_ignore_ascii_case(&meta.primary_interface.interface.iid) + }) .cloned() .ok_or_else(|| { format!( @@ -116,655 +332,2059 @@ pub(super) fn project_com_coclass( )); } } + validate_coclass_enum_files(&meta.namespace, &meta.name, &associated_interfaces)?; Ok(ProjectedComCoclass { name: meta.name.clone(), namespace: meta.namespace.clone(), - clsid: meta.clsid.clone(), + clsid: format_guid(validated_coclass.clsid().as_bytes()), primary_interface, associated_interfaces, }) } -/// Counts the JS-surfaced ("input" direction) parameters of a method — this -/// is the argument count a caller actually sees and the value overload -/// dispatch bucketing keys off of. -fn input_arity(method: &ProjectedComMethod) -> usize { - method - .params - .iter() - .filter(|param| param.direction.is_input()) - .count() -} - -/// Groups same-name COM methods (real, metadata-driven overloads — e.g. -/// `IDCompositionEffectGroup::SetOpacity(float)` vs -/// `SetOpacity(IDCompositionAnimation*)`) into a single public JS method with -/// a validated runtime dispatcher, per the classic-COM-ABI skill's mandate to -/// resolve overloads in the projected IR rather than with renderer -/// heuristics. -/// -/// Grouping never merges methods by *name* alone: it computes, for every -/// group with more than one member, whether the members are safely -/// distinguishable at a call site (same-arity siblings must have one -/// parameter position with mutually distinct, unambiguous JS dispatch -/// shapes). If they cannot be safely distinguished, this fails closed with a -/// diagnostic naming the interface, method, and reason, rather than silently -/// keeping only the last-declared overload (the pre-existing bug) or -/// guessing at a heuristic disambiguation. -fn group_overloads( - methods: Vec, - interface_name: &str, -) -> Result, String> { - // Preserve first-seen order of each public name so `.d.ts`/`.js` render - // overload signatures contiguously even if metadata interleaves them with - // other members. - let mut order: Vec = Vec::new(); - let mut groups: std::collections::HashMap> = - std::collections::HashMap::new(); - for (index, method) in methods.iter().enumerate() { - groups - .entry(method.camel_name.clone()) - .or_insert_with(|| { - order.push(method.camel_name.clone()); - Vec::new() - }) - .push(index); - } - - let mut overloads: Vec> = vec![None; methods.len()]; - for name in &order { - let indices = &groups[name]; - if indices.len() < 2 { - continue; - } - for &index in indices { - let method = &methods[index]; - if method.kind != ProjectedComMethodKind::Normal { - return Err(format!( - "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ - because at least one is a synthesized/dynamic-IID method, which is not a \ - safely dispatchable JS shape", - indices.len() - )); - } - if method.string_buffer.is_some() { - return Err(format!( - "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ - because at least one uses a caller-allocated string buffer, which is not a \ - safely dispatchable JS shape", - indices.len() - )); - } - } - - let mut arity_buckets: std::collections::BTreeMap> = - std::collections::BTreeMap::new(); - for &index in indices { - arity_buckets - .entry(input_arity(&methods[index])) - .or_default() - .push(index); - } - - for (arity, bucket) in arity_buckets { - if bucket.len() == 1 { - overloads[bucket[0]] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), - dispatch: OverloadDispatch::Arity, - }); - continue; - } - let key_param_index = (0..arity).find(|&key_index| { - let mut seen = Vec::new(); - bucket.iter().all(|&index| { - let (_, param) = input_params_of(&methods[index])[key_index]; - match dispatch_shape(¶m.typ) { - Some(shape) if !seen.contains(&shape) => { - seen.push(shape); - true - } - _ => false, - } - }) - }); - let Some(key_param_index) = key_param_index else { +fn validate_coclass_enum_files( + namespace: &str, + name: &str, + interfaces: &[ProjectedComInterface], +) -> Result<(), String> { + let mut enum_files = std::collections::BTreeMap::new(); + for interface in interfaces { + for definition in &interface.referenced_enums { + if let Some(existing) = enum_files.insert(definition.name.clone(), definition.clone()) + && existing != *definition + { return Err(format!( - "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ - position has mutually distinguishable JS shapes (arity/type/category); \ - overload dispatch cannot be safely generated", - bucket.len() + "{namespace}.{name} associated interfaces define conflicting `{}` enum files", + definition.name )); - }; - for &index in &bucket { - let (_, param) = input_params_of(&methods[index])[key_param_index]; - let shape = - dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); - overloads[index] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[index].vtable_index), - dispatch: OverloadDispatch::ArityAndShape { - key_param_index, - shape, - }, - }); } } } - - Ok(methods - .into_iter() - .zip(overloads) - .map(|(mut method, overload)| { - method.overload = overload; - method - }) - .collect()) -} - -fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> { - method - .params - .iter() - .enumerate() - .filter(|(_, param)| param.direction.is_input()) - .collect() + Ok(()) } fn project_method( - interface: &ComInterfaceMeta, - method: &MethodMeta, + semantic: &SemanticComInterface, + method: &ComMethodContract, + doc: Option, interop_target: Option<&(String, String, String)>, + interface_namespace: &str, + interface_name: &str, ) -> Result { - let context = || format!("{}.{}", interface.interface.name, method.name); - let dynamic_natural_count = dynamic_iid_natural_param_count(method); - if dynamic_natural_count.is_some() && method.preserve_hresult { - return Err(format!( - "{}: semantic HRESULT dynamic-IID methods are not supported", - context() - )); - } - let kind = match (interop_target, method.name.as_str(), dynamic_natural_count) { - (Some((_, _, target_iid)), "GetForWindow", Some(natural_param_count)) => { - ProjectedComMethodKind::SynthesizedGetForWindow { - natural_param_count, - target_iid: target_iid.clone(), - } - } - (_, _, Some(natural_param_count)) => ProjectedComMethodKind::CallerSuppliedDynamicIid { - natural_param_count, - }, - _ => ProjectedComMethodKind::Normal, - }; - - let mut params = Vec::with_capacity(method.params.len()); - for (index, param) in method.params.iter().enumerate() { - match param.direction { - ParamDirection::UnsupportedNativeArray { count_param_index } => { - let count = count_param_index - .map(|index| format!("parameter index {index}")) - .unwrap_or_else(|| "metadata-defined size".into()); - return Err(format!( - "{}: caller-sized native buffers are not supported (`{}` uses {count})", - context(), - param.name - )); - } - ParamDirection::OutFill => { - return Err(format!( - "{}: caller-allocated array outputs are not supported", - context() - )); - } - _ => {} - } - let typ = project_type(¶m.typ).map_err(|unsupported| { - unsupported_error( - unsupported, - &format!("{} parameter `{}`", context(), param.name), - ) - })?; - let cleanup = cleanup_for_param(method, index, &context())?; - if cleanup.is_some() && dynamic_natural_count.is_some() && index == method.params.len() - 1 - { + let context = || method.name().to_string(); + let dynamic_iid = method.dynamic_iid_contract(); + let mut kind = if let Some(ComMethodSpecialContract::FixedCapacityBytes { guid_param }) = + method.special_contract() + { + if dynamic_iid.is_some() { return Err(format!( - "{}: dynamic-IID interface output cannot declare an allocator cleanup contract", + "{}: fixed-capacity bytes cannot also use a dynamic IID output", context() )); } - if cleanup.is_some() && param.direction == ParamDirection::InOut { - return Err(format!( - "{}: allocator ownership transfer for [in, out] parameter `{}` is not supported", - context(), - param.name - )); + ProjectedComMethodKind::FixedCapacityBytes { + guid_param_index: guid_param.index(), } - if param.direction == ParamDirection::InOut && !is_scalar_in_out(&typ) { + } else { + project_dynamic_method_kind( + method.name(), + dynamic_iid.map(|contract| { + ( + contract.iid_param_index().index(), + contract.output_param_index().index(), + ) + }), + interop_target.map(|(_, _, target_iid)| target_iid.as_str()), + ) + }; + let is_idispatch_invoke = interface_namespace == "Windows.Win32.System.Com" + && interface_name == "IDispatch" + && method.name() == "Invoke"; + + let string_buffer = project_string_buffer(semantic, method)?; + let typed_buffers = project_typed_buffers(semantic, method)?; + let shared_counts = project_shared_counts(method, &typed_buffers)?; + let enumerator_buffers = typed_buffers + .iter() + .filter(|plan| matches!(plan.relation, TypedBufferRelation::EnumeratorNext { .. })) + .collect::>(); + if method.return_kind() == ComReturnKind::EnumeratorNextHResult { + let [plan] = enumerator_buffers.as_slice() else { return Err(format!( - "{}: unsupported [in, out] parameter `{}` of type {:?}", - context(), - param.name, - param.typ - )); - } - if param.direction == ParamDirection::Out - && typ == ComType::RawPointer - && dynamic_natural_count.is_none() - && cleanup != Some(CleanupKind::CoTaskMemFree) - && cleanup.is_none() - { - return Err(unsupported_error( - UnsupportedComType::UnknownOwnership { - type_name: "untyped pointer output".into(), - }, - &context(), + "{}: EnumeratorNext requires exactly one partial caller-output plan", + context() )); - } - if param.direction == ParamDirection::Out - && typ == ComType::Bstr - && cleanup != Some(CleanupKind::SysFreeString) - && cleanup.is_none() - { - return Err(unsupported_error( - UnsupportedComType::UnknownOwnership { - type_name: "BSTR output".into(), - }, - &context(), + }; + let TypedBufferRelation::EnumeratorNext { + capacity_param_index, + fetched_param_index, + fetched_optional_for_single, + } = plan.relation + else { + unreachable!() + }; + kind = ProjectedComMethodKind::EnumeratorNext { + buffer_param_index: plan.buffer_param_index, + capacity_param_index, + fetched_param_index, + fetched_optional_for_single, + interface: project_enumerator_interface_ref(semantic, method, plan.buffer_param_index)?, + }; + } else if !enumerator_buffers.is_empty() { + return Err(format!( + "{}: EnumeratorNext buffer requires its preserved HRESULT convention", + context() + )); + } else { + let owning_outputs = typed_buffers + .iter() + .filter(|plan| { + matches!( + plan.relation, + TypedBufferRelation::CallerOutput { + sizing: TypedBufferSizing::SingleCall, + .. + } + ) && is_owning_array_output_element(&plan.element) + && !shared_counts.iter().any(|group| { + matches!( + group, + SharedCountPlan::Parallel { + output_param_indices, + .. + } if output_param_indices.contains(&plan.buffer_param_index) + ) + }) + }) + .collect::>(); + if let [plan] = owning_outputs.as_slice() { + let TypedBufferRelation::CallerOutput { + capacity_param_index, + .. + } = plan.relation + else { + unreachable!() + }; + kind = ProjectedComMethodKind::OwningCallerOutput { + buffer_param_index: plan.buffer_param_index, + capacity_param_index, + }; + } else if owning_outputs.len() > 1 { + return Err(format!( + "{}: multiple owning caller-output arrays require an explicit compound projection", + context() )); } - if matches!(param.direction, ParamDirection::Out | ParamDirection::InOut) - && matches!( - typ, - ComType::PointerAlias { - kind: super::ir::PointerAliasKind::StringPointer(_), - .. + } + if matches!(kind, ProjectedComMethodKind::OwningCallerOutput { .. }) + && !shared_counts.is_empty() + { + return Err(format!( + "{}: owning caller-output arrays cannot be combined with independent shared buffer groups", + context() + )); + } + + validate_buffer_plan_composition(method.name(), string_buffer.as_ref(), &typed_buffers)?; + validate_dynamic_iid_buffers( + &context(), + dynamic_iid.is_some(), + string_buffer.as_ref(), + &typed_buffers, + )?; + + let mut params = Vec::with_capacity(method.params().len()); + for (index, param) in method.params().iter().enumerate() { + let typ = project_param_type(semantic, param)?; + let typed_buffer = typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == index); + let direction = if let Some(plan) = typed_buffer { + match plan.relation { + TypedBufferRelation::Input { .. } => ComParamDirection::InputBuffer, + TypedBufferRelation::CallerOutput { .. } + | TypedBufferRelation::EnumeratorNext { .. } => { + ComParamDirection::CallerOutputBuffer } - ) - && cleanup != Some(CleanupKind::CoTaskMemFree) - && cleanup.is_none() + TypedBufferRelation::CalleeAllocated { .. } => { + ComParamDirection::CalleeAllocatedBuffer + } + } + } else if string_buffer + .as_ref() + .is_some_and(|plan| plan.buffer_param_index == index) { - return Err(unsupported_error( - UnsupportedComType::UnknownOwnership { - type_name: format!("string pointer output `{}`", param.name), - }, - &context(), + ComParamDirection::OutStringBuffer + } else { + match param.direction() { + Direction::In => ComParamDirection::In, + Direction::Out + if param.optional() + && (is_idispatch_invoke + || matches!( + &kind, + ProjectedComMethodKind::EnumeratorNext { + fetched_param_index, + .. + } if *fetched_param_index == index + )) => + { + ComParamDirection::OptionalOut + } + Direction::Out => ComParamDirection::Out, + Direction::InOut => ComParamDirection::InOut, + } + }; + let mut surface_input = direction.is_input(); + let mut surface_result = matches!( + direction, + ComParamDirection::Out + | ComParamDirection::OptionalOut + | ComParamDirection::InOut + | ComParamDirection::CallerOutputBuffer + | ComParamDirection::CalleeAllocatedBuffer + ); + for plan in &typed_buffers { + match plan.relation { + TypedBufferRelation::Input { + count_param_index, .. + } if index == count_param_index => surface_input = false, + TypedBufferRelation::CallerOutput { + capacity_param_index, + actual_length_param_index, + sizing, + .. + } => { + if index == capacity_param_index { + surface_input = sizing == TypedBufferSizing::FixedCapacity + || matches!( + kind, + ProjectedComMethodKind::OwningCallerOutput { + capacity_param_index: owning_capacity, + .. + } if owning_capacity == index + ); + surface_result = false; + } + if actual_length_param_index == Some(index) { + let owning_capacity_actual = capacity_param_index == index + && matches!( + kind, + ProjectedComMethodKind::OwningCallerOutput { + capacity_param_index: owning_capacity, + .. + } if owning_capacity == index + ); + if !owning_capacity_actual { + surface_input = false; + } + surface_result = false; + } + } + TypedBufferRelation::EnumeratorNext { + capacity_param_index, + fetched_param_index, + .. + } => { + if index == capacity_param_index { + surface_input = true; + surface_result = false; + } + if index == fetched_param_index { + surface_input = false; + surface_result = false; + } + if typed_buffer.is_some() { + surface_input = false; + } + } + TypedBufferRelation::CalleeAllocated { + count_param_index, .. + } if index == count_param_index => { + surface_input = false; + surface_result = false; + } + TypedBufferRelation::Input { .. } | TypedBufferRelation::CalleeAllocated { .. } => { + } + } + } + if typed_buffer.is_some_and(|plan| { + matches!( + plan.relation, + TypedBufferRelation::CallerOutput { + sizing: TypedBufferSizing::FixedCapacity | TypedBufferSizing::TwoCall { .. }, + .. + } + ) + }) { + surface_input = false; + } + if matches!( + kind, + ProjectedComMethodKind::OwningCallerOutput { + buffer_param_index, + .. + } if buffer_param_index == index + ) { + surface_input = false; + } + if shared_counts.iter().any(|group| match group { + SharedCountPlan::StringInputScalarOutput { + scalar_output_param_index, + .. + } => *scalar_output_param_index == index, + SharedCountPlan::Parallel { + output_param_indices, + .. + } => output_param_indices.contains(&index), + }) { + surface_input = false; + } + if matches!( + &kind, + ProjectedComMethodKind::SynthesizedGetForWindow { + iid_param_index, + .. + } if *iid_param_index == index + ) { + surface_input = false; + } + if direction == ComParamDirection::InOut && !is_scalar_in_out(&typ) { + return Err(format!( + "{}: unsupported [in, out] parameter `{}`", + context(), + param.name() + )); + } + let nullable = param.nullability() == Nullability::Nullable + && (surface_input || (surface_result && matches!(typ, ComType::SafeArray { .. }))); + if nullable && !supports_nullable_projection(&typ) { + return Err(format!( + "{}: nullable parameter `{}` has no safe language/runtime lowering", + context(), + param.name() )); } params.push(ProjectedComParam { - name: param.name.clone(), + name: param.name().into(), typ, - direction: match param.direction { - ParamDirection::In => ComParamDirection::In, - ParamDirection::Out => ComParamDirection::Out, - ParamDirection::InOut => ComParamDirection::InOut, - ParamDirection::OutStringBuffer { .. } => ComParamDirection::OutStringBuffer, - ParamDirection::OutFill | ParamDirection::UnsupportedNativeArray { .. } => { - unreachable!("unsupported directions returned above") - } - }, + direction, + surface_input, + surface_result, + nullable, }); } - validate_owned_outputs(method, ¶ms, &context())?; + if let ProjectedComMethodKind::EnumeratorNext { + capacity_param_index, + .. + } = &kind + { + params[*capacity_param_index].name = "count".into(); + } + for plan in &typed_buffers { + if let TypedBufferRelation::CallerOutput { + capacity_param_index, + sizing: TypedBufferSizing::FixedCapacity, + .. + } = plan.relation + { + params[capacity_param_index].name = "capacity".into(); + } + } + if let ProjectedComMethodKind::OwningCallerOutput { + capacity_param_index, + .. + } = kind + { + params[capacity_param_index].name = "capacity".into(); + } - let return_convention = match &method.return_type { - None => ComReturnConvention::Void, - Some(typ) => { - let projected = project_type(typ).map_err(|unsupported| match unsupported { - UnsupportedComType::NativeStructLayout { .. } | UnsupportedComType::Unknown => { - unsupported_error( - UnsupportedComType::UnsupportedDirectReturn { - type_name: format!("{typ:?}"), - }, - &context(), - ) - } - unsupported => { - unsupported_error(unsupported, &format!("{} return value", context())) - } - })?; - if projected == ComType::HResult { - if method.preserve_hresult { - ComReturnConvention::SemanticHResult - } else { - ComReturnConvention::HResult - } - } else if is_supported_direct_return(&projected) { - ComReturnConvention::Direct(projected) - } else { - return Err(unsupported_error( - UnsupportedComType::UnsupportedDirectReturn { - type_name: format!("{typ:?}"), - }, - &context(), + let optional_outputs = params + .iter() + .enumerate() + .filter_map(|(index, param)| { + (param.direction == ComParamDirection::OptionalOut).then_some(index) + }) + .collect::>(); + if !optional_outputs.is_empty() + && !matches!(kind, ProjectedComMethodKind::EnumeratorNext { .. }) + { + if interface_namespace != "Windows.Win32.System.Com" + || interface_name != "IDispatch" + || method.name() != "Invoke" + || params.len() != 8 + || optional_outputs != [5, 6, 7] + || params[..5] + .iter() + .any(|param| param.direction != ComParamDirection::In) + || !matches!( + params[0].typ, + ComType::Primitive(ComPrimitive::I32) + | ComType::ScalarAlias { + underlying: ComScalarRepr::Primitive(ComPrimitive::I32), + .. + } + ) + || !matches!(params[1].typ, ComType::RawPointer) + || !matches!( + params[2].typ, + ComType::Primitive(ComPrimitive::U32) + | ComType::ScalarAlias { + underlying: ComScalarRepr::Primitive(ComPrimitive::U32), + .. + } + ) + || !matches!( + params[3].typ, + ComType::Primitive(ComPrimitive::U16) + | ComType::Enum { + underlying: ComEnumUnderlying::U16, + .. + } + | ComType::ScalarAlias { + underlying: ComScalarRepr::Primitive(ComPrimitive::U16), + .. + } + ) + || params[4].direction != ComParamDirection::In + || !matches!(params[4].typ, ComType::DispatchParams) + || !matches!(params[5].typ, ComType::Variant) + || !matches!(params[6].typ, ComType::ExcepInfo) + || !matches!( + params[7].typ, + ComType::Primitive(ComPrimitive::U32) + | ComType::ScalarAlias { + underlying: ComScalarRepr::Primitive(ComPrimitive::U32), + .. + } + ) + { + return Err(format!( + "{}: optional COM outputs require the exact validated IDispatch::Invoke contract", + context() + )); + } + kind = ProjectedComMethodKind::DispatchInvoke { + result_param_index: 5, + excep_info_param_index: 6, + arg_err_param_index: 7, + }; + params[4].name = "dispParams".into(); + params[6].surface_result = false; + params[7].surface_result = false; + } + + fn supports_nullable_projection(typ: &ComType) -> bool { + matches!( + typ, + ComType::RawPointer + | ComType::PointerAlias { .. } + | ComType::NativePodPointer { .. } + | ComType::Bstr + | ComType::ManagedInterface { .. } + | ComType::SafeArray { .. } + ) + } + + let mut return_convention = match method.return_kind() { + ComReturnKind::HResult => ComReturnConvention::HResult, + ComReturnKind::SemanticHResult => ComReturnConvention::SemanticHResult, + ComReturnKind::EnumeratorNextHResult => ComReturnConvention::SemanticHResult, + ComReturnKind::Void => ComReturnConvention::Void, + ComReturnKind::DirectValue(abi_type) => { + let typ = project_value_type(semantic, abi_type)?; + if !is_supported_direct_return(&typ) { + return Err(format!( + "{}: unsupported direct native return type {}", + context(), + semantic_type_name(semantic, abi_type) )); } + ComReturnConvention::Direct(typ) + } + ComReturnKind::DirectPointer(abi_type) => { + return Err(format!( + "{}: unsupported direct native return type {}", + context(), + semantic_type_name(semantic, abi_type) + )); } }; - if method.preserve_hresult && !matches!(return_convention, ComReturnConvention::SemanticHResult) + if matches!(kind, ProjectedComMethodKind::DispatchInvoke { .. }) + && return_convention != ComReturnConvention::HResult { return Err(format!( - "{}: semantic HRESULT metadata requires an HRESULT return", + "{}: IDispatch::Invoke requires the HRESULT return convention", context() )); } - - let string_buffer = project_string_buffer(method)?; - if params - .iter() - .any(|param| param.direction == ComParamDirection::OutStringBuffer) - && string_buffer.is_none() - { - return Err(format!( - "{}: unsupported string-buffer encoding or count relationship", - context() - )); + if matches!(kind, ProjectedComMethodKind::DispatchInvoke { .. }) { + return_convention = ComReturnConvention::DispatchInvokeHResult; } + let mut results = Vec::new(); - if let ComReturnConvention::SemanticHResult | ComReturnConvention::Direct(_) = - &return_convention + if !matches!(kind, ProjectedComMethodKind::EnumeratorNext { .. }) + && let ComReturnConvention::SemanticHResult | ComReturnConvention::Direct(_) = + &return_convention { let typ = match &return_convention { ComReturnConvention::SemanticHResult => ComType::HResult, ComReturnConvention::Direct(typ) => typ.clone(), - ComReturnConvention::HResult | ComReturnConvention::Void => unreachable!(), + ComReturnConvention::HResult + | ComReturnConvention::DispatchInvokeHResult + | ComReturnConvention::Void => unreachable!(), }; results.push(ProjectedComResult { - conversion: result_conversion(&typ, method, None, &kind), typ, source: ResultSource::DirectReturn, + conversion: ResultConversion::Value, }); } - for (index, param) in params.iter().enumerate() { - if matches!( - param.direction, - ComParamDirection::Out | ComParamDirection::InOut - ) { + for (index, (contract, param)) in method.params().iter().zip(¶ms).enumerate() { + if param.surface_result { results.push(ProjectedComResult { typ: param.typ.clone(), source: ResultSource::Param(index), - conversion: result_conversion(¶m.typ, method, Some(index), &kind), + conversion: if matches!( + param.direction, + ComParamDirection::CallerOutputBuffer + | ComParamDirection::CalleeAllocatedBuffer + ) { + if matches!( + typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == index) + .map(|plan| &plan.relation), + Some(TypedBufferRelation::EnumeratorNext { .. }) + ) { + let interface = match &kind { + ProjectedComMethodKind::EnumeratorNext { interface, .. } => { + interface.clone() + } + _ => unreachable!("EnumeratorNext buffer has EnumeratorNext kind"), + }; + ResultConversion::EnumeratorArray { interface } + } else if is_owning_array_output_element( + &typed_buffers + .iter() + .find(|plan| plan.buffer_param_index == index) + .expect("caller output buffer plan") + .element, + ) { + ResultConversion::OwningArray { + interface: project_buffer_interface_ref(semantic, method, index)?, + } + } else if shared_counts.iter().any(|group| match group { + SharedCountPlan::StringInputScalarOutput { + scalar_output_param_index, + .. + } => *scalar_output_param_index == index, + SharedCountPlan::Parallel { + output_param_indices, + .. + } => output_param_indices.contains(&index), + }) { + ResultConversion::PlainArray + } else { + ResultConversion::Buffer + } + } else { + result_conversion( + contract, + ¶m.typ, + dynamic_iid + .is_some_and(|dynamic| dynamic.output_param_index().index() == index), + )? + }, }); } } Ok(ProjectedComMethod { - name: method.name.clone(), - camel_name: camel_case(&method.name), - vtable_index: method.vtable_index, + name: method.name().into(), + camel_name: camel_case(method.name()), + vtable_index: method.vtable_slot(), params, return_convention, results, string_buffer, + typed_buffers, + shared_counts, kind, - doc: method.doc.clone(), + doc, overload: None, }) } -fn result_conversion( - typ: &ComType, - method: &MethodMeta, - param_index: Option, - kind: &ProjectedComMethodKind, -) -> ResultConversion { - if matches!( - kind, - ProjectedComMethodKind::CallerSuppliedDynamicIid { .. } - | ProjectedComMethodKind::SynthesizedGetForWindow { .. } - ) && param_index == Some(method.params.len() - 1) - { - return ResultConversion::DynamicIidAdoption; - } - if let Some(index) = param_index { - let cleanup = cleanup_for_param(method, index, &method.name) - .expect("cleanup contract was validated during projection"); - if cleanup == Some(CleanupKind::SysFreeString) && matches!(typ, ComType::Bstr) { - return ResultConversion::Bstr; - } - if cleanup == Some(CleanupKind::CoTaskMemFree) { - return match typ { - ComType::PointerAlias { name, .. } if name == "PWSTR" => { - ResultConversion::CoTaskMemString(StringEncoding::Wide) - } - ComType::PointerAlias { name, .. } if name == "PSTR" => { - ResultConversion::CoTaskMemString(StringEncoding::Ansi) - } - _ => ResultConversion::CoTaskMemData, - }; +fn project_dynamic_method_kind( + method_name: &str, + dynamic_iid: Option<(usize, usize)>, + interop_target_iid: Option<&str>, +) -> ProjectedComMethodKind { + match (method_name, dynamic_iid, interop_target_iid) { + ("GetForWindow", Some((iid_param_index, output_param_index)), Some(target_iid)) => { + ProjectedComMethodKind::SynthesizedGetForWindow { + iid_param_index, + output_param_index, + target_iid: target_iid.into(), + } } - } - match typ { - ComType::ManagedInterface { .. } => ResultConversion::ManagedCom, - ComType::HString => ResultConversion::HString, - _ => ResultConversion::Value, + (_, Some((iid_param_index, output_param_index)), _) => { + ProjectedComMethodKind::CallerSuppliedDynamicIid { + iid_param_index, + output_param_index, + } + } + _ => ProjectedComMethodKind::Normal, } } -fn validate_owned_outputs( - method: &MethodMeta, - params: &[ProjectedComParam], - context: &str, +fn validate_buffer_plan_composition( + method: &str, + string_buffer: Option<&StringBufferPlan>, + typed_buffers: &[TypedBufferPlan], ) -> Result<(), String> { - for (index, param) in params.iter().enumerate() { - let Some(cleanup) = cleanup_for_param(method, index, context)? else { - continue; - }; - if !matches!( - param.direction, - ComParamDirection::Out | ComParamDirection::InOut - ) { - return Err(format!( - "{context}: ownership metadata applies to non-output parameter `{}`", - param.name - )); - } - if cleanup == CleanupKind::SysFreeString { - if param.direction != ComParamDirection::Out || param.typ != ComType::Bstr { - return Err(format!( - "{context}: SysFreeString ownership requires a scalar Out BSTR" - )); - } - } else if cleanup == CleanupKind::CoTaskMemFree { - if param.direction != ComParamDirection::Out - || !matches!( - param.typ, - ComType::RawPointer - | ComType::PointerAlias { - kind: super::ir::PointerAliasKind::DataPointer - | super::ir::PointerAliasKind::StringPointer(_), - .. - } - ) - { - return Err(format!( - "{context}: CoTaskMemFree ownership requires an Out data or string pointer" - )); - } - } + if string_buffer.is_some() && !typed_buffers.is_empty() { + return Err(format!( + "{method}: mixed string and typed buffer plans are not supported" + )); } - for owned in &method.owned_outputs { - if owned.param_index >= params.len() { - return Err(format!( - "{context}: ownership metadata references missing parameter index {}", - owned.param_index - )); - } + let two_call_count = typed_buffers + .iter() + .filter(|plan| { + matches!( + plan.relation, + TypedBufferRelation::CallerOutput { + sizing: TypedBufferSizing::TwoCall { .. }, + .. + } + ) + }) + .count(); + if two_call_count > 0 && typed_buffers.len() != 1 { + return Err(format!( + "{method}: two-call sizing cannot be combined with another buffer plan" + )); } Ok(()) } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum CleanupKind { - SysFreeString, - CoTaskMemFree, +fn validate_dynamic_iid_buffers( + method: &str, + has_dynamic_iid: bool, + string_buffer: Option<&StringBufferPlan>, + typed_buffers: &[TypedBufferPlan], +) -> Result<(), String> { + if has_dynamic_iid && (string_buffer.is_some() || !typed_buffers.is_empty()) { + return Err(format!( + "{method}: dynamic-IID methods with hidden string/buffer parameters are not supported" + )); + } + Ok(()) } -fn cleanup_for_param( - method: &MethodMeta, - param_index: usize, - context: &str, -) -> Result, String> { - let contracts = method - .owned_outputs - .iter() - .filter(|owned| owned.param_index == param_index) - .map(|owned| owned.free_with.as_str()) - .collect::>(); - match contracts.as_slice() { - [] => Ok(None), - [contract] => parse_cleanup_contract(contract) - .map(Some) - .ok_or_else(|| format!("{context}: unsupported output cleanup contract `{contract}`")), - _ => Err(format!( - "{context}: output parameter index {param_index} has multiple cleanup contracts" +fn project_param_type( + semantic: &SemanticComInterface, + param: &ComParamContract, +) -> Result { + match param.direction() { + Direction::In => project_input_type(semantic, param.abi_type()), + Direction::InOut if param.nullability() == Nullability::Nullable => { + let typ = project_input_type(semantic, param.abi_type())?; + if matches!(typ, ComType::NativePodPointer { .. }) { + Ok(typ) + } else { + Err(format!( + "nullable [in, out] parameter `{}` requires a native POD pointer contract", + param.name() + )) + } + } + Direction::Out | Direction::InOut => project_output_type(semantic, param.abi_type()), + } +} + +fn project_input_type( + semantic: &SemanticComInterface, + abi_type: super::model::ids::TypeId, +) -> Result { + let definition = semantic + .type_definition(abi_type) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Pointer { pointee, depth, .. } if depth.get() == 1 => { + let pointee_definition = semantic + .type_definition(*pointee) + .map_err(|error| error.to_string())?; + if matches!(pointee_definition.abi(), ComAbiType::ComInterface { .. }) { + project_value_type(semantic, *pointee) + } else if matches!(pointee_definition.abi(), ComAbiType::NativeStruct(_)) { + let ComType::NativePod { layout } = project_value_type(semantic, *pointee)? else { + unreachable!("validated native struct projection") + }; + Ok(ComType::NativePodPointer { layout }) + } else if matches!(pointee_definition.abi(), ComAbiType::NativeUnion(_)) { + let ComAbiType::NativeUnion(layout_id) = pointee_definition.abi() else { + unreachable!() + }; + let native_name = pointee_definition + .native_name() + .ok_or_else(|| "validated native union has no qualified name".to_string())?; + Ok(ComType::NativeUnionPointer { + layout: project_native_union_layout( + semantic, + native_name.namespace(), + native_name.name(), + *layout_id, + )?, + }) + } else if matches!( + pointee_definition.abi(), + ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::SafeArray { .. } + | ComAbiType::DispatchParams + ) { + project_value_type(semantic, *pointee) + } else if matches!(pointee_definition.abi(), ComAbiType::ExcepInfo) { + Err("EXCEPINFO is output-only".into()) + } else { + Ok(ComType::RawPointer) + } + } + ComAbiType::Pointer { .. } => Ok(ComType::RawPointer), + ComAbiType::CountedBuffer { .. } => project_counted_buffer_type(semantic, definition), + ComAbiType::Variant => Ok(ComType::VariantByValue), + ComAbiType::PropVariant + | ComAbiType::SafeArray { .. } + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo => Err(format!( + "{} must be passed through its native pointer contract", + semantic_type_definition_name(definition) )), + ComAbiType::NativeUnion(_) => Err(format!( + "{} by-value union input is not supported; use an explicit tagged pointer input", + semantic_type_definition_name(definition) + )), + _ => project_value_type(semantic, abi_type), } } -fn parse_cleanup_contract(contract: &str) -> Option { - if contract.is_empty() - || contract != contract.trim() - || contract - .chars() - .any(|character| character.is_whitespace() || matches!(character, ',' | ';')) - { - return None; +fn project_output_type( + semantic: &SemanticComInterface, + abi_type: super::model::ids::TypeId, +) -> Result { + let definition = semantic + .type_definition(abi_type) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Pointer { pointee, depth, .. } if depth.get() == 1 => { + let pointee_definition = semantic + .type_definition(*pointee) + .map_err(|error| error.to_string())?; + if let ComAbiType::NativeStruct(layout_id) = pointee_definition.abi() + && native_layout_requires_output_ownership( + semantic, + *layout_id, + &mut std::collections::BTreeSet::new(), + )? + { + return Err( + "native struct outputs with nested pointer lifetimes require ownership projection" + .into(), + ); + } + if matches!(pointee_definition.abi(), ComAbiType::NativeUnion(_)) { + return Err( + "native union outputs require an explicit active-field/discriminant contract" + .into(), + ); + } + if matches!(pointee_definition.abi(), ComAbiType::SafeArray { .. }) { + return Err( + "SAFEARRAY output requires SAFEARRAY** ownership, not writable descriptor bytes" + .into(), + ); + } + if matches!(pointee_definition.abi(), ComAbiType::DispatchParams) { + return Err("DISPPARAMS is input-only".into()); + } + project_value_type(semantic, *pointee) + } + ComAbiType::Pointer { pointee, depth, .. } + if depth.get() == 2 + && matches!( + semantic + .type_definition(*pointee) + .map_err(|error| error.to_string())? + .abi(), + ComAbiType::SafeArray { .. } + ) => + { + project_value_type(semantic, *pointee) + } + ComAbiType::Pointer { .. } => Ok(ComType::RawPointer), + ComAbiType::DataPointer { depth, .. } if depth.get() > 1 => Ok(ComType::RawPointer), + ComAbiType::CountedBuffer { .. } => project_counted_buffer_type(semantic, definition), + ComAbiType::NativeStruct(layout_id) + if native_layout_requires_output_ownership( + semantic, + *layout_id, + &mut std::collections::BTreeSet::new(), + )? => + { + Err( + "native struct outputs with nested pointer lifetimes require ownership projection" + .into(), + ) + } + ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::SafeArray { .. } + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo => Err( + "Automation outputs require VARIANT*, PROPVARIANT*, or SAFEARRAY** pointer metadata" + .into(), + ), + _ => project_value_type(semantic, abi_type), } - let identifier = contract - .rsplit_once(|character: char| matches!(character, '.' | '!' | ':')) - .map_or(contract, |(_, identifier)| identifier); - if identifier.is_empty() { - return None; +} + +fn native_layout_requires_output_ownership( + semantic: &SemanticComInterface, + layout_id: super::model::ids::LayoutId, + visiting: &mut std::collections::BTreeSet, +) -> Result { + if !visiting.insert(layout_id) { + return Err("recursive native layout while checking resource ownership".into()); } - match identifier { - "SysFreeString" => Some(CleanupKind::SysFreeString), - "CoTaskMemFree" => Some(CleanupKind::CoTaskMemFree), - _ => None, + let layouts = semantic + .layout_definition(layout_id) + .map_err(|error| error.to_string())?; + let mut contains = false; + 'architectures: for architecture in [Architecture::X86, Architecture::X64, Architecture::Arm64] + { + for field in layouts.get(architecture).fields() { + let definition = semantic + .type_definition(field.abi_type()) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Handle(_) + | ComAbiType::DataPointer { .. } + | ComAbiType::Pointer { .. } + | ComAbiType::StringPointer { .. } + | ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::ComInterface { .. } => { + contains = true; + break 'architectures; + } + ComAbiType::NativeStruct(nested) => { + if native_layout_requires_output_ownership(semantic, *nested, visiting)? { + contains = true; + break 'architectures; + } + } + _ => {} + } + } } + visiting.remove(&layout_id); + Ok(contains) } -fn project_string_buffer(method: &MethodMeta) -> Result, String> { - let buffers = method - .params - .iter() - .enumerate() - .filter_map(|(buffer_param_index, param)| { - let ParamDirection::OutStringBuffer { count_param_index } = param.direction else { - return None; - }; - Some((buffer_param_index, count_param_index, param)) - }) - .collect::>(); - if buffers.len() > 1 { - return Err(format!( - "{}: multiple caller-owned string buffers are not supported", - method.name - )); - } - let plan = - buffers - .into_iter() - .next() - .and_then(|(buffer_param_index, count_param_index, param)| { - let encoding = match pointer_alias_name(¶m.typ) { - Some("PWSTR") => StringEncoding::Wide, - Some("PSTR") => StringEncoding::Ansi, - _ => return None, - }; - method - .params - .get(count_param_index) - .filter(|count| count.direction == ParamDirection::In)?; - let optional_param_indices = (count_param_index..method.params.len()) - .filter(|index| string_buffer_param_is_optional(method, *index)) - .collect(); - Some(StringBufferPlan { - buffer_param_index, - count_param_index, - encoding, - optional_param_indices, +fn project_value_type( + semantic: &SemanticComInterface, + abi_type: super::model::ids::TypeId, +) -> Result { + let definition = semantic + .type_definition(abi_type) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Scalar(scalar) => project_scalar(definition, *scalar), + ComAbiType::Guid => Ok(ComType::Guid), + ComAbiType::Enum(enum_id) => { + let definition = semantic + .enum_definition(*enum_id) + .map_err(|error| error.to_string())?; + Ok(ComType::Enum { + namespace: definition.native_name().namespace().into(), + name: definition.native_name().name().into(), + underlying: project_enum_underlying(definition.underlying())?, + }) + } + ComAbiType::Handle(handle) => Ok(ComType::PointerAlias { + namespace: handle.native_name().namespace().into(), + name: handle.native_name().name().into(), + kind: PointerAliasKind::HandleValue, + }), + ComAbiType::DataPointer { .. } => { + if definition.underlying().is_some() { + let name = definition + .native_name() + .ok_or_else(|| "validated data-pointer alias has no native name".to_string())?; + Ok(ComType::PointerAlias { + namespace: name.namespace().into(), + name: name.name().into(), + kind: PointerAliasKind::DataPointer, }) - }); - if plan - .as_ref() - .is_some_and(|plan| plan.encoding == StringEncoding::Ansi) + } else { + Ok(ComType::RawPointer) + } + } + ComAbiType::StringPointer { encoding, .. } => { + let name = definition + .native_name() + .ok_or_else(|| "validated string pointer has no native name".to_string())?; + Ok(ComType::PointerAlias { + namespace: name.namespace().into(), + name: name.name().into(), + kind: PointerAliasKind::StringPointer(project_string_encoding(*encoding)), + }) + } + ComAbiType::Bstr => Ok(ComType::Bstr), + ComAbiType::HString => Ok(ComType::HString), + ComAbiType::ComInterface { iid } => Ok(ComType::ManagedInterface { + iid: format_guid(iid.as_bytes()), + }), + ComAbiType::Pointer { .. } => Ok(ComType::RawPointer), + ComAbiType::CountedBuffer { .. } => project_counted_buffer_type(semantic, definition), + ComAbiType::NativeStruct(layout_id) => { + let native_name = definition + .native_name() + .ok_or_else(|| "validated native POD struct has no qualified name".to_string())?; + Ok(ComType::NativePod { + layout: project_native_pod_layout( + semantic, + native_name.namespace(), + native_name.name(), + *layout_id, + )?, + }) + } + ComAbiType::Variant => Ok(ComType::Variant), + ComAbiType::SafeArray { + element: Some(element), + } => Ok(ComType::SafeArray { + element: project_safe_array_element(semantic, *element)?, + }), + ComAbiType::SafeArray { element: None } => { + Err("SAFEARRAY element VARTYPE is not proven".into()) + } + ComAbiType::PropVariant => Ok(ComType::PropVariant), + ComAbiType::DispatchParams => Ok(ComType::DispatchParams), + ComAbiType::ExcepInfo => Ok(ComType::ExcepInfo), + ComAbiType::NativeUnion(_) | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => { + Err(format!( + "unsupported Classic-COM semantic type {}", + semantic_type_definition_name(definition) + )) + } + } +} + +fn project_native_union_layout( + semantic: &SemanticComInterface, + namespace: &str, + name: &str, + layout_id: super::model::ids::LayoutId, +) -> Result { + let layouts = semantic + .layout_definition(layout_id) + .map_err(|error| error.to_string())?; + let x86 = project_native_union_architecture( + semantic, + layouts.get(Architecture::X86), + Architecture::X86, + )?; + let x64 = project_native_union_architecture( + semantic, + layouts.get(Architecture::X64), + Architecture::X64, + )?; + let arm64 = project_native_union_architecture( + semantic, + layouts.get(Architecture::Arm64), + Architecture::Arm64, + )?; + let field_contract = |layout: &NativeUnionArchitectureLayout| { + layout + .fields + .iter() + .map(|field| (field.name.clone(), field.count)) + .collect::>() + }; + if field_contract(&x86) != field_contract(&x64) + || field_contract(&x64) != field_contract(&arm64) { return Err(format!( - "{}: caller-owned ANSI output buffers are not yet decoded safely", - method.name + "native union `{namespace}.{name}` has architecture-dependent active fields" )); } - Ok(plan) + Ok(NativeUnionLayout { + namespace: namespace.into(), + name: name.into(), + x86, + x64, + arm64, + }) } -fn string_buffer_param_is_optional(method: &MethodMeta, param_index: usize) -> bool { - let Some(count_index) = method - .params +fn project_safe_array_element( + semantic: &SemanticComInterface, + type_id: super::model::ids::TypeId, +) -> Result { + let definition = semantic + .type_definition(type_id) + .map_err(|error| error.to_string())?; + Ok(match definition.abi() { + ComAbiType::Scalar(ScalarType::I8) => SafeArrayElement::I8, + ComAbiType::Scalar(ScalarType::U8) => SafeArrayElement::U8, + ComAbiType::Scalar(ScalarType::I16) => SafeArrayElement::I16, + ComAbiType::Scalar(ScalarType::U16) => SafeArrayElement::U16, + ComAbiType::Scalar(ScalarType::I32) => SafeArrayElement::I32, + ComAbiType::Scalar(ScalarType::U32) => SafeArrayElement::U32, + ComAbiType::Scalar(ScalarType::I64) => SafeArrayElement::I64, + ComAbiType::Scalar(ScalarType::U64) => SafeArrayElement::U64, + ComAbiType::Scalar(ScalarType::F32) => SafeArrayElement::F32, + ComAbiType::Scalar(ScalarType::F64) => SafeArrayElement::F64, + ComAbiType::Scalar(ScalarType::Bool | ScalarType::Win32Bool) => SafeArrayElement::Bool, + ComAbiType::Bstr => SafeArrayElement::Bstr, + ComAbiType::Variant => SafeArrayElement::Variant, + ComAbiType::ComInterface { iid } => SafeArrayElement::Interface { + iid: *iid.as_bytes(), + }, + unsupported => { + return Err(format!( + "unsupported SAFEARRAY element semantic {unsupported:?}" + )); + } + }) +} + +fn project_native_union_architecture( + semantic: &SemanticComInterface, + layout: &super::model::layout::NativeLayout, + architecture: Architecture, +) -> Result { + if layout.kind() != super::model::layout::LayoutKind::Union { + return Err("native union type references a non-union layout".into()); + } + if layout.packing() != 8 { + return Err(format!( + "packed native union layouts are not supported (packing {})", + layout.packing() + )); + } + let fields = layout + .fields() .iter() - .find_map(|param| match param.direction { - ParamDirection::OutStringBuffer { count_param_index } => Some(count_param_index), - _ => None, + .map(|field| { + if field.offset() != 0 { + return Err(format!( + "native union field `{}` does not overlap at offset zero", + field.name() + )); + } + Ok(NativeUnionField { + name: field.name().into(), + count: field.fixed_count().map_or(1, |count| count.get()), + typ: project_native_union_field_type(semantic, field.abi_type(), architecture)?, + }) }) - else { - return false; - }; - // The count parameter is optional (defaultable) only when no other required - // input parameter follows it — otherwise a caller could not omit it without - // also omitting later required arguments. This authoritative, metadata-driven - // count relationship replaces any name-based ("cch..."/"pfd"/find-data) shape - // guessing. - param_index == count_index - && method - .params - .iter() - .skip(param_index + 1) - .filter(|param| param.direction.is_input()) - .count() - == 0 + .collect::, String>>()?; + Ok(NativeUnionArchitectureLayout { + size: layout.size(), + alignment: layout.alignment(), + fields, + }) } -fn pointer_alias_name(typ: &TypeMeta) -> Option<&str> { - match typ { - TypeMeta::Struct { name, .. } => Some(name), - _ => None, +fn project_native_union_field_type( + semantic: &SemanticComInterface, + type_id: super::model::ids::TypeId, + architecture: Architecture, +) -> Result { + let definition = semantic + .type_definition(type_id) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Scalar(scalar) => Ok(NativeUnionFieldType::Scalar(match scalar { + ScalarType::Bool | ScalarType::I8 => NativePodScalar::I8, + ScalarType::U8 => NativePodScalar::U8, + ScalarType::I16 => NativePodScalar::I16, + ScalarType::U16 | ScalarType::Char16 => NativePodScalar::U16, + ScalarType::I32 | ScalarType::Win32Bool | ScalarType::HResult => NativePodScalar::I32, + ScalarType::U32 => NativePodScalar::U32, + ScalarType::I64 => NativePodScalar::I64, + ScalarType::U64 => NativePodScalar::U64, + ScalarType::F32 => NativePodScalar::F32, + ScalarType::F64 => NativePodScalar::F64, + ScalarType::NativeIsize => NativePodScalar::NativeIsize, + ScalarType::NativeUsize => NativePodScalar::NativeUsize, + })), + ComAbiType::Guid => Ok(NativeUnionFieldType::Guid), + ComAbiType::Enum(enum_id) => { + let underlying = semantic + .enum_definition(*enum_id) + .map_err(|error| error.to_string())? + .underlying(); + Ok(NativeUnionFieldType::Scalar(match underlying { + ScalarType::I8 => NativePodScalar::I8, + ScalarType::U8 => NativePodScalar::U8, + ScalarType::I16 => NativePodScalar::I16, + ScalarType::U16 => NativePodScalar::U16, + ScalarType::I32 => NativePodScalar::I32, + ScalarType::U32 => NativePodScalar::U32, + ScalarType::I64 => NativePodScalar::I64, + ScalarType::U64 => NativePodScalar::U64, + _ => return Err("native union enum has a non-integral ABI".into()), + })) + } + ComAbiType::Pointer { .. } | ComAbiType::DataPointer { .. } => { + Ok(NativeUnionFieldType::Pointer) + } + ComAbiType::NativeStruct(layout_id) => { + let native_name = definition + .native_name() + .ok_or_else(|| "nested native POD has no qualified name".to_string())?; + let nested = semantic + .layout_definition(*layout_id) + .map_err(|error| error.to_string())?; + let mut visiting = std::collections::HashSet::new(); + Ok(NativeUnionFieldType::Struct { + name: format!("{}.{}", native_name.namespace(), native_name.name()), + layout: Box::new(project_native_pod_architecture( + semantic, + nested.get(architecture), + architecture, + &mut visiting, + )?), + }) + } + _ => Err(format!( + "unsupported owned or nested union field {}", + semantic_type_definition_name(definition) + )), } } -fn dynamic_iid_natural_param_count(method: &MethodMeta) -> Option { - if !method - .return_type - .as_ref() - .is_some_and(|typ| matches!(project_type(typ), Ok(ComType::HResult))) - || method.params.len() < 2 - { - return None; - } - let output = method.params.last()?; - if output.direction != ParamDirection::Out || output.typ != TypeMeta::Object { - return None; - } - let iid = &method.params[method.params.len() - 2]; - let iid_name = iid.name.to_ascii_lowercase(); - if iid.direction != ParamDirection::In - || iid.typ != TypeMeta::Object - || !matches!(iid_name.as_str(), "iid" | "riid") - || method.params[..method.params.len() - 2] - .iter() - .any(|param| param.direction != ParamDirection::In) - { - return None; - } - Some(method.params.len() - 2) +fn project_native_pod_layout( + semantic: &SemanticComInterface, + namespace: &str, + name: &str, + layout_id: super::model::ids::LayoutId, +) -> Result { + let layouts = semantic + .layout_definition(layout_id) + .map_err(|error| error.to_string())?; + let mut visiting = std::collections::HashSet::new(); + Ok(NativePodLayout { + namespace: namespace.into(), + name: name.into(), + x86: project_native_pod_architecture( + semantic, + layouts.get(Architecture::X86), + Architecture::X86, + &mut visiting, + )?, + x64: project_native_pod_architecture( + semantic, + layouts.get(Architecture::X64), + Architecture::X64, + &mut visiting, + )?, + arm64: project_native_pod_architecture( + semantic, + layouts.get(Architecture::Arm64), + Architecture::Arm64, + &mut visiting, + )?, + }) } -fn detect_interop_target( - meta: &ComInterfaceMeta, - winmd_paths: &str, -) -> Result, String> { - if !meta.interface.name.ends_with("Interop") - || !meta.interface.methods.iter().any(|method| { - method.name == "GetForWindow" && dynamic_iid_natural_param_count(method).is_some() +fn project_native_pod_architecture( + semantic: &SemanticComInterface, + layout: &super::model::layout::NativeLayout, + architecture: Architecture, + visiting: &mut std::collections::HashSet, +) -> Result { + if layout.packing() != 8 { + return Err(format!( + "packed native POD layouts are not supported (packing {})", + layout.packing() + )); + } + let fields = layout + .fields() + .iter() + .map(|field| { + Ok(NativePodField { + name: field.name().into(), + offset: field.offset(), + count: field.fixed_count().map_or(1, |count| count.get()), + typ: project_native_pod_field_type( + semantic, + field.abi_type(), + architecture, + visiting, + )?, + }) + }) + .collect::, String>>()?; + Ok(NativePodArchitectureLayout { + size: layout.size(), + alignment: layout.alignment(), + fields, + }) +} + +fn project_native_pod_field_type( + semantic: &SemanticComInterface, + type_id: super::model::ids::TypeId, + architecture: Architecture, + visiting: &mut std::collections::HashSet, +) -> Result { + let definition = semantic + .type_definition(type_id) + .map_err(|error| error.to_string())?; + match definition.abi() { + ComAbiType::Scalar(scalar) => Ok(NativePodFieldType::Scalar(match scalar { + ScalarType::Bool | ScalarType::I8 => NativePodScalar::I8, + ScalarType::U8 => NativePodScalar::U8, + ScalarType::I16 => NativePodScalar::I16, + ScalarType::U16 | ScalarType::Char16 => NativePodScalar::U16, + ScalarType::I32 | ScalarType::Win32Bool | ScalarType::HResult => NativePodScalar::I32, + ScalarType::U32 => NativePodScalar::U32, + ScalarType::I64 => NativePodScalar::I64, + ScalarType::U64 => NativePodScalar::U64, + ScalarType::F32 => NativePodScalar::F32, + ScalarType::F64 => NativePodScalar::F64, + ScalarType::NativeIsize => NativePodScalar::NativeIsize, + ScalarType::NativeUsize => NativePodScalar::NativeUsize, + })), + ComAbiType::Guid => Ok(NativePodFieldType::Guid), + ComAbiType::Enum(enum_id) => { + let underlying = semantic + .enum_definition(*enum_id) + .map_err(|error| error.to_string())? + .underlying(); + Ok(NativePodFieldType::Scalar(match underlying { + ScalarType::I8 => NativePodScalar::I8, + ScalarType::U8 => NativePodScalar::U8, + ScalarType::I16 => NativePodScalar::I16, + ScalarType::U16 => NativePodScalar::U16, + ScalarType::I32 => NativePodScalar::I32, + ScalarType::U32 => NativePodScalar::U32, + ScalarType::I64 => NativePodScalar::I64, + ScalarType::U64 => NativePodScalar::U64, + _ => return Err("native POD enum has a non-integral ABI".into()), + })) + } + ComAbiType::Pointer { .. } + | ComAbiType::DataPointer { .. } + | ComAbiType::Handle(_) + | ComAbiType::StringPointer { .. } => Ok(NativePodFieldType::Pointer), + ComAbiType::NativeStruct(layout_id) => { + if !visiting.insert(*layout_id) { + return Err("recursive native POD layout".into()); + } + let native_name = definition + .native_name() + .ok_or_else(|| "nested native POD has no qualified name".to_string())?; + let nested = semantic + .layout_definition(*layout_id) + .map_err(|error| error.to_string())?; + let projected = project_native_pod_architecture( + semantic, + nested.get(architecture), + architecture, + visiting, + )?; + visiting.remove(layout_id); + Ok(NativePodFieldType::Struct { + name: format!("{}.{}", native_name.namespace(), native_name.name()), + layout: Box::new(projected), + }) + } + ComAbiType::Bstr + | ComAbiType::HString + | ComAbiType::ComInterface { .. } + | ComAbiType::NativeUnion(_) + | ComAbiType::CountedBuffer { .. } + | ComAbiType::SafeArray { .. } + | ComAbiType::Variant + | ComAbiType::PropVariant + | ComAbiType::DispatchParams + | ComAbiType::ExcepInfo + | ComAbiType::FunctionPointer(_) + | ComAbiType::Unknown(_) => Err(format!( + "unsupported nested native POD field {}", + semantic_type_definition_name(definition) + )), + } +} + +fn project_scalar(definition: &ComTypeDefinition, scalar: ScalarType) -> Result { + if definition.underlying().is_some() { + let name = definition + .native_name() + .ok_or_else(|| "validated scalar alias has no native name".to_string())?; + return Ok(ComType::ScalarAlias { + namespace: name.namespace().into(), + name: name.name().into(), + underlying: project_scalar_repr(scalar)?, + }); + } + match scalar { + ScalarType::NativeIsize => Ok(ComType::NativeIsize), + ScalarType::NativeUsize => Ok(ComType::NativeUsize), + ScalarType::Win32Bool => Ok(ComType::Win32Bool), + ScalarType::HResult => Ok(ComType::HResult), + _ => Ok(ComType::Primitive(project_primitive(scalar)?)), + } +} + +fn project_primitive(scalar: ScalarType) -> Result { + match scalar { + ScalarType::Bool => Ok(ComPrimitive::Bool), + ScalarType::I8 => Ok(ComPrimitive::I8), + ScalarType::U8 => Ok(ComPrimitive::U8), + ScalarType::I16 => Ok(ComPrimitive::I16), + ScalarType::U16 => Ok(ComPrimitive::U16), + ScalarType::I32 => Ok(ComPrimitive::I32), + ScalarType::U32 => Ok(ComPrimitive::U32), + ScalarType::I64 => Ok(ComPrimitive::I64), + ScalarType::U64 => Ok(ComPrimitive::U64), + ScalarType::F32 => Ok(ComPrimitive::F32), + ScalarType::F64 => Ok(ComPrimitive::F64), + ScalarType::Char16 => Ok(ComPrimitive::Char16), + ScalarType::NativeIsize + | ScalarType::NativeUsize + | ScalarType::Win32Bool + | ScalarType::HResult => Err(format!( + "non-primitive scalar {scalar:?} cannot use a primitive projection" + )), + } +} + +fn project_scalar_repr(scalar: ScalarType) -> Result { + match scalar { + ScalarType::NativeIsize => Ok(ComScalarRepr::NativeIsize), + ScalarType::NativeUsize => Ok(ComScalarRepr::NativeUsize), + ScalarType::Win32Bool | ScalarType::HResult => Err(format!( + "special scalar {scalar:?} cannot use a transparent alias projection" + )), + _ => Ok(ComScalarRepr::Primitive(project_primitive(scalar)?)), + } +} + +fn project_enum_underlying(scalar: ScalarType) -> Result { + match scalar { + ScalarType::I8 => Ok(ComEnumUnderlying::I8), + ScalarType::U8 => Ok(ComEnumUnderlying::U8), + ScalarType::I16 => Ok(ComEnumUnderlying::I16), + ScalarType::U16 => Ok(ComEnumUnderlying::U16), + ScalarType::I32 => Ok(ComEnumUnderlying::I32), + ScalarType::U32 => Ok(ComEnumUnderlying::U32), + ScalarType::I64 => Ok(ComEnumUnderlying::I64), + ScalarType::U64 => Ok(ComEnumUnderlying::U64), + ScalarType::Bool + | ScalarType::F32 + | ScalarType::F64 + | ScalarType::Char16 + | ScalarType::NativeIsize + | ScalarType::NativeUsize + | ScalarType::Win32Bool + | ScalarType::HResult => Err(format!("unsupported COM enum underlying type {scalar:?}")), + } +} + +fn project_counted_buffer_type( + semantic: &SemanticComInterface, + definition: &ComTypeDefinition, +) -> Result { + let ComAbiType::CountedBuffer { + element, + element_ownership, + .. + } = definition.abi() + else { + unreachable!("counted-buffer projection requires CountedBuffer semantics"); + }; + match element { + BufferElement::Character(encoding) => { + let name = definition + .native_name() + .ok_or_else(|| "validated string buffer has no native name".to_string())?; + Ok(ComType::PointerAlias { + namespace: name.namespace().into(), + name: name.name().into(), + kind: PointerAliasKind::StringPointer(project_string_encoding(*encoding)), + }) + } + BufferElement::StringPointer { + encoding, + pointer_depth, + constness, + } => match element_ownership { + BufferElementOwnership::Borrowed => Ok(ComType::StringArray { + encoding: project_string_encoding(*encoding), + element_pointer_depth: pointer_depth.get(), + element_const: *constness == Constness::Const, + }), + BufferElementOwnership::CoTaskMemStringOwned + if *encoding == super::model::abi::StringEncoding::Utf16 => + { + Ok(ComType::OwningArray { + element: Box::new(ComType::CoTaskMemWideString), + interface: None, + }) + } + _ => Err("string pointer array ownership is not safely projected".into()), + }, + BufferElement::Typed(element) => { + let projected = project_value_type(semantic, *element)?; + if matches!( + element_ownership, + BufferElementOwnership::ComOwned + | BufferElementOwnership::BstrOwned + | BufferElementOwnership::VariantOwned + ) { + Ok(ComType::OwningArray { + interface: project_interface_ref_for_type(semantic, *element)?, + element: Box::new(projected), + }) + } else { + Ok(ComType::TypedBuffer { + element: Box::new(projected), + }) + } + } + BufferElement::Opaque(_) => { + Err("opaque counted-buffer elements are not safe to project".into()) + } + } +} + +fn project_typed_buffers( + semantic: &SemanticComInterface, + method: &ComMethodContract, +) -> Result, String> { + let mut plans = Vec::new(); + for (buffer_param_index, param) in method.params().iter().enumerate() { + let definition = semantic + .type_definition(param.abi_type()) + .map_err(|error| error.to_string())?; + let ComAbiType::CountedBuffer { + element, + element_ownership, + .. + } = definition.abi() + else { + continue; + }; + let element = match element { + BufferElement::StringPointer { + encoding, + pointer_depth, + constness, + } => { + if matches!(element_ownership, BufferElementOwnership::Borrowed) + && (param.direction() != Direction::In + || !matches!( + param.count(), + Some(CountRelation::InputCount { + actual_length_param: None, + unit: CountUnit::Elements, + .. + }) + )) + { + return Err(format!( + "{}: string pointer array `{}` must be a borrowed element-counted input", + method.name(), + param.name() + )); + } + match element_ownership { + BufferElementOwnership::Borrowed => ComType::StringArray { + encoding: project_string_encoding(*encoding), + element_pointer_depth: pointer_depth.get(), + element_const: *constness == Constness::Const, + }, + BufferElementOwnership::CoTaskMemStringOwned + if *encoding == super::model::abi::StringEncoding::Utf16 => + { + ComType::CoTaskMemWideString + } + _ => { + return Err(format!( + "{}: string pointer array `{}` has unsupported element ownership", + method.name(), + param.name() + )); + } + } + } + BufferElement::Typed(element) => project_value_type(semantic, *element)?, + BufferElement::Character(_) | BufferElement::Opaque(_) => continue, + }; + if matches!(element, ComType::NativePod { .. }) + && !matches!( + param.count(), + Some(CountRelation::InputCount { .. } | CountRelation::EnumeratorNext { .. }) + ) + { + return Err(format!( + "{}: native struct counted buffer `{}` currently supports input contracts only", + method.name(), + param.name() + )); + } + if !is_supported_buffer_element(&element) { + return Err(format!( + "{}: counted buffer `{}` has unsupported element type", + method.name(), + param.name() + )); + } + let relation = match param + .count() + .ok_or_else(|| format!("{}: counted buffer has no relation", param.name()))? + { + CountRelation::InputCount { + count_param, + actual_length_param, + unit, + } => TypedBufferRelation::Input { + count_param_index: count_param.index(), + actual_length_param_index: actual_length_param.map(|index| index.index()), + unit: project_count_unit(*unit), + }, + CountRelation::CallerCapacity { + capacity_param, + actual_length_param, + unit, + sizing, + } => { + let sizing = match sizing { + BufferSizing::SingleCall => TypedBufferSizing::SingleCall, + BufferSizing::FixedCapacity => TypedBufferSizing::FixedCapacity, + BufferSizing::TwoCall { max_retries } => { + if *unit != CountUnit::Bytes + || !matches!(element, ComType::Primitive(ComPrimitive::U8)) + { + return Err(format!( + "{}: bounded two-call sizing currently requires a byte buffer", + method.name() + )); + } + TypedBufferSizing::TwoCall { + max_retries: *max_retries, + } + } + }; + TypedBufferRelation::CallerOutput { + capacity_param_index: capacity_param.index(), + actual_length_param_index: actual_length_param.map(|index| index.index()), + unit: project_count_unit(*unit), + sizing, + } + } + CountRelation::EnumeratorNext { + capacity_param, + fetched_param, + fetched_optional_for_single, + } => TypedBufferRelation::EnumeratorNext { + capacity_param_index: capacity_param.index(), + fetched_param_index: fetched_param.index(), + fetched_optional_for_single: *fetched_optional_for_single, + }, + CountRelation::CalleeAllocated { count_param, unit } => { + TypedBufferRelation::CalleeAllocated { + count_param_index: count_param.index(), + unit: project_count_unit(*unit), + } + } + }; + plans.push(TypedBufferPlan { + buffer_param_index, + element, + relation, + }); + } + Ok(plans) +} + +fn project_enumerator_interface_ref( + semantic: &SemanticComInterface, + method: &ComMethodContract, + buffer_param_index: usize, +) -> Result, String> { + let param = method + .params() + .get(buffer_param_index) + .ok_or_else(|| "EnumeratorNext buffer index is outside the method".to_string())?; + let definition = semantic + .type_definition(param.abi_type()) + .map_err(|error| error.to_string())?; + let ComAbiType::CountedBuffer { + element: BufferElement::Typed(element), + .. + } = definition.abi() + else { + return Ok(None); + }; + project_interface_ref_for_type(semantic, *element) +} + +fn project_buffer_interface_ref( + semantic: &SemanticComInterface, + method: &ComMethodContract, + buffer_param_index: usize, +) -> Result, String> { + project_enumerator_interface_ref(semantic, method, buffer_param_index) +} + +fn project_interface_ref_for_type( + semantic: &SemanticComInterface, + element: super::model::ids::TypeId, +) -> Result, String> { + let element = semantic + .type_definition(element) + .map_err(|error| error.to_string())?; + let ComAbiType::ComInterface { iid } = element.abi() else { + return Ok(None); + }; + if iid.as_bytes() + == &[ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x46, + ] + { + return Ok(None); + } + let name = element.native_name().ok_or_else(|| { + "EnumeratorNext interface element has no exact native identity".to_string() + })?; + Ok(Some(ProjectedInterfaceRef { + namespace: name.namespace().into(), + name: name.name().into(), + })) +} + +fn project_count_unit(unit: CountUnit) -> ProjectedBufferCountUnit { + match unit { + CountUnit::Elements => ProjectedBufferCountUnit::Elements, + CountUnit::Bytes => ProjectedBufferCountUnit::Bytes, + } +} + +fn project_shared_counts( + method: &ComMethodContract, + buffers: &[TypedBufferPlan], +) -> Result, String> { + let mut by_count = std::collections::BTreeMap::>::new(); + for plan in buffers { + let count_param_index = match plan.relation { + TypedBufferRelation::Input { + count_param_index, .. + } => count_param_index, + TypedBufferRelation::CallerOutput { + capacity_param_index, + .. + } => capacity_param_index, + TypedBufferRelation::EnumeratorNext { + capacity_param_index, + .. + } => capacity_param_index, + TypedBufferRelation::CalleeAllocated { + count_param_index, .. + } => count_param_index, + }; + by_count.entry(count_param_index).or_default().push(plan); + } + let mut groups = Vec::new(); + for (count_param_index, plans) in by_count { + if plans.len() == 1 { + continue; + } + let input_units = plans + .iter() + .map(|plan| match plan.relation { + TypedBufferRelation::Input { + count_param_index: count, + actual_length_param_index: None, + unit, + } if count == count_param_index => Some(unit), + _ => None, + }) + .collect::>>(); + if input_units.is_some_and(|units| { + units + .first() + .is_some_and(|first| units.iter().all(|unit| unit == first)) + }) { + continue; + } + if plans.len() == 2 + && plans + .iter() + .any(|plan| matches!(plan.element, ComType::StringArray { .. })) + { + let mut string_input = None; + let mut scalar_output = None; + for plan in &plans { + match (&plan.element, &plan.relation) { + ( + ComType::StringArray { .. }, + TypedBufferRelation::Input { + count_param_index: count, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + }, + ) if *count == count_param_index && string_input.is_none() => { + string_input = Some(plan.buffer_param_index); + } + ( + element, + TypedBufferRelation::CallerOutput { + capacity_param_index, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + sizing: TypedBufferSizing::SingleCall, + }, + ) if *capacity_param_index == count_param_index + && is_plain_array_output_element(element) + && scalar_output.is_none() => + { + scalar_output = Some(plan.buffer_param_index); + } + _ => {} + } + } + if let (Some(string_input_param_index), Some(scalar_output_param_index)) = + (string_input, scalar_output) + { + groups.push(SharedCountPlan::StringInputScalarOutput { + count_param_index, + string_input_param_index, + scalar_output_param_index, + }); + continue; + } + return Err(format!( + "{}: count parameter {count_param_index} has an unsupported string-array group", + method.name() + )); + } + if plans + .iter() + .any(|plan| matches!(plan.element, ComType::StringArray { .. })) + { + return Err(format!( + "{}: count parameter {count_param_index} has an unsupported string-array group", + method.name() + )); + } + let mut parallel_inputs = Vec::new(); + let mut parallel_outputs = Vec::new(); + let parallel = plans.iter().all(|plan| match plan.relation { + TypedBufferRelation::Input { + count_param_index: count, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + } if count == count_param_index => { + parallel_inputs.push(plan.buffer_param_index); + true + } + TypedBufferRelation::CallerOutput { + capacity_param_index: count, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + sizing: TypedBufferSizing::SingleCall, + } if count == count_param_index => { + parallel_outputs.push(plan.buffer_param_index); + true + } + _ => false, + }); + if parallel && !parallel_inputs.is_empty() && !parallel_outputs.is_empty() { + groups.push(SharedCountPlan::Parallel { + count_param_index, + input_param_indices: parallel_inputs, + output_param_indices: parallel_outputs, + }); + continue; + } + if plans.len() != 2 { + return Err(format!( + "{}: count parameter {count_param_index} describes an ambiguous buffer group", + method.name() + )); + } + let mut string_input = None; + let mut scalar_output = None; + for plan in plans { + match (&plan.element, &plan.relation) { + ( + ComType::StringArray { .. }, + TypedBufferRelation::Input { + count_param_index: count, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + }, + ) if *count == count_param_index && string_input.is_none() => { + string_input = Some(plan.buffer_param_index); + } + ( + element, + TypedBufferRelation::CallerOutput { + capacity_param_index, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Elements, + sizing: TypedBufferSizing::SingleCall, + }, + ) if *capacity_param_index == count_param_index + && is_plain_array_output_element(element) + && scalar_output.is_none() => + { + scalar_output = Some(plan.buffer_param_index); + } + _ => { + return Err(format!( + "{}: count parameter {count_param_index} describes unrelated buffers", + method.name() + )); + } + } + } + groups.push(SharedCountPlan::StringInputScalarOutput { + count_param_index, + string_input_param_index: string_input.ok_or_else(|| { + format!( + "{}: shared count {count_param_index} has no string input array", + method.name() + ) + })?, + scalar_output_param_index: scalar_output.ok_or_else(|| { + format!( + "{}: shared count {count_param_index} has no plain scalar output array", + method.name() + ) + })?, + }); + } + Ok(groups) +} + +fn is_plain_array_output_element(typ: &ComType) -> bool { + matches!( + typ, + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Enum { .. } + | ComType::ScalarAlias { .. } + ) +} + +fn is_supported_buffer_element(typ: &ComType) -> bool { + matches!( + typ, + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Guid + | ComType::Enum { .. } + | ComType::ScalarAlias { .. } + | ComType::NativePod { .. } + | ComType::StringArray { .. } + | ComType::ManagedInterface { .. } + | ComType::Bstr + | ComType::Variant + | ComType::CoTaskMemWideString + ) +} + +fn is_owning_array_output_element(typ: &ComType) -> bool { + matches!( + typ, + ComType::ManagedInterface { .. } + | ComType::Bstr + | ComType::Variant + | ComType::CoTaskMemWideString + ) +} + +fn project_string_buffer( + semantic: &SemanticComInterface, + method: &ComMethodContract, +) -> Result, String> { + let mut plans = Vec::new(); + for (buffer_param_index, param) in method.params().iter().enumerate() { + let definition = semantic + .type_definition(param.abi_type()) + .map_err(|error| error.to_string())?; + let ComAbiType::CountedBuffer { element, .. } = definition.abi() else { + continue; + }; + let BufferElement::Character(element_encoding) = element else { + continue; + }; + if param.direction() == Direction::In { + continue; + } + let (capacity_param, encoding) = match param.count() { + Some(CountRelation::CallerCapacity { + capacity_param, + actual_length_param: None, + unit: CountUnit::Elements, + sizing: BufferSizing::SingleCall, + }) => ( + capacity_param.index(), + project_string_encoding(*element_encoding), + ), + _ => { + return Err(format!( + "{}: caller-sized native buffers are not supported (`{}`)", + method.name(), + param.name() + )); + } + }; + if encoding == StringEncoding::Ansi { + return Err(format!( + "{}: caller-owned ANSI output buffers are not yet decoded safely", + method.name() + )); + } + let optional_param_indices = if method + .params() + .iter() + .skip(capacity_param + 1) + .all(|param| !param.direction().is_input()) + { + vec![capacity_param] + } else { + Vec::new() + }; + plans.push(StringBufferPlan { + buffer_param_index, + count_param_index: capacity_param, + encoding, + optional_param_indices, + }); + } + match plans.len() { + 0 => Ok(None), + 1 => Ok(plans.pop()), + _ => Err(format!( + "{}: multiple caller-owned string buffers are not supported", + method.name() + )), + } +} + +fn result_conversion( + param: &ComParamContract, + typ: &ComType, + dynamic_iid_output: bool, +) -> Result { + if dynamic_iid_output { + return match (param.ownership(), param.cleanup()) { + (ComOwnership::ComOwned, Cleanup::ComRelease) => { + Ok(ResultConversion::DynamicIidAdoption) + } + _ => Err(format!( + "{}: dynamic-IID output lacks COM ownership", + param.name() + )), + }; + } + match (param.ownership(), param.cleanup()) { + (ComOwnership::Borrowed, Cleanup::None) + if matches!( + typ, + ComType::PointerAlias { + kind: PointerAliasKind::HandleValue, + .. + } + ) => + { + Ok(ResultConversion::BorrowedHandle) + } + (ComOwnership::Borrowed, Cleanup::None) => Ok(ResultConversion::Value), + (ComOwnership::ComOwned, Cleanup::ComRelease) + if matches!(typ, ComType::ManagedInterface { .. }) => + { + Ok(ResultConversion::ManagedCom) + } + (ComOwnership::BstrOwned, Cleanup::SysFreeString) if matches!(typ, ComType::Bstr) => { + Ok(ResultConversion::Bstr) + } + (ComOwnership::BstrReplaced, Cleanup::SysFreeString) if matches!(typ, ComType::Bstr) => { + Ok(ResultConversion::Bstr) + } + (ComOwnership::CoTaskMemOwned, Cleanup::CoTaskMemFree) => match typ { + ComType::PointerAlias { + kind: PointerAliasKind::StringPointer(encoding), + .. + } => Ok(ResultConversion::CoTaskMemString(*encoding)), + ComType::RawPointer + | ComType::PointerAlias { + kind: PointerAliasKind::DataPointer, + .. + } => Ok(ResultConversion::CoTaskMemData), + _ => Err(format!( + "{}: CoTaskMem ownership requires a data or string pointer", + param.name() + )), + }, + (ComOwnership::HStringOwned, Cleanup::WindowsDeleteString) + if matches!(typ, ComType::HString) => + { + Ok(ResultConversion::HString) + } + (ComOwnership::VariantOwned, Cleanup::VariantClear) if matches!(typ, ComType::Variant) => { + Ok(ResultConversion::Variant) + } + (ComOwnership::SafeArrayOwned, Cleanup::SafeArrayDestroy) + if matches!(typ, ComType::SafeArray { .. }) => + { + Ok(ResultConversion::SafeArray) + } + (ComOwnership::PropVariantOwned, Cleanup::PropVariantClear) + if matches!(typ, ComType::PropVariant) => + { + Ok(ResultConversion::PropVariant) + } + (ComOwnership::ExcepInfoOwned, Cleanup::ExcepInfoClear) + if matches!(typ, ComType::ExcepInfo) => + { + Ok(ResultConversion::ExcepInfo) + } + (ownership, cleanup) => Err(format!( + "{}: unsupported projected ownership {ownership:?} with cleanup {cleanup:?}", + param.name() + )), + } +} + +fn detect_interop_target( + validated: &ValidatedComInterface<'_>, + winmd_paths: &str, +) -> Result, String> { + let meta = validated.metadata(); + if !meta.interface.name.ends_with("Interop") + || !validated.semantic().methods().iter().any(|method| { + method.name() == "GetForWindow" && method.dynamic_iid_contract().is_some() }) { return Ok(None); @@ -792,147 +2412,673 @@ fn detect_interop_target( Ok(Some((class_name, namespace, iid))) } -fn unsupported_error(unsupported: UnsupportedComType, context: &str) -> String { - match unsupported { - UnsupportedComType::Array => format!( - "{context}: native arrays require an explicit count and element-ownership projection; \ - raw-pointer fallback is not allowed" - ), - UnsupportedComType::ParameterizedInterface { namespace, name } => format!( - "{context}: parameterized interface `{namespace}.{name}` requires a computed closed IID \ - and managed ownership projection; raw-pointer fallback is not allowed" - ), - UnsupportedComType::AsyncInterface => format!( - "{context}: async interface requires a computed closed IID and managed ownership \ - projection; raw-pointer fallback is not allowed" - ), - UnsupportedComType::Delegate { namespace, name } => format!( - "{context}: delegate `{namespace}.{name}` requires a managed callback projection; \ - raw-pointer fallback is not allowed" - ), - UnsupportedComType::NativeStructLayout { namespace, name } => { - format!("{context}: struct `{namespace}.{name}` requires native layout projection") +fn project_string_encoding(encoding: SemanticStringEncoding) -> StringEncoding { + match encoding { + SemanticStringEncoding::Utf16 => StringEncoding::Wide, + SemanticStringEncoding::Ansi => StringEncoding::Ansi, + } +} + +fn is_scalar_in_out(typ: &ComType) -> bool { + matches!( + typ, + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Enum { .. } + | ComType::ScalarAlias { .. } + | ComType::Bstr + | ComType::NativePod { .. } + | ComType::NativePodPointer { .. } + ) +} + +fn is_supported_direct_return(typ: &ComType) -> bool { + matches!( + typ, + ComType::Primitive(_) + | ComType::NativeIsize + | ComType::NativeUsize + | ComType::Win32Bool + | ComType::HResult + | ComType::Enum { .. } + | ComType::ScalarAlias { .. } + | ComType::PointerAlias { .. } + ) +} + +fn semantic_type_name( + semantic: &SemanticComInterface, + abi_type: super::model::ids::TypeId, +) -> String { + semantic + .type_definition(abi_type) + .map(semantic_type_definition_name) + .unwrap_or_else(|_| format!("type#{}", abi_type.index())) +} + +fn semantic_type_definition_name(definition: &ComTypeDefinition) -> String { + definition.native_name().map_or_else( + || format!("{:?}", definition.abi()), + |name| format!("{}.{}", name.namespace(), name.name()), + ) +} + +pub(super) fn format_guid(bytes: &[u8; 16]) -> String { + let hex = bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} + +fn input_arity(method: &ProjectedComMethod) -> usize { + method + .params + .iter() + .filter(|param| param.surface_input) + .count() +} + +fn group_overloads( + methods: Vec, + interface_name: &str, +) -> Result, String> { + let mut order = Vec::new(); + let mut groups: std::collections::HashMap> = + std::collections::HashMap::new(); + for (index, method) in methods.iter().enumerate() { + groups + .entry(method.camel_name.clone()) + .or_insert_with(|| { + order.push(method.camel_name.clone()); + Vec::new() + }) + .push(index); + } + + let mut overloads = vec![None; methods.len()]; + for name in &order { + let indices = &groups[name]; + if indices.len() < 2 { + continue; } - UnsupportedComType::UnknownPointerAlias { namespace, name } => format!( - "{context}: pointer-shaped typedef `{namespace}.{name}` has no explicit semantic \ - classification; raw-pointer fallback is not allowed" - ), - UnsupportedComType::UnresolvedInterface { namespace, name } => format!( - "{context}: interface `{namespace}.{name}` has no resolvable IID; \ - pass the metadata that defines it via --ref instead of projecting it as a raw pointer" - ), - UnsupportedComType::UnresolvedRuntimeClass { namespace, name } => format!( - "{context}: runtime class `{namespace}.{name}` has no resolvable default interface; \ - pass the metadata that defines it via --ref" - ), - UnsupportedComType::UnknownOwnership { type_name } => { - format!("{context}: {type_name} has no ownership projection") + for &index in indices { + let method = &methods[index]; + if method.kind != ProjectedComMethodKind::Normal { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one is a synthesized/dynamic-IID method, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } + if method.string_buffer.is_some() || !method.typed_buffers.is_empty() { + return Err(format!( + "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ + because at least one uses a projected buffer, which is not a \ + safely dispatchable JS shape", + indices.len() + )); + } } - UnsupportedComType::UnsupportedDirectReturn { type_name } => { - format!("{context}: unsupported direct native return type {type_name}") + + let mut arity_buckets: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for &index in indices { + arity_buckets + .entry(input_arity(&methods[index])) + .or_default() + .push(index); } - UnsupportedComType::Unknown => { - format!("{context}: unsupported Classic-COM type") + + for (arity, bucket) in arity_buckets { + if bucket.len() == 1 { + overloads[bucket[0]] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), + dispatch: OverloadDispatch::Arity, + }); + continue; + } + let key_param_index = (0..arity).find(|&key_index| { + let mut seen: Vec = Vec::new(); + bucket.iter().all(|&index| { + let (_, param) = input_params_of(&methods[index])[key_index]; + match dispatch_shape(¶m.typ) { + Some(shape) if !seen.contains(&shape) => { + seen.push(shape); + true + } + _ => false, + } + }) + }); + let Some(key_param_index) = key_param_index else { + return Err(format!( + "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ + position has mutually distinguishable JS shapes (arity/type/category); \ + overload dispatch cannot be safely generated", + bucket.len() + )); + }; + for &index in &bucket { + let (_, param) = input_params_of(&methods[index])[key_param_index]; + let shape = + dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); + overloads[index] = Some(OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[index].vtable_index), + dispatch: OverloadDispatch::ArityAndShape { + key_param_index, + shape, + }, + }); + } } } + + Ok(methods + .into_iter() + .zip(overloads) + .map(|(mut method, overload)| { + method.overload = overload; + method + }) + .collect()) +} + +fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComParam)> { + method + .params + .iter() + .enumerate() + .filter(|(_, param)| param.surface_input) + .collect() } #[cfg(test)] mod tests { use super::*; - use crate::com_metadata::{InterfaceMeta, MethodMeta, ParamMeta}; - - fn interface(method: MethodMeta) -> ComInterfaceMeta { - ComInterfaceMeta { - interface: InterfaceMeta { - name: "ITest".into(), - namespace: "Tests".into(), - iid: "00000000-0000-0000-0000-000000000001".into(), - methods: vec![method], - ..Default::default() + + #[test] + fn guid_format_preserves_canonical_semantic_identity() { + assert_eq!( + format_guid(&[ + 0x3a, 0x3d, 0xcd, 0x6c, 0x3e, 0xab, 0x43, 0xdc, 0xbc, 0xde, 0x45, 0x67, 0x1c, 0xe8, + 0x00, 0xc8, + ]), + "3a3dcd6c-3eab-43dc-bcde-45671ce800c8" + ); + } + + #[test] + fn dynamic_iid_projection_preserves_explicit_parameter_indices() { + assert_eq!( + project_dynamic_method_kind("Resolve", Some((3, 1)), None), + ProjectedComMethodKind::CallerSuppliedDynamicIid { + iid_param_index: 3, + output_param_index: 1, + } + ); + assert_eq!( + project_dynamic_method_kind( + "GetForWindow", + Some((2, 5)), + Some("11111111-2222-3333-4444-555555555555"), + ), + ProjectedComMethodKind::SynthesizedGetForWindow { + iid_param_index: 2, + output_param_index: 5, + target_iid: "11111111-2222-3333-4444-555555555555".into(), + } + ); + } + + #[test] + fn validated_semantic_projection_only_diverges_for_pod_upgrades() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + + let validated = model::validate_interface(&meta).unwrap(); + let mut semantic = project_validated_interface(&validated, &winmd).unwrap(); + let mut legacy = legacy_diagnostics::project_com_interface_for_test(&meta, &winmd).unwrap(); + let semantic_clip = semantic + .methods + .iter() + .find(|method| method.name == "SetThumbnailClip") + .unwrap(); + let legacy_clip = legacy + .methods + .iter() + .find(|method| method.name == "SetThumbnailClip") + .unwrap(); + assert!(matches!( + semantic_clip.params[1].typ, + ComType::NativePodPointer { .. } + )); + assert_eq!(legacy_clip.params[1].typ, ComType::RawPointer); + + for name in ["ThumbBarAddButtons", "ThumbBarUpdateButtons"] { + let semantic_method = semantic + .methods + .iter() + .find(|method| method.name == name) + .unwrap(); + assert!(matches!( + semantic_method + .params + .iter() + .find(|param| param.name == "pButton") + .unwrap() + .typ, + ComType::TypedBuffer { .. } + )); + } + + semantic.methods.retain(|method| { + !matches!( + method.name.as_str(), + "SetThumbnailClip" | "ThumbBarAddButtons" | "ThumbBarUpdateButtons" + ) + }); + legacy.methods.retain(|method| { + !matches!( + method.name.as_str(), + "SetThumbnailClip" | "ThumbBarAddButtons" | "ThumbBarUpdateButtons" + ) + }); + assert_eq!(semantic, legacy); + } + + #[test] + fn shell_link_get_path_projects_nullable_in_out_pod() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "IShellLinkW", + ) + .unwrap(); + let validated = model::validate_interface(&meta).unwrap(); + let projected = project_validated_interface(&validated, &winmd).unwrap(); + let get_path = projected + .methods + .iter() + .find(|method| method.name == "GetPath") + .unwrap(); + let pfd = get_path + .params + .iter() + .find(|param| param.name == "pfd") + .unwrap(); + assert!(pfd.nullable); + assert!(matches!(pfd.typ, ComType::NativePodPointer { .. })); + } + + #[test] + fn bstr_inputs_outputs_and_replacements_project_as_strings() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Web.InternetExplorer", + "ITargetNotify2", + ) + .unwrap(); + let projected = project_com_interface(&meta, &winmd).unwrap(); + let method = projected + .methods + .iter() + .find(|method| method.name == "GetOptionString") + .unwrap(); + let (index, replacement) = method + .params + .iter() + .enumerate() + .find(|(_, parameter)| parameter.direction == ComParamDirection::InOut) + .unwrap(); + assert_eq!(replacement.typ, ComType::Bstr); + assert!(replacement.surface_input); + assert!(replacement.surface_result); + assert!(!replacement.nullable); + assert!(method.results.iter().any(|result| { + result.source == ResultSource::Param(index) + && result.conversion == ResultConversion::Bstr + })); + + let input_meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.System.TaskScheduler", + "IExecAction2", + ) + .unwrap(); + let input_projected = project_com_interface(&input_meta, &winmd).unwrap(); + assert!(input_projected.methods.iter().any(|method| { + method.params.iter().any(|parameter| { + parameter.direction == ComParamDirection::In + && parameter.typ == ComType::Bstr + && parameter.surface_input + && !parameter.surface_result + }) + })); + } + + #[test] + fn documented_bstr_output_overrides_project_or_fail_on_later_contracts() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let photo = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Media.PictureAcquisition", + "IPhotoAcquireDeviceSelectionDialog", + ) + .unwrap(); + let photo = model::validate_interface(&photo).unwrap(); + let error = project_validated_interface(&photo, &winmd).unwrap_err(); + assert!(error.contains("pnDeviceType"), "{error}"); + + let recorder = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Storage.Imapi", + "IDiscRecorder", + ) + .unwrap(); + let recorder = model::validate_interface(&recorder).unwrap(); + let projected = project_validated_interface(&recorder, &winmd).unwrap(); + let method = projected + .methods + .iter() + .find(|method| method.name == "GetDisplayNames") + .unwrap(); + let outputs = method + .params + .iter() + .filter(|parameter| { + parameter.direction == ComParamDirection::Out && parameter.typ == ComType::Bstr + }) + .count(); + assert_eq!(outputs, 3); + assert!(method.params.iter().all(|parameter| { + parameter.typ != ComType::Bstr + || parameter.direction != ComParamDirection::Out + || (!parameter.surface_input && !parameter.nullable) + })); + } + + #[test] + fn scalar_bstr_pointer_inputs_remain_fail_closed() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let mut meta = crate::com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.UI.Shell", + "IFileSearchBand", + ) + .unwrap(); + let method_index = meta + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "SetSearchParameters") + .unwrap(); + meta.raw_methods = Some(vec![ + meta.raw_methods.as_ref().unwrap()[method_index].clone(), + ]); + meta.interface.methods = vec![meta.interface.methods[method_index].clone()]; + meta.own_methods_start = 0; + let error = project_com_interface(&meta, &winmd).unwrap_err(); + assert!( + error.contains("BSTR") || error.contains("string"), + "{error}" + ); + + let mut nested = meta; + nested.raw_methods.as_mut().unwrap()[0].params[0] + .typ + .pointer_depth = 2; + let error = project_com_interface(&nested, &winmd).unwrap_err(); + assert!( + error.contains("BSTR") || error.contains("string"), + "{error}" + ); + } + + #[test] + fn native_pod_surface_names_reject_namespace_collisions() { + let architecture = NativePodArchitectureLayout { + size: 4, + alignment: 4, + fields: Vec::new(), + }; + let pod = |namespace: &str| ComType::NativePod { + layout: NativePodLayout { + namespace: namespace.into(), + name: "COLLISION".into(), + x86: architecture.clone(), + x64: architecture.clone(), + arm64: architecture.clone(), }, - base_offset: 3, + }; + let method = |name: &str, typ: ComType, slot| ProjectedComMethod { + name: name.into(), + camel_name: name.into(), + vtable_index: slot, + params: vec![ProjectedComParam { + name: "value".into(), + typ, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }; + let interface = ProjectedComInterface { + name: "ITest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-c000-000000000046".into(), is_iunknown_rooted: true, - base_chain: vec!["IUnknown".into()], - coclass_clsid: None, - coclass_name: None, - own_methods_start: 3, + methods: vec![ + method("first", pod("Contoso.One"), 3), + method("second", pod("Contoso.Two"), 4), + ], + activation: ActivationPlan::None, referenced_enums: Vec::new(), - } + }; + + let error = validate_projected_surface_names(&interface).unwrap_err(); + assert!(error.contains("Contoso.One.COLLISION")); + assert!(error.contains("Contoso.Two.COLLISION")); } #[test] - fn unsupported_type_fails_during_projection() { - let method = MethodMeta { - name: "Bad".into(), - params: vec![ParamMeta { - name: "values".into(), - typ: TypeMeta::Array(Box::new(TypeMeta::I32)), - direction: ParamDirection::In, - }], - ..Default::default() + fn specialized_buffer_rendering_rejects_uncomposable_plans() { + let string = StringBufferPlan { + buffer_param_index: 0, + count_param_index: 1, + encoding: StringEncoding::Wide, + optional_param_indices: Vec::new(), + }; + let input = TypedBufferPlan { + buffer_param_index: 2, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::Input { + count_param_index: 3, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Bytes, + }, }; assert!( - project_com_interface(&interface(method), "") - .unwrap_err() - .contains("raw-pointer fallback is not allowed") + validate_buffer_plan_composition("Mixed", Some(&string), &[input.clone()]).is_err() ); + + let two_call = TypedBufferPlan { + buffer_param_index: 0, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::CallerOutput { + capacity_param_index: 1, + actual_length_param_index: Some(2), + unit: ProjectedBufferCountUnit::Bytes, + sizing: TypedBufferSizing::TwoCall { max_retries: 2 }, + }, + }; + assert!(validate_buffer_plan_composition("One", None, &[two_call.clone()]).is_ok()); + assert!(validate_buffer_plan_composition("Many", None, &[two_call, input]).is_err()); } #[test] - fn by_value_guid_is_not_dynamic_iid() { - let method = MethodMeta { - name: "Get".into(), - params: vec![ - ParamMeta { - name: "riid".into(), - typ: TypeMeta::Guid, - direction: ParamDirection::In, - }, - ParamMeta { - name: "result".into(), - typ: TypeMeta::Object, - direction: ParamDirection::Out, - }, - ], - return_type: Some(TypeMeta::Struct { - namespace: "Windows.Win32.Foundation".into(), - name: "HRESULT".into(), - fields: Vec::new(), - }), - ..Default::default() + fn dynamic_iid_rejects_hidden_string_buffers() { + let string = StringBufferPlan { + buffer_param_index: 0, + count_param_index: 1, + encoding: StringEncoding::Wide, + optional_param_indices: Vec::new(), }; assert!( - project_com_interface(&interface(method), "") + validate_dynamic_iid_buffers("Resolve", true, Some(&string), &[]) .unwrap_err() - .contains("untyped pointer output") + .contains("hidden string/buffer") ); + assert!(validate_dynamic_iid_buffers("Resolve", false, Some(&string), &[]).is_ok()); + let fixed = TypedBufferPlan { + buffer_param_index: 0, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::CallerOutput { + capacity_param_index: 1, + actual_length_param_index: Some(2), + unit: ProjectedBufferCountUnit::Bytes, + sizing: TypedBufferSizing::FixedCapacity, + }, + }; + assert!(validate_buffer_plan_composition("Fixed", None, &[fixed]).is_ok()); } #[test] - fn owned_output_without_a_known_cleanup_fails_before_rendering() { - let method = MethodMeta { - name: "GetName".into(), - params: vec![ParamMeta { - name: "name".into(), - typ: TypeMeta::Struct { - namespace: "Windows.Win32.Foundation".into(), - name: "BSTR".into(), - fields: Vec::new(), + fn projected_surface_names_reject_cross_category_and_qualified_collisions() { + let mut interface = ProjectedComInterface { + name: "ITest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-c000-000000000046".into(), + is_iunknown_rooted: true, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: vec![ + ProjectedComEnum { + namespace: "Contoso.One".into(), + name: "MODE".into(), + underlying: ComEnumUnderlying::I32, + members: Vec::new(), }, - direction: ParamDirection::Out, + ProjectedComEnum { + namespace: "Contoso.Two".into(), + name: "MODE".into(), + underlying: ComEnumUnderlying::I32, + members: Vec::new(), + }, + ], + }; + assert!(validate_projected_surface_names(&interface).is_err()); + + interface.referenced_enums.pop(); + interface.methods.push(ProjectedComMethod { + name: "useMode".into(), + camel_name: "useMode".into(), + vtable_index: 3, + params: vec![ProjectedComParam { + name: "mode".into(), + typ: ComType::ScalarAlias { + namespace: "Contoso.Values".into(), + name: "MODE".into(), + underlying: ComScalarRepr::Primitive(ComPrimitive::I32), + }, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }); + assert!(validate_projected_surface_names(&interface).is_err()); + } + + #[test] + fn coclass_rejects_conflicting_enum_filenames() { + let interface = |name: &str, namespace: &str| ProjectedComInterface { + name: name.into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-c000-000000000046".into(), + is_iunknown_rooted: true, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: vec![ProjectedComEnum { + namespace: namespace.into(), + name: "STATE".into(), + underlying: ComEnumUnderlying::I32, + members: Vec::new(), }], - return_type: Some(TypeMeta::Struct { - namespace: "Windows.Win32.Foundation".into(), - name: "HRESULT".into(), - fields: Vec::new(), - }), - ..Default::default() }; assert!( - project_com_interface(&interface(method), "") - .unwrap_err() - .contains("BSTR output has no ownership projection") + validate_coclass_enum_files( + "Tests", + "Class", + &[ + interface("IFirst", "Contoso.One"), + interface("ISecond", "Contoso.Two"), + ], + ) + .is_err() ); } } diff --git a/tools/dynwinrt-codegen/src/com_borrowed_handle_registry.rs b/tools/dynwinrt-codegen/src/com_borrowed_handle_registry.rs new file mode 100644 index 00000000..81458694 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_borrowed_handle_registry.rs @@ -0,0 +1,408 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct BorrowedHwndOutputEvidence { + pub declaring_namespace: &'static str, + pub declaring_interface: &'static str, + pub declaring_iid: &'static str, + pub method_name: &'static str, + pub vtable_index: usize, + pub parameter_count: usize, + pub parameter_index: usize, + pub parameter_name: &'static str, + pub optional: bool, + pub reason: &'static str, + pub citation: &'static str, +} + +const BORROWED_HWND_OUTPUTS: &[BorrowedHwndOutputEvidence] = &[ + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Devices.ImageAcquisition", + declaring_interface: "IWiaAppErrorHandler", + declaring_iid: "6c16186c-d0a6-400c-80f4-d26986a0e734", + method_name: "GetWindow", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as the existing WIA error-handler dialog HWND, which may be NULL and must remain valid for the transfer; the caller does not acquire window ownership", + citation: "https://learn.microsoft.com/previous-versions/windows/desktop/wia/-wia-iwiaapperrorhandler-getwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.PictureAcquisition", + declaring_interface: "IPhotoProgressDialog", + declaring_iid: "00f246f9-0750-4f08-9381-2cd8e906a4ae", + method_name: "GetWindow", + vtable_index: 4, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwndProgressDialog", + optional: false, + reason: "Microsoft documents this getter as retrieving the progress dialog box handle; it does not create or transfer ownership of the dialog", + citation: "https://learn.microsoft.com/windows/win32/api/photoacquire/nf-photoacquire-iphotoprogressdialog-getwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow", + declaring_interface: "IOverlay", + declaring_iid: "56a868a1-0ad4-11ce-b03a-0020af0ba770", + method_name: "GetWindowHandle", + vtable_index: 8, + parameter_count: 1, + parameter_index: 0, + parameter_name: "pHwnd", + optional: false, + reason: "Microsoft documents this as retrieving the clipping window handle already associated with the overlay; it does not create or transfer ownership of the window", + citation: "https://learn.microsoft.com/windows/win32/api/strmif/nf-strmif-ioverlay-getwindowhandle", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IMSVidCtl", + declaring_iid: "b0edf162-910a-11d2-b632-00c04f79498e", + method_name: "get_Window", + vtable_index: 15, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this property as retrieving the existing video control window handle; the caller does not acquire ownership of that window", + citation: "https://learn.microsoft.com/windows/win32/api/msvidctl/nf-msvidctl-imsvidctl-get_window", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IMSVidRect", + declaring_iid: "7f5000a6-a440-47ca-8acc-c0e75531a2c2", + method_name: "get_HWnd", + vtable_index: 15, + parameter_count: 1, + parameter_index: 0, + parameter_name: "HWndVal", + optional: false, + reason: "Microsoft documents this property as retrieving the window handle represented by the existing video rectangle; it does not create or transfer the window", + citation: "https://learn.microsoft.com/windows/win32/api/segment/nf-segment-imsvidrect-get_hwnd", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.MediaFoundation", + declaring_interface: "IMFPMediaPlayer", + declaring_iid: "a714590a-58af-430a-85bf-44f5ec838d85", + method_name: "GetVideoWindow", + vtable_index: 31, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwndVideo", + optional: false, + reason: "Microsoft documents this as retrieving the media player's current video window; it is an existing caller-configured window and ownership is not transferred", + citation: "https://learn.microsoft.com/windows/win32/api/mfplay/nf-mfplay-imfpmediaplayer-getvideowindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.Media.MediaFoundation", + declaring_interface: "IMFVideoDisplayControl", + declaring_iid: "a490b1e4-ab84-4d31-a1b2-181e03b1077a", + method_name: "GetVideoWindow", + vtable_index: 10, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwndVideo", + optional: false, + reason: "Microsoft documents this as retrieving the video window already set on the display control; it does not create or transfer ownership of the window", + citation: "https://learn.microsoft.com/windows/win32/api/evr/nf-evr-imfvideodisplaycontrol-getvideowindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.Mmc", + declaring_interface: "IConsole", + declaring_iid: "43136eb1-d36c-11cf-adbc-00aa00a80033", + method_name: "GetMainWindow", + vtable_index: 12, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as retrieving MMC's existing main frame window handle, not creating a caller-owned window", + citation: "https://learn.microsoft.com/windows/win32/api/mmc/nf-mmc-iconsole-getmainwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.Ole", + declaring_interface: "IOleWindow", + declaring_iid: "00000114-0000-0000-c000-000000000046", + method_name: "GetWindow", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as retrieving an existing frame, document, parent, or in-place activation window; ownership remains with the participant that created that window", + citation: "https://learn.microsoft.com/windows/win32/api/oleidl/nf-oleidl-iolewindow-getwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.WinRT", + declaring_interface: "ICoreWindowInterop", + declaring_iid: "45d64a29-a63e-4cb6-b498-5781d298cb4f", + method_name: "get_WindowHandle", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "hwnd", + optional: false, + reason: "Microsoft documents this read-only property as obtaining the HWND of the existing CoreWindow; it does not transfer window lifetime", + citation: "https://learn.microsoft.com/windows/win32/api/corewindow/nf-corewindow-icorewindowinterop-get_windowhandle", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.WinRT", + declaring_interface: "IShareWindowCommandEventArgsInterop", + declaring_iid: "6571a721-643d-43d4-aca4-6b6f5f30f1ad", + method_name: "GetWindow", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "value", + optional: false, + reason: "Microsoft documents this as receiving the window identifier carried by the event arguments, with no creation or ownership transfer", + citation: "https://learn.microsoft.com/windows/win32/api/sharewindowcommandsourceinterop/nf-sharewindowcommandsourceinterop-isharewindowcommandeventargsinterop-getwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.WinRT.Xaml", + declaring_interface: "IDesktopWindowXamlSourceNative", + declaring_iid: "3cbcf1bf-2f76-4e9c-96ab-e84b37972554", + method_name: "get_WindowHandle", + vtable_index: 4, + parameter_count: 1, + parameter_index: 0, + parameter_name: "hWnd", + optional: false, + reason: "Microsoft documents this as the parent UI element HWND associated with the current XAML source instance; the associated UI element retains ownership", + citation: "https://learn.microsoft.com/windows/win32/api/windows.ui.xaml.hosting.desktopwindowxamlsource/nf-windows-ui-xaml-hosting-desktopwindowxamlsource-idesktopwindowxamlsourcenative-get_windowhandle", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.System.UpdateAgent", + declaring_interface: "IUpdateInstaller", + declaring_iid: "7b929c68-ccdc-4226-96b1-8724600b54c2", + method_name: "get_ParentHwnd", + vtable_index: 11, + parameter_count: 1, + parameter_index: 0, + parameter_name: "retval", + optional: false, + reason: "Microsoft documents this property as retrieving the existing parent window configured for the update installer; no window ownership is transferred", + citation: "https://learn.microsoft.com/windows/win32/api/wuapi/nf-wuapi-iupdateinstaller-get_parenthwnd", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationElement", + declaring_iid: "d22108aa-8ac5-49a5-837b-37bbb3d7591e", + method_name: "get_CachedNativeWindowHandle", + vtable_index: 68, + parameter_count: 1, + parameter_index: 0, + parameter_name: "retVal", + optional: false, + reason: "Microsoft documents this property as retrieving the cached native window handle of the existing UI Automation element; the element's window remains externally owned", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_cachednativewindowhandle", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationElement", + declaring_iid: "d22108aa-8ac5-49a5-837b-37bbb3d7591e", + method_name: "get_CurrentNativeWindowHandle", + vtable_index: 36, + parameter_count: 1, + parameter_index: 0, + parameter_name: "retVal", + optional: false, + reason: "Microsoft documents this property as retrieving the current native window handle of the existing UI Automation element; the element's window remains externally owned", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentnativewindowhandle", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Shell", + declaring_interface: "ICredentialProviderCredentialEvents", + declaring_iid: "fa6fa76b-66b7-4b11-95f1-86171118e816", + method_name: "OnCreatingWindow", + vtable_index: 12, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwndOwner", + optional: false, + reason: "Microsoft documents this as the Credential UI or Logon UI parent HWND that providers must borrow when parenting dialogs", + citation: "https://learn.microsoft.com/windows/win32/api/credentialprovider/nf-credentialprovider-icredentialprovidercredentialevents-oncreatingwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Shell", + declaring_interface: "ILaunchSourceViewSizePreference", + declaring_iid: "e5aa01f7-1fb8-4830-8720-4e6734cbd5f3", + method_name: "GetSourceViewToPosition", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "hwnd", + optional: false, + reason: "Microsoft documents this as retrieving the existing source application window used for positioning, without creating or transferring it", + citation: "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ilaunchsourceviewsizepreference-getsourceviewtoposition", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Shell", + declaring_interface: "IFileIsInUse", + declaring_iid: "64a1cbf0-3a1a-4461-9158-376969693950", + method_name: "GetSwitchToHWND", + vtable_index: 6, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as retrieving the existing application window to switch to; the caller observes the handle without acquiring the window", + citation: "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifileisinuse-getswitchtohwnd", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.Shell", + declaring_interface: "IPreviewHandler", + declaring_iid: "8895b1c6-b41f-4c1c-a562-0d564250836f", + method_name: "QueryFocus", + vtable_index: 8, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as the HWND returned by GetFocus on the preview handler's foreground thread, which is an observed borrowed window identity", + citation: "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ipreviewhandler-queryfocus", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.TabletPC", + declaring_interface: "ITextInputPanel", + declaring_iid: "6b6a65a5-6af3-46c2-b6ea-56cd1f80df71", + method_name: "get_AttachedEditWindow", + vtable_index: 3, + parameter_count: 1, + parameter_index: 0, + parameter_name: "AttachedEditWindow", + optional: false, + reason: "Microsoft documents this property as retrieving the edit window already attached to the text input panel; attachment does not transfer window ownership", + citation: "https://learn.microsoft.com/windows/win32/api/peninputpanel/nf-peninputpanel-itextinputpanel-get_attachededitwindow", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.TextServices", + declaring_interface: "ITfContextOwner", + declaring_iid: "aa80e80c-2021-11d2-93e0-0060b067b86e", + method_name: "GetWnd", + vtable_index: 7, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as retrieving the existing owner window associated with the text context; ownership remains with the context owner", + citation: "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextowner-getwnd", + }, + BorrowedHwndOutputEvidence { + declaring_namespace: "Windows.Win32.UI.TextServices", + declaring_interface: "ITfContextView", + declaring_iid: "2433bf8e-0f9b-435c-ba2c-180611978c30", + method_name: "GetWnd", + vtable_index: 6, + parameter_count: 1, + parameter_index: 0, + parameter_name: "phwnd", + optional: false, + reason: "Microsoft documents this as retrieving the existing window represented by the text context view; the view retains window ownership", + citation: "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-itfcontextview-getwnd", + }, +]; + +pub(crate) fn registered_borrowed_hwnd_output( + namespace: &str, + interface: &str, + iid: &str, + method: &str, + slot: usize, + parameter_index: usize, +) -> Option<&'static BorrowedHwndOutputEvidence> { + BORROWED_HWND_OUTPUTS.iter().find(|evidence| { + evidence.declaring_namespace == namespace + && evidence.declaring_interface == interface + && evidence.declaring_iid.eq_ignore_ascii_case(iid) + && evidence.method_name == method + && evidence.vtable_index == slot + && evidence.parameter_index == parameter_index + }) +} + +pub(crate) fn borrowed_hwnd_evidence_for_declaration( + namespace: &str, + interface: &str, + method: &str, + slot: usize, +) -> Option<&'static BorrowedHwndOutputEvidence> { + BORROWED_HWND_OUTPUTS.iter().find(|evidence| { + evidence.declaring_namespace == namespace + && evidence.declaring_interface == interface + && (evidence.method_name == method || evidence.vtable_index == slot) + }) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + use super::*; + + #[test] + fn registry_entries_have_unique_exact_identity_and_microsoft_citations() { + let mut identities = BTreeSet::new(); + assert_eq!(BORROWED_HWND_OUTPUTS.len(), 22); + for evidence in BORROWED_HWND_OUTPUTS { + assert!(identities.insert(( + evidence.declaring_namespace, + evidence.declaring_interface, + evidence.declaring_iid.to_ascii_lowercase(), + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + ))); + assert_eq!(evidence.declaring_iid.len(), 36); + assert!(evidence.parameter_index < evidence.parameter_count); + assert!(!evidence.optional); + assert!( + evidence + .citation + .starts_with("https://learn.microsoft.com/") + ); + assert!(!evidence.reason.is_empty()); + } + } + + #[test] + fn exact_lookup_rejects_identity_drift() { + let evidence = BORROWED_HWND_OUTPUTS + .iter() + .find(|evidence| evidence.declaring_interface == "IOleWindow") + .unwrap(); + assert!( + registered_borrowed_hwnd_output( + evidence.declaring_namespace, + evidence.declaring_interface, + evidence.declaring_iid, + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + ) + .is_some() + ); + assert!( + registered_borrowed_hwnd_output( + evidence.declaring_namespace, + evidence.declaring_interface, + "00000000-0000-0000-c000-000000000046", + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + ) + .is_none() + ); + assert!( + borrowed_hwnd_evidence_for_declaration( + evidence.declaring_namespace, + evidence.declaring_interface, + evidence.method_name, + evidence.vtable_index + 1, + ) + .is_some() + ); + } +} diff --git a/tools/dynwinrt-codegen/src/com_enumerator_registry.rs b/tools/dynwinrt-codegen/src/com_enumerator_registry.rs new file mode 100644 index 00000000..af747c57 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_enumerator_registry.rs @@ -0,0 +1,1368 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum EnumeratorElementKind { + Interface, + Struct, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum EnumeratorDirection { + Out, + InOut, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct EnumeratorContract { + pub interface_namespace: &'static str, + pub interface_name: &'static str, + pub interface_iid: &'static str, + pub next_vtable_index: usize, + pub element_namespace: &'static str, + pub element_name: &'static str, + pub element_kind: EnumeratorElementKind, + pub element_iid: Option<&'static str>, + pub citation: &'static str, +} + +use EnumeratorElementKind::{Interface, Struct, Unknown}; + +const STANDARD_NEXT: &str = + "https://learn.microsoft.com/windows/win32/api/unknwn/nf-unknwn-ienumunknown-next"; + +const fn entry( + interface_namespace: &'static str, + interface_name: &'static str, + interface_iid: &'static str, + next_vtable_index: usize, + element_namespace: &'static str, + element_name: &'static str, + element_kind: EnumeratorElementKind, + element_iid: Option<&'static str>, + citation: &'static str, +) -> EnumeratorContract { + EnumeratorContract { + interface_namespace, + interface_name, + interface_iid, + next_vtable_index, + element_namespace, + element_name, + element_kind, + element_iid, + citation, + } +} + +// DocumentationAttribute URLs are preserved where Windows.Win32 metadata +// supplies them. Entries using STANDARD_NEXT have no attached URL in +// Microsoft.Windows.SDK.Win32Metadata 71.0.14-preview; the citation supplies +// the standard Microsoft Next contract while every identity and element fact +// remains an exact Windows.Win32.winmd registry key. +const ENUMERATOR_CONTRACTS: &[EnumeratorContract] = &[ + entry( + "Windows.Win32.System.Com", + "IEnumGUID", + "0002e000-0000-0000-c000-000000000046", + 3, + "System", + "Guid", + Unknown, + None, + "https://learn.microsoft.com/windows/win32/api/objidl/nn-objidl-ienumguid", + ), + entry( + "Windows.Win32.System.Com", + "IEnumConnectionPoints", + "b196b285-bab4-101a-b69c-00aa00341d07", + 3, + "Windows.Win32.System.Com", + "IConnectionPoint", + Interface, + Some("b196b286-bab4-101a-b69c-00aa00341d07"), + "https://learn.microsoft.com/windows/win32/api/ocidl/nn-ocidl-ienumconnectionpoints", + ), + entry( + "Windows.Win32.System.Ole", + "IEnumVARIANT", + "00020404-0000-0000-c000-000000000046", + 3, + "Windows.Win32.System.Variant", + "VARIANT", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/oaidl/nn-oaidl-ienumvariant", + ), + entry( + "Windows.Win32.System.Com", + "IEnumString", + "00000101-0000-0000-c000-000000000046", + 3, + "Windows.Win32.Foundation", + "PWSTR", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/objidl/nn-objidl-ienumstring", + ), + entry( + "Windows.Win32.System.Com", + "IEnumUnknown", + "00000100-0000-0000-c000-000000000046", + 3, + "Windows.Win32.System.Com", + "IUnknown", + Interface, + Some("00000000-0000-0000-c000-000000000046"), + "https://learn.microsoft.com/windows/win32/api/unknwn/nn-unknwn-iunknown", + ), + entry( + "Windows.Win32.Storage.VirtualDiskService", + "IEnumVdsObject", + "118610b7-8d94-4030-b5b8-500889788e4e", + 3, + "Windows.Win32.System.Com", + "IUnknown", + Interface, + Some("00000000-0000-0000-c000-000000000046"), + "https://learn.microsoft.com/windows/win32/api/vds/nn-vds-ienumvdsobject", + ), + entry( + "Windows.Win32.System.Com.Events", + "IEnumEventObject", + "f4a07d63-2e25-11d1-9964-00c04fbbb345", + 4, + "Windows.Win32.System.Com", + "IUnknown", + Interface, + Some("00000000-0000-0000-c000-000000000046"), + "https://learn.microsoft.com/windows/win32/api/eventsys/nn-eventsys-ienumeventobject", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumITfCompositionView", + "5efd22ba-7838-46cb-88e2-cadb14124f8f", + 4, + "Windows.Win32.UI.TextServices", + "ITfCompositionView", + Interface, + Some("d7540241-f9a1-4364-befc-dbcd2c4395b7"), + "https://learn.microsoft.com/windows/win32/api/msctf/nn-msctf-ienumitfcompositionview", + ), + entry( + "Windows.Win32.System.Search", + "IEnumSearchRoots", + "ab310581-ac80-11d1-8df3-00c04fb6ef52", + 3, + "Windows.Win32.System.Search", + "ISearchRoot", + Interface, + Some("04c18ccf-1f57-4cbd-88cc-3900f5195ce3"), + "https://learn.microsoft.com/windows/win32/api/searchapi/nf-searchapi-ienumsearchroots-next", + ), + entry( + "Windows.Win32.System.Search", + "IEnumSearchScopeRules", + "ab310581-ac80-11d1-8df3-00c04fb6ef54", + 3, + "Windows.Win32.System.Search", + "ISearchScopeRule", + Interface, + Some("ab310581-ac80-11d1-8df3-00c04fb6ef53"), + "https://learn.microsoft.com/windows/win32/api/searchapi/nf-searchapi-ienumsearchscoperules-next", + ), + entry( + "Windows.Win32.System.Search", + "IEnumSubscription", + "f72c8d97-6dbd-11d1-a1e8-00c04fc2fbe1", + 3, + "System", + "Guid", + Unknown, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Storage.FileSystem", + "IEnumDiskQuotaUsers", + "7988b577-ec89-11cf-9c00-00aa00a14f56", + 3, + "Windows.Win32.Storage.FileSystem", + "IDiskQuotaUser", + Interface, + Some("7988b574-ec89-11cf-9c00-00aa00a14f56"), + "https://learn.microsoft.com/windows/win32/api/dskquota/nf-dskquota-ienumdiskquotausers-next", + ), + entry( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmString", + "0adda826-2c26-11d2-ad65-00a0c9af11a6", + 3, + "Windows.Win32.Foundation", + "BSTR", + Struct, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmError", + "0adda829-2c26-11d2-ad65-00a0c9af11a6", + 3, + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IMsmError", + Interface, + Some("0adda828-2c26-11d2-ad65-00a0c9af11a6"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmDependency", + "0adda82c-2c26-11d2-ad65-00a0c9af11a6", + 3, + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IMsmDependency", + Interface, + Some("0adda82b-2c26-11d2-ad65-00a0c9af11a6"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Storage.Imapi", + "IEnumDiscMasterFormats", + "ddf445e1-54ba-11d3-9144-00104ba11c5e", + 3, + "System", + "Guid", + Unknown, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Storage.Imapi", + "IEnumDiscRecorders", + "9b1921e1-54ac-11d3-9144-00104ba11c5e", + 3, + "Windows.Win32.Storage.Imapi", + "IDiscRecorder", + Interface, + Some("85ac9776-ca88-4cf2-894e-09598c078a41"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Storage.Imapi", + "IEnumProgressItems", + "2c941fd6-975b-59be-a960-9a2a262853a5", + 3, + "Windows.Win32.Storage.Imapi", + "IProgressItem", + Interface, + Some("2c941fd5-975b-59be-a960-9a2a262853a5"), + "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ienumprogressitems-next", + ), + entry( + "Windows.Win32.Storage.Imapi", + "IEnumFsiItems", + "2c941fda-975b-59be-a960-9a2a262853a5", + 3, + "Windows.Win32.Storage.Imapi", + "IFsiItem", + Interface, + Some("2c941fd9-975b-59be-a960-9a2a262853a5"), + "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ienumfsiitems-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyJobs", + "1af4f612-3b71-466f-8f58-7b6f73ac57ad", + 3, + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IBackgroundCopyJob", + Interface, + Some("37668d37-507e-4160-9316-26306d150b12"), + "https://learn.microsoft.com/windows/win32/api/bits/nf-bits-ienumbackgroundcopyjobs-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyGroups", + "d993e603-4aa4-47c5-8665-c20d39c2ba4f", + 3, + "System", + "Guid", + Unknown, + None, + "https://learn.microsoft.com/windows/win32/api/qmgr/nf-qmgr-ienumbackgroundcopygroups-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBitsPeers", + "659cdea5-489e-11d9-a9cd-000d56965251", + 3, + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IBitsPeer", + Interface, + Some("659cdea2-489e-11d9-a9cd-000d56965251"), + "https://learn.microsoft.com/windows/win32/api/bits3_0/nf-bits3_0-ienumbitspeers-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyFiles", + "ca51e165-c365-424c-8d41-24aaa4ff3c40", + 3, + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IBackgroundCopyFile", + Interface, + Some("01b7bd23-fb88-4a77-8490-5891d3e4653a"), + "https://learn.microsoft.com/windows/win32/api/bits/nf-bits-ienumbackgroundcopyfiles-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBitsPeerCacheRecords", + "659cdea4-489e-11d9-a9cd-000d56965251", + 3, + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IBitsPeerCacheRecord", + Interface, + Some("659cdeaf-489e-11d9-a9cd-000d56965251"), + "https://learn.microsoft.com/windows/win32/api/bits3_0/nf-bits3_0-ienumbitspeercacherecords-next", + ), + entry( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyJobs1", + "8baeba9d-8f1c-42c4-b82c-09ae79980d25", + 3, + "System", + "Guid", + Unknown, + None, + "https://learn.microsoft.com/windows/win32/api/qmgr/nf-qmgr-ienumbackgroundcopyjobs1-next", + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumGuideDataProperties", + "ae44423b-4571-475c-ad2c-f40a771d80ef", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "IGuideDataProperty", + Interface, + Some("88ec5e58-bb73-41d6-99ce-66c524b8b591"), + "https://learn.microsoft.com/windows/win32/api/bdatif/nf-bdatif-ienumguidedataproperties-next", + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumComponents", + "2a6e2939-2595-11d3-b64c-00c04f79498e", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "IComponent", + Interface, + Some("1a5576fc-0e19-11d3-9d8e-00c04f72d980"), + "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-ienumcomponents-next", + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumMSVidGraphSegment", + "3dd2903e-e0aa-11d2-b63a-00c04f79498e", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "IMSVidGraphSegment", + Interface, + Some("238dec54-adeb-4005-a349-f772b9afebc4"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumTuneRequests", + "1993299c-ced6-4788-87a3-420067dce0c7", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "ITuneRequest", + Interface, + Some("07ddc146-fc3d-11d2-9d8c-00c04f72d980"), + "https://learn.microsoft.com/windows/win32/api/bdatif/nf-bdatif-ienumtunerequests-next", + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumTuningSpaces", + "8b8eb248-fc2b-11d2-9d8c-00c04f72d980", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "ITuningSpace", + Interface, + Some("061c6e30-e622-11d2-9493-00c04f72d980"), + "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-ienumtuningspaces-next", + ), + entry( + "Windows.Win32.Media.DirectShow.Tv", + "IEnumComponentTypes", + "8a674b4a-1f63-11d3-b64c-00c04f79498e", + 3, + "Windows.Win32.Media.DirectShow.Tv", + "IComponentType", + Interface, + Some("6a340dc0-0311-11d3-9d8e-00c04f72d980"), + "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-ienumcomponenttypes-next", + ), + entry( + "Windows.Win32.Globalization", + "IEnumCodePage", + "275c23e3-3747-11d0-9fea-00aa003f8646", + 4, + "Windows.Win32.Globalization", + "MIMECPINFO", + Struct, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Globalization", + "IEnumScript", + "ae5f1430-388b-11d2-8380-00c04f8f5da1", + 4, + "Windows.Win32.Globalization", + "SCRIPTINFO", + Struct, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Globalization", + "IEnumRfc1766", + "3dc39d1d-c030-11d0-b81b-00c04fc9b31f", + 4, + "Windows.Win32.Globalization", + "RFC1766INFO", + Struct, + None, + STANDARD_NEXT, + ), + entry( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgBindingInterface", + "c0e8ae90-306e-11d1-aacf-00805fc1270e", + 3, + "Windows.Win32.NetworkManagement.NetManagement", + "INetCfgBindingInterface", + Interface, + Some("c0e8ae94-306e-11d1-aacf-00805fc1270e"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgBindingPath", + "c0e8ae91-306e-11d1-aacf-00805fc1270e", + 3, + "Windows.Win32.NetworkManagement.NetManagement", + "INetCfgBindingPath", + Interface, + Some("c0e8ae96-306e-11d1-aacf-00805fc1270e"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgComponent", + "c0e8ae92-306e-11d1-aacf-00805fc1270e", + 3, + "Windows.Win32.NetworkManagement.NetManagement", + "INetCfgComponent", + Interface, + Some("c0e8ae99-306e-11d1-aacf-00805fc1270e"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWIA_FORMAT_INFO", + "81befc5b-656d-44f1-b24c-d41d51b4dc81", + 3, + "Windows.Win32.Devices.ImageAcquisition", + "WIA_FORMAT_INFO", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/wia_xp/nf-wia_xp-ienumwia_format_info-next", + ), + entry( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWiaItem2", + "59970af4-cd0d-44d9-ab24-52295630e582", + 3, + "Windows.Win32.Devices.ImageAcquisition", + "IWiaItem2", + Interface, + Some("6cba0075-1287-407d-9b77-cf0e030435cc"), + "https://learn.microsoft.com/windows/win32/wia/-wia-ienumwiaitem2-next", + ), + entry( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWIA_DEV_INFO", + "5e38b83c-8cf1-11d1-bf92-0060081ed811", + 3, + "Windows.Win32.Devices.ImageAcquisition", + "IWiaPropertyStorage", + Interface, + Some("98b5e8a0-29cc-491a-aac0-e6db4fdcceb6"), + "https://learn.microsoft.com/windows/win32/api/wia_xp/nf-wia_xp-ienumwia_dev_info-next", + ), + entry( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWiaItem", + "5e8383fc-3391-11d2-9a33-00c04fa36145", + 3, + "Windows.Win32.Devices.ImageAcquisition", + "IWiaItem", + Interface, + Some("4db1ad10-3391-11d2-9a33-00c04fa36145"), + "https://learn.microsoft.com/windows/win32/api/wia_xp/nf-wia_xp-ienumwiaitem-next", + ), + entry( + "Windows.Win32.NetworkManagement.WiFi", + "IEnumDot11AdHocNetworks", + "8f10cc28-cf0d-42a0-acbe-e2de7007384d", + 3, + "Windows.Win32.NetworkManagement.WiFi", + "IDot11AdHocNetwork", + Interface, + Some("8f10cc29-cf0d-42a0-acbe-e2de7007384d"), + "https://learn.microsoft.com/windows/win32/api/adhoc/nf-adhoc-ienumdot11adhocnetworks-next", + ), + entry( + "Windows.Win32.NetworkManagement.WiFi", + "IEnumDot11AdHocInterfaces", + "8f10cc2c-cf0d-42a0-acbe-e2de7007384d", + 3, + "Windows.Win32.NetworkManagement.WiFi", + "IDot11AdHocInterface", + Interface, + Some("8f10cc2b-cf0d-42a0-acbe-e2de7007384d"), + "https://learn.microsoft.com/windows/win32/api/adhoc/nf-adhoc-ienumdot11adhocinterfaces-next", + ), + entry( + "Windows.Win32.NetworkManagement.WiFi", + "IEnumDot11AdHocSecuritySettings", + "8f10cc2d-cf0d-42a0-acbe-e2de7007384d", + 3, + "Windows.Win32.NetworkManagement.WiFi", + "IDot11AdHocSecuritySettings", + Interface, + Some("8f10cc2e-cf0d-42a0-acbe-e2de7007384d"), + "https://learn.microsoft.com/windows/win32/api/adhoc/nf-adhoc-ienumdot11adhocsecuritysettings-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfRanges", + "f99d3f40-8e32-11d2-bf46-00105a2799b5", + 4, + "Windows.Win32.UI.TextServices", + "ITfRange", + Interface, + Some("aa80e7ff-2021-11d2-93e0-0060b067b86e"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfranges-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfDisplayAttributeInfo", + "7cef04d7-cb75-4e80-a7ab-5f5bc7d332de", + 4, + "Windows.Win32.UI.TextServices", + "ITfDisplayAttributeInfo", + Interface, + Some("70528852-2f26-4aea-8c96-215150578932"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfdisplayattributeinfo-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfContextViews", + "f0c0f8dd-cf38-44e1-bb0f-68cf0d551c78", + 4, + "Windows.Win32.UI.TextServices", + "ITfContextView", + Interface, + Some("2433bf8e-0f9b-435c-ba2c-180611978c30"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfUIElements", + "887aa91e-acba-4931-84da-3c5208cf543f", + 4, + "Windows.Win32.UI.TextServices", + "ITfUIElement", + Interface, + Some("ea1ea137-19df-11d7-a6d2-00065b84435c"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfuielements-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfCandidates", + "defb1926-6c80-4ce8-87d4-d6b72b812bde", + 4, + "Windows.Win32.UI.TextServices", + "ITfCandidateString", + Interface, + Some("581f317e-fd9d-443f-b972-ed00467c5d40"), + "https://learn.microsoft.com/windows/win32/api/ctffunc/nf-ctffunc-ienumtfcandidates-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfLangBarItems", + "583f34d0-de25-11d2-afdd-00105a2799b5", + 4, + "Windows.Win32.UI.TextServices", + "ITfLangBarItem", + Interface, + Some("73540d69-edeb-4ee9-96c9-23aa30b25916"), + "https://learn.microsoft.com/windows/win32/api/ctfutb/nf-ctfutb-ienumtflangbaritems-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfFunctionProviders", + "e4b24db0-0990-11d3-8df0-00105a2799b5", + 4, + "Windows.Win32.UI.TextServices", + "ITfFunctionProvider", + Interface, + Some("101d6610-0990-11d3-8df0-00105a2799b5"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtffunctionproviders-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfProperties", + "19188cb0-aca9-11d2-afc5-00105a2799b5", + 4, + "Windows.Win32.UI.TextServices", + "ITfProperty", + Interface, + Some("e2449660-9542-11d2-bf46-00105a2799b5"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfproperties-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfDocumentMgrs", + "aa80e808-2021-11d2-93e0-0060b067b86e", + 4, + "Windows.Win32.UI.TextServices", + "ITfDocumentMgr", + Interface, + Some("aa80e7f4-2021-11d2-93e0-0060b067b86e"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfdocumentmgrs-next", + ), + entry( + "Windows.Win32.UI.TextServices", + "IEnumTfContexts", + "8f1a7ea6-1654-4502-a86e-b2902344d507", + 4, + "Windows.Win32.UI.TextServices", + "ITfContext", + Interface, + Some("aa80e7fd-2021-11d2-93e0-0060b067b86e"), + "https://learn.microsoft.com/windows/win32/api/msctf/nf-msctf-ienumtfcontexts-next", + ), + entry( + "Windows.Win32.System.Com", + "IEnumMoniker", + "00000102-0000-0000-c000-000000000046", + 3, + "Windows.Win32.System.Com", + "IMoniker", + Interface, + Some("0000000f-0000-0000-c000-000000000046"), + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-ienummoniker-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumSyncProviderConfigUIInfos", + "f6be2602-17c6-4658-a2d7-68ed3330f641", + 3, + "Windows.Win32.System.WindowsSync", + "ISyncProviderConfigUIInfo", + Interface, + Some("214141ae-33d7-4d8d-8e37-f227e880ce50"), + "https://learn.microsoft.com/windows/win32/api/syncregistration/nf-syncregistration-ienumsyncproviderconfiguiinfos-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumSingleItemExceptions", + "e563381c-1b4d-4c66-9796-c86faccdcd40", + 3, + "Windows.Win32.System.WindowsSync", + "ISingleItemException", + Interface, + Some("892fb9b0-7c55-4a18-9316-fdf449569b64"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumsingleitemexceptions-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumSyncChangeUnits", + "346b35f1-8703-4c6d-ab1a-4dbca2cff97f", + 3, + "Windows.Win32.System.WindowsSync", + "ISyncChangeUnit", + Interface, + Some("60edd8ca-7341-4bb7-95ce-fab6394b51cb"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumsyncchangeunits-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumSyncProviderInfos", + "a04ba850-5eb1-460d-a973-393fcb608a11", + 3, + "Windows.Win32.System.WindowsSync", + "ISyncProviderInfo", + Interface, + Some("1ee135de-88a4-4504-b0d0-f7920d7e5ba6"), + "https://learn.microsoft.com/windows/win32/api/syncregistration/nf-syncregistration-ienumsyncproviderinfos-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumClockVector", + "525844db-2837-4799-9e80-81a66e02220c", + 3, + "Windows.Win32.System.WindowsSync", + "IClockVectorElement", + Interface, + Some("e71c4250-adf8-4a07-8fae-5669596909c1"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumclockvector-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumChangeUnitExceptions", + "3074e802-9319-4420-be21-1022e2e21da8", + 3, + "Windows.Win32.System.WindowsSync", + "IChangeUnitException", + Interface, + Some("0cd7ee7c-fec0-4021-99ee-f0e5348f2a5f"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumchangeunitexceptions-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumSyncChanges", + "5f86be4a-5e78-4e32-ac1c-c24fd223ef85", + 3, + "Windows.Win32.System.WindowsSync", + "ISyncChange", + Interface, + Some("a1952beb-0f6b-4711-b136-01da85b968a6"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumsyncchanges-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumRangeExceptions", + "0944439f-ddb1-4176-b703-046ff22a2386", + 3, + "Windows.Win32.System.WindowsSync", + "IRangeException", + Interface, + Some("75ae8777-6848-49f7-956c-a3a92f5096e8"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumrangeexceptions-next", + ), + entry( + "Windows.Win32.System.WindowsSync", + "IEnumFeedClockVector", + "550f763d-146a-48f6-abeb-6c88c7f70514", + 3, + "Windows.Win32.System.WindowsSync", + "IFeedClockVectorElement", + Interface, + Some("a40b46d2-e97b-4156-b6da-991f501b0f05"), + "https://learn.microsoft.com/windows/win32/api/winsync/nf-winsync-ienumfeedclockvector-next", + ), + entry( + "Windows.Win32.Media.Speech", + "IEnumSpObjectTokens", + "06b64f9e-7fda-11d2-b4f2-00c04f797396", + 3, + "Windows.Win32.Media.Speech", + "ISpObjectToken", + Interface, + Some("14056589-e16c-11d2-bb90-00c04f8ee6c0"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Web.InternetExplorer", + "IEnumOpenServiceActivityCategory", + "33627a56-8c9a-4430-8fd1-b5f5c771afb6", + 3, + "Windows.Win32.Web.InternetExplorer", + "IOpenServiceActivityCategory", + Interface, + Some("850af9d6-7309-40b5-bdb8-786c106b2153"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Web.InternetExplorer", + "IEnumOpenServiceActivity", + "a436d7d2-17c3-4ef4-a1e8-5c86faff26c0", + 3, + "Windows.Win32.Web.InternetExplorer", + "IOpenServiceActivity", + Interface, + Some("13645c88-221a-4905-8ed1-4f5112cfc108"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Media.DirectShow", + "IEnumPins", + "56a86892-0ad4-11ce-b03a-0020af0ba770", + 3, + "Windows.Win32.Media.DirectShow", + "IPin", + Interface, + Some("56a86891-0ad4-11ce-b03a-0020af0ba770"), + "https://learn.microsoft.com/windows/win32/api/strmif/nf-strmif-ienumpins-next", + ), + entry( + "Windows.Win32.Media.DirectShow", + "IEnumFilters", + "56a86893-0ad4-11ce-b03a-0020af0ba770", + 3, + "Windows.Win32.Media.DirectShow", + "IBaseFilter", + Interface, + Some("56a86895-0ad4-11ce-b03a-0020af0ba770"), + "https://learn.microsoft.com/windows/win32/api/strmif/nf-strmif-ienumfilters-next", + ), + entry( + "Windows.Win32.Devices.Tapi", + "IEnumQueue", + "5afc3158-4bcc-11d1-bf80-00805fc147d3", + 3, + "Windows.Win32.Devices.Tapi", + "ITQueue", + Interface, + Some("5afc3149-4bcc-11d1-bf80-00805fc147d3"), + "https://learn.microsoft.com/windows/win32/api/tapi3cc/nf-tapi3cc-ienumqueue-next", + ), + entry( + "Windows.Win32.Devices.Tapi", + "IEnumAgentSession", + "5afc314e-4bcc-11d1-bf80-00805fc147d3", + 3, + "Windows.Win32.Devices.Tapi", + "ITAgentSession", + Interface, + Some("5afc3147-4bcc-11d1-bf80-00805fc147d3"), + "https://learn.microsoft.com/windows/win32/api/tapi3cc/nf-tapi3cc-ienumagentsession-next", + ), + entry( + "Windows.Win32.Devices.Tapi", + "IEnumACDGroup", + "5afc3157-4bcc-11d1-bf80-00805fc147d3", + 3, + "Windows.Win32.Devices.Tapi", + "ITACDGroup", + Interface, + Some("5afc3148-4bcc-11d1-bf80-00805fc147d3"), + "https://learn.microsoft.com/windows/win32/api/tapi3cc/nf-tapi3cc-ienumacdgroup-next", + ), + entry( + "Windows.Win32.Devices.Tapi", + "IEnumAgent", + "5afc314d-4bcc-11d1-bf80-00805fc147d3", + 3, + "Windows.Win32.Devices.Tapi", + "ITAgent", + Interface, + Some("5770ece5-4b27-11d1-bf80-00805fc147d3"), + "https://learn.microsoft.com/windows/win32/api/tapi3cc/nf-tapi3cc-ienumagent-next", + ), + entry( + "Windows.Win32.Devices.Tapi", + "IEnumAgentHandler", + "587e8c28-9802-11d1-a0a4-00805fc147d3", + 3, + "Windows.Win32.Devices.Tapi", + "ITAgentHandler", + Interface, + Some("587e8c22-9802-11d1-a0a4-00805fc147d3"), + "https://learn.microsoft.com/windows/win32/api/tapi3cc/nf-tapi3cc-ienumagenthandler-next", + ), + entry( + "Windows.Win32.System.Ole", + "IEnumOleUndoUnits", + "b3e7c340-ef97-11ce-9bc9-00aa00608e01", + 3, + "Windows.Win32.System.Ole", + "IOleUndoUnit", + Interface, + Some("894ad3b0-ef97-11ce-9bc9-00aa00608e01"), + "https://learn.microsoft.com/windows/win32/api/ocidl/nf-ocidl-ienumoleundounits-next", + ), + entry( + "Windows.Win32.System.Ole", + "IEnumOleDocumentViews", + "b722bcc8-4e68-101b-a2bc-00aa00404770", + 3, + "Windows.Win32.System.Ole", + "IOleDocumentView", + Interface, + Some("b722bcc6-4e68-101b-a2bc-00aa00404770"), + "https://learn.microsoft.com/windows/win32/api/docobj/nf-docobj-ienumoledocumentviews-next", + ), + entry( + "Windows.Win32.NetworkManagement.WindowsFirewall", + "IEnumNetSharingPrivateConnection", + "c08956b5-1cd3-11d1-b1c5-00805fc1270e", + 3, + "Windows.Win32.System.Variant", + "VARIANT", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/netcon/nf-netcon-ienumnetsharingprivateconnection-next", + ), + entry( + "Windows.Win32.NetworkManagement.WindowsFirewall", + "IEnumNetSharingPublicConnection", + "c08956b4-1cd3-11d1-b1c5-00805fc1270e", + 3, + "Windows.Win32.System.Variant", + "VARIANT", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/netcon/nf-netcon-ienumnetsharingpublicconnection-next", + ), + entry( + "Windows.Win32.NetworkManagement.WindowsFirewall", + "IEnumNetConnection", + "c08956a0-1cd3-11d1-b1c5-00805fc1270e", + 3, + "Windows.Win32.NetworkManagement.WindowsFirewall", + "INetConnection", + Interface, + Some("c08956a1-1cd3-11d1-b1c5-00805fc1270e"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.NetworkManagement.WindowsFirewall", + "IEnumNetSharingEveryConnection", + "c08956b8-1cd3-11d1-b1c5-00805fc1270e", + 3, + "Windows.Win32.System.Variant", + "VARIANT", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/netcon/nf-netcon-ienumnetsharingeveryconnection-next", + ), + entry( + "Windows.Win32.NetworkManagement.WindowsFirewall", + "IEnumNetSharingPortMapping", + "c08956b0-1cd3-11d1-b1c5-00805fc1270e", + 3, + "Windows.Win32.System.Variant", + "VARIANT", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/netcon/nf-netcon-ienumnetsharingportmapping-next", + ), + entry( + "Windows.Win32.Devices.PortableDevices", + "IEnumPortableDeviceConnectors", + "bfdef549-9247-454f-bd82-06fe80853faa", + 3, + "Windows.Win32.Devices.PortableDevices", + "IPortableDeviceConnector", + Interface, + Some("625e2df8-6392-4cf0-9ad1-3cfa5f17775c"), + "https://learn.microsoft.com/windows/win32/wpd_sdk/ienumportabledeviceconnectors-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumShellItems", + "70629033-e363-4a28-a567-0db78006e6d7", + 3, + "Windows.Win32.UI.Shell", + "IShellItem", + Interface, + Some("43826d1e-e718-42ee-bc55-a1e261c37bfe"), + "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ienumshellitems-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumSyncMgrEvents", + "c81a1d4e-8cf7-4683-80e0-bcae88d677b6", + 3, + "Windows.Win32.UI.Shell", + "ISyncMgrEvent", + Interface, + Some("fee0ef8b-46bd-4db4-b7e6-ff2c687313bc"), + "https://learn.microsoft.com/windows/win32/api/syncmgr/nf-syncmgr-ienumsyncmgrevents-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumTravelLogEntry", + "7ebfdd85-ad18-11d3-a4c5-00c04f72d6b8", + 3, + "Windows.Win32.UI.Shell", + "ITravelLogEntry", + Interface, + Some("7ebfdd87-ad18-11d3-a4c5-00c04f72d6b8"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumSyncMgrConflict", + "82705914-dda3-4893-ba99-49de6c8c8036", + 3, + "Windows.Win32.UI.Shell", + "ISyncMgrConflict", + Interface, + Some("9c204249-c443-4ba4-85ed-c972681db137"), + "https://learn.microsoft.com/windows/win32/api/syncmgr/nf-syncmgr-ienumsyncmgrconflict-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumSyncMgrSyncItems", + "54b3abf3-f085-4181-b546-e29c403c726b", + 3, + "Windows.Win32.UI.Shell", + "ISyncMgrSyncItem", + Interface, + Some("b20b24ce-2593-4f04-bd8b-7ad6c45051cd"), + "https://learn.microsoft.com/windows/win32/api/syncmgr/nf-syncmgr-ienumsyncmgrsyncitems-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumAssocHandlers", + "973810ae-9599-4b88-9e4d-6ee98c9552da", + 3, + "Windows.Win32.UI.Shell", + "IAssocHandler", + Interface, + Some("f04061ac-1659-4a3f-a954-775aa57fc083"), + "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ienumassochandlers-next", + ), + entry( + "Windows.Win32.UI.Shell", + "IEnumExplorerCommand", + "a88826f8-186f-4987-aade-ea0cef8fbfe8", + 3, + "Windows.Win32.UI.Shell", + "IExplorerCommand", + Interface, + Some("a08ce4d0-fa25-44ab-b57c-c7b1c323e0b9"), + "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ienumexplorercommand-next", + ), + entry( + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IEnumRemoteDebugApplications", + "51973c3b-cb0c-11d0-b5c9-00a0244a0e7a", + 3, + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IRemoteDebugApplication", + Interface, + Some("51973c30-cb0c-11d0-b5c9-00a0244a0e7a"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IEnumDebugExpressionContexts", + "51973c40-cb0c-11d0-b5c9-00a0244a0e7a", + 3, + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IDebugExpressionContext", + Interface, + Some("51973c15-cb0c-11d0-b5c9-00a0244a0e7a"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IEnumRemoteDebugApplicationThreads", + "51973c3c-cb0c-11d0-b5c9-00a0244a0e7a", + 3, + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IRemoteDebugApplicationThread", + Interface, + Some("51973c37-cb0c-11d0-b5c9-00a0244a0e7a"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IEnumDebugApplicationNodes", + "51973c3a-cb0c-11d0-b5c9-00a0244a0e7a", + 3, + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IDebugApplicationNode", + Interface, + Some("51973c34-cb0c-11d0-b5c9-00a0244a0e7a"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IEnumDebugCodeContexts", + "51973c1d-cb0c-11d0-b5c9-00a0244a0e7a", + 3, + "Windows.Win32.System.Diagnostics.Debug.ActiveScript", + "IDebugCodeContext", + Interface, + Some("51973c13-cb0c-11d0-b5c9-00a0244a0e7a"), + STANDARD_NEXT, + ), + entry( + "Windows.Win32.Storage.OfflineFiles", + "IEnumOfflineFilesSettings", + "729680c4-1a38-47bc-9e5c-02c51562ac30", + 3, + "Windows.Win32.Storage.OfflineFiles", + "IOfflineFilesSetting", + Interface, + Some("d871d3f7-f613-48a1-827e-7a34e560fff6"), + "https://learn.microsoft.com/windows/win32/api/cscobj/nf-cscobj-ienumofflinefilessettings-next", + ), + entry( + "Windows.Win32.Storage.OfflineFiles", + "IEnumOfflineFilesItems", + "da70e815-c361-4407-bc0b-0d7046e5f2cd", + 3, + "Windows.Win32.Storage.OfflineFiles", + "IOfflineFilesItem", + Interface, + Some("4a753da6-e044-4f12-a718-5d14d079a906"), + "https://learn.microsoft.com/windows/win32/api/cscobj/nf-cscobj-ienumofflinefilesitems-next", + ), + entry( + "Windows.Win32.System.ComponentServices", + "IEnumNames", + "51372af2-cae7-11cf-be81-00aa00a2fa25", + 3, + "Windows.Win32.Foundation", + "BSTR", + Struct, + None, + "https://learn.microsoft.com/windows/win32/api/comsvcs/nf-comsvcs-ienumnames-next", + ), +]; + +const INOUT_FETCHED_DECLARATIONS: &[(&str, &str)] = &[ + ("Windows.Win32.System.Search", "IEnumSearchRoots"), + ("Windows.Win32.System.Search", "IEnumSearchScopeRules"), + ("Windows.Win32.Storage.FileSystem", "IEnumDiskQuotaUsers"), + ( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmString", + ), + ( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmError", + ), + ( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmDependency", + ), + ( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyJobs", + ), + ( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBitsPeers", + ), + ( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBackgroundCopyFiles", + ), + ( + "Windows.Win32.Networking.BackgroundIntelligentTransferService", + "IEnumBitsPeerCacheRecords", + ), + ( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWIA_FORMAT_INFO", + ), + ("Windows.Win32.Devices.ImageAcquisition", "IEnumWiaItem2"), + ( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWIA_DEV_INFO", + ), + ("Windows.Win32.Devices.ImageAcquisition", "IEnumWiaItem"), + ("Windows.Win32.UI.TextServices", "IEnumTfLangBarItems"), + ( + "Windows.Win32.System.WindowsSync", + "IEnumSingleItemExceptions", + ), + ("Windows.Win32.System.WindowsSync", "IEnumSyncChangeUnits"), + ("Windows.Win32.System.WindowsSync", "IEnumClockVector"), + ( + "Windows.Win32.System.WindowsSync", + "IEnumChangeUnitExceptions", + ), + ("Windows.Win32.System.WindowsSync", "IEnumSyncChanges"), + ("Windows.Win32.System.WindowsSync", "IEnumRangeExceptions"), + ("Windows.Win32.System.WindowsSync", "IEnumFeedClockVector"), + ( + "Windows.Win32.Devices.PortableDevices", + "IEnumPortableDeviceConnectors", + ), + ("Windows.Win32.System.ComponentServices", "IEnumNames"), +]; + +const OPTIONAL_FETCHED_DECLARATIONS: &[(&str, &str)] = &[ + ("Windows.Win32.System.Com", "IEnumGUID"), + ("Windows.Win32.System.Com", "IEnumString"), + ("Windows.Win32.System.Com", "IEnumUnknown"), + ("Windows.Win32.Globalization", "IEnumCodePage"), + ("Windows.Win32.Globalization", "IEnumScript"), + ("Windows.Win32.Globalization", "IEnumRfc1766"), + ( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgBindingInterface", + ), + ( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgBindingPath", + ), + ( + "Windows.Win32.NetworkManagement.NetManagement", + "IEnumNetCfgComponent", + ), + ("Windows.Win32.System.Com", "IEnumMoniker"), + ("Windows.Win32.Media.Speech", "IEnumSpObjectTokens"), + ("Windows.Win32.Media.DirectShow", "IEnumPins"), + ("Windows.Win32.Media.DirectShow", "IEnumFilters"), + ("Windows.Win32.UI.Shell", "IEnumShellItems"), + ("Windows.Win32.UI.Shell", "IEnumAssocHandlers"), + ("Windows.Win32.UI.Shell", "IEnumExplorerCommand"), +]; + +fn declaration_is_in( + declarations: &[(&str, &str)], + interface_namespace: &str, + interface_name: &str, +) -> bool { + declarations + .iter() + .any(|(namespace, name)| *namespace == interface_namespace && *name == interface_name) +} + +pub(crate) fn fetched_shape( + interface_namespace: &str, + interface_name: &str, +) -> (EnumeratorDirection, bool) { + let direction = if declaration_is_in( + INOUT_FETCHED_DECLARATIONS, + interface_namespace, + interface_name, + ) { + EnumeratorDirection::InOut + } else { + EnumeratorDirection::Out + }; + let optional = declaration_is_in( + OPTIONAL_FETCHED_DECLARATIONS, + interface_namespace, + interface_name, + ); + (direction, optional) +} + +pub(crate) fn values_direction( + interface_namespace: &str, + interface_name: &str, +) -> EnumeratorDirection { + if matches!( + (interface_namespace, interface_name), + ( + "Windows.Win32.System.ApplicationInstallationAndServicing", + "IEnumMsmString" + ) | ( + "Windows.Win32.Devices.ImageAcquisition", + "IEnumWIA_FORMAT_INFO" + ) | ("Windows.Win32.System.ComponentServices", "IEnumNames") + ) { + EnumeratorDirection::InOut + } else { + EnumeratorDirection::Out + } +} + +pub(crate) fn contract_for_declaration( + interface_namespace: &str, + interface_name: &str, +) -> Option<&'static EnumeratorContract> { + ENUMERATOR_CONTRACTS.iter().find(|contract| { + contract.interface_namespace == interface_namespace + && contract.interface_name == interface_name + }) +} + +pub(crate) fn exact_contract( + interface_namespace: &str, + interface_name: &str, + interface_iid: &str, + next_vtable_index: usize, +) -> Option<&'static EnumeratorContract> { + contract_for_declaration(interface_namespace, interface_name).filter(|contract| { + contract.interface_iid.eq_ignore_ascii_case(interface_iid) + && contract.next_vtable_index == next_vtable_index + }) +} + +#[cfg(test)] +pub(crate) fn contracts() -> &'static [EnumeratorContract] { + ENUMERATOR_CONTRACTS +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_lookup_rejects_identity_and_slot_drift() { + assert!( + exact_contract( + "Windows.Win32.System.Com", + "IEnumUnknown", + "00000100-0000-0000-c000-000000000046", + 3 + ) + .is_some() + ); + assert!( + exact_contract( + "Contoso", + "IEnumUnknown", + "00000100-0000-0000-c000-000000000046", + 3 + ) + .is_none() + ); + assert!( + exact_contract( + "Windows.Win32.System.Com", + "IEnumUnknown", + "ffffffff-ffff-ffff-ffff-ffffffffffff", + 3 + ) + .is_none() + ); + assert!( + exact_contract( + "Windows.Win32.System.Com", + "IEnumUnknown", + "00000100-0000-0000-c000-000000000046", + 4 + ) + .is_none() + ); + } + + #[test] + fn declarations_are_unique() { + for (index, contract) in ENUMERATOR_CONTRACTS.iter().enumerate() { + assert!( + !ENUMERATOR_CONTRACTS[..index].iter().any(|previous| { + previous.interface_namespace == contract.interface_namespace + && previous.interface_name == contract.interface_name + }), + "{}.{}", + contract.interface_namespace, + contract.interface_name + ); + assert_eq!( + contract.element_iid.is_some(), + contract.element_kind == EnumeratorElementKind::Interface, + "{}.{} element IID", + contract.interface_namespace, + contract.interface_name + ); + } + } +} diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index d8b5e18b..ec4892ca 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -7,6 +7,279 @@ use windows_metadata::{HasAttributes, reader}; use crate::types::TypeMeta; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawConstness { + Const, + Mutable, + Unspecified, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RawNamedKind { + Interface, + Enum, + Struct, + Delegate, + RuntimeClass, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawLayoutKind { + Sequential, + Explicit, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawPacking { + Default, + Explicit(u16), + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawNativeField { + pub name: String, + pub typ: RawComType, + pub explicit_offset: Option, + pub fixed_count: Option, + pub bitfield: bool, + pub flexible_array: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawNativeLayout { + /// SupportedArchitectureAttribute mask: x86=1, x64=2, ARM64=4. + pub architectures: u8, + pub kind: RawLayoutKind, + pub packing: RawPacking, + pub declared_size: Option, + pub fields: Vec, + /// Win32 metadata uses explicit layout for C unions. Synthetic metadata + /// tests may set this to false to exercise non-overlapping explicit PODs. + pub is_union: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawNativeLayoutSet { + pub recursive: bool, + pub variants: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RawNativeType { + Void, + Bool, + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + Char16, + ISize, + USize, + String, + Object, + Named { + namespace: String, + name: String, + kind: RawNamedKind, + iid: Option, + layout: Option>, + }, + Array(Box), + FixedArray { + element: Box, + count: usize, + }, + Unknown(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawComType { + pub native_type: RawNativeType, + pub underlying: Option>, + pub pointer_depth: usize, + /// Constness shared by every pointer level. Mixed per-level qualifiers + /// become `Unspecified` and fail semantic validation until modeled + /// explicitly. + pub constness: RawConstness, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawParamDirection { + In, + Out, + InOut, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawStringEncoding { + Utf16, + Ansi, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawElementOwnership { + Borrowed, + CoTaskMemOwned, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawStringPointerArray { + pub encoding: RawStringEncoding, + pub pointer_depth: usize, + pub constness: RawConstness, + pub ownership: RawElementOwnership, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawArrayRelation { + pub count_param_index: Option, + pub actual_length_param_index: Option, + pub unit: RawCountUnit, + pub two_call: bool, + pub projected_capacity: bool, + pub constness: Option, + pub evidence: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawEnumeratorNext { + pub capacity_param_index: usize, + pub values_param_index: usize, + pub fetched_param_index: usize, + pub fetched_optional_for_single: bool, + pub evidence: RawEvidence, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawCountUnit { + Elements, + Bytes, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RawEvidence { + MetadataAttribute(&'static str), + Override { + reason: &'static str, + citation: &'static str, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawFreeWith { + pub function: String, + pub evidence: RawEvidence, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawComParam { + pub name: String, + pub typ: RawComType, + pub direction: RawParamDirection, + pub optional: bool, + pub const_attribute: bool, + pub native_array: Option, + pub string_pointer_array: Option, + pub free_with: Option, + pub safe_array_evidence: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawSafeArrayVartype { + I4, + Ui1, + Ui4, + R8, + Bstr, + Unknown, + Variant, +} + +impl RawSafeArrayVartype { + pub const fn value(self) -> u16 { + match self { + Self::I4 => 3, + Self::R8 => 5, + Self::Bstr => 8, + Self::Variant => 12, + Self::Unknown => 13, + Self::Ui1 => 17, + Self::Ui4 => 19, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawSafeArrayOwnership { + BorrowedInput, + OwnedOutput, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawSafeArrayEvidence { + pub declaring_namespace: &'static str, + pub declaring_interface: &'static str, + pub declaring_iid: &'static str, + pub method_name: &'static str, + pub vtable_index: usize, + pub parameter_index: usize, + pub parameter_name: &'static str, + pub element_vartype: RawSafeArrayVartype, + pub element_iid: Option<&'static str>, + pub ownership: RawSafeArrayOwnership, + pub raw_method_shape: &'static str, + pub reason: &'static str, + pub citation: &'static str, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawComMethod { + pub declaring_namespace: String, + pub declaring_interface: String, + pub declaring_iid: String, + pub metadata_name: String, + pub projected_name: String, + pub vtable_index: usize, + pub params: Vec, + pub return_type: RawComType, + pub semantic_hresult: Option, + pub enumerator_next: Option, + pub exact_contract: Option, + pub safe_array_contract_error: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RawExactMethodContractKind { + FixedCapacityBytes, + UnsafePrivateData, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawExactMethodContract { + pub kind: RawExactMethodContractKind, + pub declaring_namespace: &'static str, + pub declaring_interface: &'static str, + pub declaring_iid: &'static str, + pub method_name: &'static str, + pub vtable_index: usize, + pub buffer_param_index: usize, + pub capacity_param_index: usize, + pub actual_length_param_index: Option, + pub citation: &'static str, + pub reason: &'static str, +} + #[derive(Debug, Clone, PartialEq)] pub enum ParamDirection { In, @@ -83,6 +356,8 @@ pub struct ComInterfaceMeta { pub coclass_name: Option, pub own_methods_start: usize, pub referenced_enums: Vec, + pub raw_referenced_enums: Option>, + pub raw_methods: Option>, } #[derive(Debug, Clone)] @@ -221,6 +496,7 @@ fn parse_com_interface_from_index( .sum::(); let mut methods = Vec::new(); + let mut raw_methods = Vec::new(); let mut slot = root_offset; for (base_namespace, base_name, _) in base_chain .iter() @@ -228,14 +504,17 @@ fn parse_com_interface_from_index( .filter(|(_, name, _)| name != "IUnknown" && name != "IInspectable") { let base_def = index.get(base_namespace, base_name).next()?; - let mut base_methods = parse_methods(index, &base_def, slot); + let (mut base_methods, mut base_raw_methods) = parse_methods(index, &base_def, slot); slot += base_methods.len(); methods.append(&mut base_methods); + raw_methods.append(&mut base_raw_methods); } if slot != own_methods_start { return None; } - methods.extend(parse_methods(index, &def, slot)); + let (own_methods, own_raw_methods) = parse_methods(index, &def, slot); + methods.extend(own_methods); + raw_methods.extend(own_raw_methods); let iid = crate::meta::extract_iid(&def); let interface = InterfaceMeta { @@ -250,6 +529,7 @@ fn parse_com_interface_from_index( }; let (coclass_name, coclass_clsid) = find_coclass(index, namespace, name); let referenced_enums = collect_referenced_enums(index, &interface); + let raw_referenced_enums = Some(referenced_enums.clone()); Some(ComInterfaceMeta { interface, @@ -260,6 +540,8 @@ fn parse_com_interface_from_index( coclass_name, own_methods_start, referenced_enums, + raw_referenced_enums, + raw_methods: Some(raw_methods), }) } @@ -356,7 +638,7 @@ fn parse_methods( index: &reader::Index, def: &reader::TypeDef, base_offset: usize, -) -> Vec { +) -> (Vec, Vec) { def.methods() .enumerate() .map(|(index_in_interface, method)| { @@ -376,6 +658,7 @@ fn parse_methods( }) .unwrap_or(raw_name); let mut params = Vec::new(); + let mut raw_params = Vec::new(); let mut owned_outputs = Vec::new(); for (param_index, (param, typ)) in method .params() @@ -387,13 +670,37 @@ fn parse_methods( param.flags(), matches!(typ, windows_metadata::Type::Array(_)), ); + let raw_direction = raw_param_direction(param.flags()); + let metadata_array = + native_array_count_param(¶m).map(|count_param_index| RawArrayRelation { + count_param_index, + actual_length_param_index: None, + unit: RawCountUnit::Elements, + two_call: false, + projected_capacity: false, + constness: None, + evidence: vec![RawEvidence::MetadataAttribute("NativeArrayInfoAttribute")], + }); + let native_array = known_array_contract_override( + def.namespace(), + def.name(), + &crate::meta::extract_iid(def), + method.name(), + base_offset + index_in_interface, + param_index, + metadata_array, + ); let mapped_type = map_parameter_type(typ, &direction, index); - // Use the metadata's own `NativeArrayInfo(CountParamIndex = ...)` as the sole, - // authoritative source for buffer/count relationships. A `[out]` `PWSTR`/`PSTR` - // buffer with an authoritative count becomes a caller-owned string buffer; any - // other `[out]`/`[out, in]` array-shaped output with a count relationship is an - // unsupported native buffer (no name- or adjacency-based guessing). - if let Some(count_param_index) = native_array_count_param(¶m) { + let raw_type = map_raw_com_type(typ, index); + // Use NativeArrayInfo or an exact documented registry contract as the + // authoritative source for buffer/count relationships. A `[out]` + // `PWSTR`/`PSTR` buffer with an authoritative count becomes a caller-owned + // string buffer; any other `[out]`/`[out, in]` array-shaped output with a + // count relationship is an unsupported native buffer. + if let Some(count_param_index) = native_array + .as_ref() + .map(|relation| relation.count_param_index) + { if direction == ParamDirection::Out && is_string_buffer(&mapped_type) { if let Some(count_param_index) = count_param_index { direction = ParamDirection::OutStringBuffer { count_param_index }; @@ -402,27 +709,63 @@ fn parse_methods( direction = ParamDirection::UnsupportedNativeArray { count_param_index }; } } - let free_with = param - .find_attribute("FreeWithAttribute") - .and_then(|attribute| { - attribute - .value() - .into_iter() - .next() - .and_then(|(_, value)| match value { - windows_metadata::Value::Utf8(value) => Some(value), - _ => None, - }) - }) - .or_else(|| { - known_free_with(def.namespace(), def.name(), method.name(), typ, &direction) - }); - if let Some(free_with) = free_with { + let free_with = + param + .find_attribute("FreeWithAttribute") + .and_then(|attribute| { + attribute.value().into_iter().next().and_then( + |(_, value)| match value { + windows_metadata::Value::Utf8(value) => Some(value), + _ => None, + }, + ) + }) + .map(|function| RawFreeWith { + function, + evidence: RawEvidence::MetadataAttribute("FreeWithAttribute"), + }) + .or_else(|| { + known_free_with_override( + def.namespace(), + def.name(), + method.name(), + typ, + &direction, + ) + }); + let mut string_pointer_array = native_array.as_ref().and_then(|_| { + classify_raw_string_pointer_array(&raw_type, raw_direction, free_with.as_ref()) + }); + if def.namespace() == "Windows.Win32.System.Com" + && def.name() == "IEnumString" + && crate::meta::extract_iid(def) + .eq_ignore_ascii_case("00000101-0000-0000-c000-000000000046") + && method.name() == "Next" + && base_offset + index_in_interface == 3 + && param_index == 1 + && let Some(string) = &mut string_pointer_array + { + string.ownership = RawElementOwnership::CoTaskMemOwned; + } + if let Some(free_with) = &free_with { owned_outputs.push(OwnedOutput { param_index, - free_with, + free_with: free_with.function.clone(), }); } + raw_params.push(RawComParam { + name: param.name().to_string(), + typ: raw_type, + direction: raw_direction, + optional: param + .flags() + .contains(windows_metadata::ParamAttributes::Optional), + const_attribute: param.has_attribute("ConstAttribute"), + native_array, + string_pointer_array, + free_with, + safe_array_evidence: None, + }); params.push(ParamMeta { name: param.name().to_string(), typ: mapped_type, @@ -431,8 +774,29 @@ fn parse_methods( } let return_type = (signature.return_type != windows_metadata::Type::Void) .then(|| map_return_type(&signature.return_type, index)); - let preserve_hresult = method.has_attribute("CanReturnMultipleSuccessValuesAttribute") - || is_known_semantic_hresult(def.namespace(), def.name(), method.name()); + let mut semantic_hresult = + if method.has_attribute("CanReturnMultipleSuccessValuesAttribute") { + Some(RawEvidence::MetadataAttribute( + "CanReturnMultipleSuccessValuesAttribute", + )) + } else { + known_semantic_hresult_override(def.namespace(), def.name(), method.name()) + }; + let enumerator_next = known_enumerator_next_override( + def.namespace(), + def.name(), + &crate::meta::extract_iid(def), + method.name(), + base_offset + index_in_interface, + &raw_params, + &map_raw_com_type(&signature.return_type, index), + ); + if semantic_hresult.is_none() + && let Some(enumerator) = &enumerator_next + { + semantic_hresult = Some(enumerator.evidence.clone()); + } + let preserve_hresult = semantic_hresult.is_some(); // win32metadata does not embed textual doc comments (no sibling // `.xml` file like WinRT's `xml_doc.rs`), but it does attach a // `DocumentationAttribute` with a `learn.microsoft.com` reference @@ -450,34 +814,1143 @@ fn parse_methods( _ => None, }) }); - MethodMeta { - name, + let mut compatibility = MethodMeta { + name: name.clone(), vtable_index: base_offset + index_in_interface, params, return_type, preserve_hresult, doc, owned_outputs, + }; + let mut raw = RawComMethod { + declaring_namespace: def.namespace().to_string(), + declaring_interface: def.name().to_string(), + declaring_iid: crate::meta::extract_iid(def), + metadata_name: method.name().to_string(), + projected_name: name, + vtable_index: base_offset + index_in_interface, + params: raw_params, + return_type: map_raw_com_type(&signature.return_type, index), + semantic_hresult, + enumerator_next, + exact_contract: None, + safe_array_contract_error: None, + }; + apply_exact_method_contract( + def.namespace(), + def.name(), + &crate::meta::extract_iid(def), + &mut compatibility, + &mut raw, + ); + apply_safe_array_evidence(&mut raw); + (compatibility, raw) + }) + .unzip() +} + +fn apply_safe_array_evidence(raw: &mut RawComMethod) { + for parameter_index in 0..raw.params.len() { + let declaration_evidence = + crate::com_safe_array_registry::safe_array_evidence_for_declaration( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.metadata_name, + parameter_index, + ); + let is_safe_array = matches!( + &raw.params[parameter_index].typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Com" && name == "SAFEARRAY" + ); + if !is_safe_array { + if declaration_evidence.is_some() { + raw.safe_array_contract_error = Some(format!( + "{}.{} SAFEARRAY evidence signature no longer matches metadata", + raw.declaring_interface, raw.metadata_name + )); + } + continue; + } + let Some(evidence) = crate::com_safe_array_registry::registered_safe_array_evidence( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.declaring_iid, + &raw.metadata_name, + raw.vtable_index, + parameter_index, + ) else { + if declaration_evidence.is_some() { + raw.safe_array_contract_error = Some(format!( + "{}.{} SAFEARRAY evidence identity no longer matches metadata", + raw.declaring_interface, raw.metadata_name + )); + } + continue; + }; + if let Err(error) = validate_safe_array_evidence(raw, &evidence) { + raw.safe_array_contract_error = Some(error); + continue; + } + raw.params[parameter_index].safe_array_evidence = Some(evidence); + } +} + +fn validate_safe_array_evidence( + raw: &RawComMethod, + evidence: &RawSafeArrayEvidence, +) -> Result<(), String> { + if raw.declaring_namespace != evidence.declaring_namespace + || raw.declaring_interface != evidence.declaring_interface + || !raw + .declaring_iid + .eq_ignore_ascii_case(evidence.declaring_iid) + || raw.metadata_name != evidence.method_name + || raw.projected_name != evidence.method_name + || raw.vtable_index != evidence.vtable_index + || evidence.parameter_index >= raw.params.len() + { + return Err(format!( + "{}.{} SAFEARRAY evidence identity no longer matches metadata", + evidence.declaring_interface, evidence.method_name + )); + } + let parameter = &raw.params[evidence.parameter_index]; + if parameter.name != evidence.parameter_name + || !matches!( + ¶meter.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Com" && name == "SAFEARRAY" + ) + || parameter.optional + || parameter.native_array.is_some() + || parameter.string_pointer_array.is_some() + || parameter.free_with.is_some() + || match evidence.ownership { + RawSafeArrayOwnership::BorrowedInput => { + parameter.direction != RawParamDirection::In || parameter.typ.pointer_depth != 1 + } + RawSafeArrayOwnership::OwnedOutput => { + parameter.direction != RawParamDirection::Out || parameter.typ.pointer_depth != 2 + } + } + || parameter.typ.constness != RawConstness::Mutable + || evidence.element_iid.is_some() + != (evidence.element_vartype == RawSafeArrayVartype::Unknown) + || raw_method_shape(raw) != evidence.raw_method_shape + { + return Err(format!( + "{}.{} SAFEARRAY signature no longer matches exact documented evidence", + evidence.declaring_interface, evidence.method_name + )); + } + Ok(()) +} + +pub(crate) fn validate_attached_safe_array_evidence(raw: &RawComMethod) -> Result<(), String> { + if let Some(error) = &raw.safe_array_contract_error { + return Err(error.clone()); + } + for evidence in raw + .params + .iter() + .filter_map(|parameter| parameter.safe_array_evidence.as_ref()) + { + let registered = crate::com_safe_array_registry::registered_safe_array_evidence( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.declaring_iid, + &raw.metadata_name, + raw.vtable_index, + evidence.parameter_index, + ) + .ok_or_else(|| { + format!( + "{}.{} SAFEARRAY evidence is no longer registered", + evidence.declaring_interface, evidence.method_name + ) + })?; + if registered != *evidence { + return Err(format!( + "{}.{} SAFEARRAY evidence no longer matches the registry", + evidence.declaring_interface, evidence.method_name + )); + } + validate_safe_array_evidence(raw, evidence)?; + } + Ok(()) +} + +pub(crate) fn validate_borrowed_hwnd_output_evidence(raw: &RawComMethod) -> Result<(), String> { + let Some(evidence) = + crate::com_borrowed_handle_registry::borrowed_hwnd_evidence_for_declaration( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.metadata_name, + raw.vtable_index, + ) + else { + return Ok(()); + }; + let registered = crate::com_borrowed_handle_registry::registered_borrowed_hwnd_output( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.declaring_iid, + &raw.metadata_name, + raw.vtable_index, + evidence.parameter_index, + ) + .ok_or_else(|| { + format!( + "{}.{} borrowed HWND evidence identity no longer matches metadata", + evidence.declaring_interface, evidence.method_name + ) + })?; + if registered != evidence + || raw.params.len() != evidence.parameter_count + || evidence.parameter_index >= raw.params.len() + { + return Err(format!( + "{}.{} borrowed HWND evidence no longer matches the registry", + evidence.declaring_interface, evidence.method_name + )); + } + let parameter = &raw.params[evidence.parameter_index]; + if parameter.name != evidence.parameter_name + || parameter.direction != RawParamDirection::Out + || parameter.optional != evidence.optional + || parameter.const_attribute + || parameter.typ.pointer_depth != 1 + || parameter.typ.constness != RawConstness::Mutable + || !matches!( + ¶meter.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Foundation" && name == "HWND" + ) + || parameter.native_array.is_some() + || parameter.string_pointer_array.is_some() + || parameter.free_with.is_some() + || parameter.safe_array_evidence.is_some() + || !raw_hresult(&raw.return_type) + || raw.semantic_hresult.is_some() + || raw.enumerator_next.is_some() + || raw.exact_contract.is_some() + || raw.safe_array_contract_error.is_some() + { + return Err(format!( + "{}.{} signature no longer matches exact documented borrowed HWND evidence", + evidence.declaring_interface, evidence.method_name + )); + } + Ok(()) +} + +pub(crate) fn is_registered_borrowed_hwnd_output( + raw: &RawComMethod, + parameter_index: usize, +) -> bool { + crate::com_borrowed_handle_registry::registered_borrowed_hwnd_output( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.declaring_iid, + &raw.metadata_name, + raw.vtable_index, + parameter_index, + ) + .is_some() +} + +pub(crate) fn raw_method_shape(raw: &RawComMethod) -> String { + let mut shape = format!("{}@{}(", raw.metadata_name, raw.vtable_index); + for (index, parameter) in raw.params.iter().enumerate() { + if index != 0 { + shape.push(','); + } + + shape.push_str(¶meter.name); + shape.push(':'); + shape.push_str(match parameter.direction { + RawParamDirection::In => "in", + RawParamDirection::Out => "out", + RawParamDirection::InOut => "inout", + }); + shape.push(':'); + shape.push_str(if parameter.optional { + "optional" + } else { + "required" + }); + shape.push(':'); + shape.push_str(if parameter.const_attribute { + "constattr" + } else { + "noconstattr" + }); + shape.push(':'); + push_raw_type_shape(&mut shape, ¶meter.typ); + if let Some(relation) = ¶meter.native_array { + shape.push_str(&format!( + ":array={:?}/{:?}/{:?}/{}/{}/{:?}", + relation.count_param_index, + relation.actual_length_param_index, + relation.unit, + relation.two_call, + relation.projected_capacity, + relation.constness + )); + } + if let Some(array) = ¶meter.string_pointer_array { + shape.push_str(&format!( + ":strings={:?}/{}/{:?}/{:?}", + array.encoding, array.pointer_depth, array.constness, array.ownership + )); + } + if let Some(free_with) = ¶meter.free_with { + shape.push_str(":free="); + shape.push_str(&free_with.function); + } + } + shape.push_str(")->"); + push_raw_type_shape(&mut shape, &raw.return_type); + shape.push_str(if raw.semantic_hresult.is_some() { + ":semantic_hresult" + } else { + ":plain_hresult" + }); + shape.push_str(if raw.enumerator_next.is_some() { + ":enumerator_next" + } else { + ":not_enumerator_next" + }); + shape +} + +fn push_raw_type_shape(shape: &mut String, typ: &RawComType) { + match &typ.native_type { + RawNativeType::Void => shape.push_str("void"), + RawNativeType::Bool => shape.push_str("bool"), + RawNativeType::I8 => shape.push_str("i8"), + RawNativeType::U8 => shape.push_str("u8"), + RawNativeType::I16 => shape.push_str("i16"), + RawNativeType::U16 => shape.push_str("u16"), + RawNativeType::I32 => shape.push_str("i32"), + RawNativeType::U32 => shape.push_str("u32"), + RawNativeType::I64 => shape.push_str("i64"), + RawNativeType::U64 => shape.push_str("u64"), + RawNativeType::F32 => shape.push_str("f32"), + RawNativeType::F64 => shape.push_str("f64"), + RawNativeType::Char16 => shape.push_str("char16"), + RawNativeType::ISize => shape.push_str("isize"), + RawNativeType::USize => shape.push_str("usize"), + RawNativeType::String => shape.push_str("string"), + RawNativeType::Object => shape.push_str("object"), + RawNativeType::Named { + namespace, + name, + kind, + iid, + .. + } => { + shape.push_str(namespace); + shape.push('.'); + shape.push_str(name); + shape.push_str(&format!("[{kind:?}]")); + if let Some(iid) = iid { + shape.push('{'); + shape.push_str(iid); + shape.push('}'); + } + } + RawNativeType::Array(element) => { + shape.push_str("array<"); + push_raw_type_shape(shape, element); + shape.push('>'); + } + RawNativeType::FixedArray { element, count } => { + shape.push_str(&format!("fixed[{count}]<")); + push_raw_type_shape(shape, element); + shape.push('>'); + } + RawNativeType::Unknown(name) => { + shape.push_str("unknown<"); + shape.push_str(name); + shape.push('>'); + } + } + shape.push_str(&format!("/ptr{}/{:?}", typ.pointer_depth, typ.constness)); + if let Some(underlying) = &typ.underlying { + shape.push_str("/underlying="); + push_raw_type_shape(shape, underlying); + } +} + +fn apply_exact_method_contract( + interface_namespace: &str, + interface_name: &str, + interface_iid: &str, + compatibility: &mut MethodMeta, + raw: &mut RawComMethod, +) { + let Some(contract) = + registered_exact_method_contract(interface_namespace, interface_name, &raw.metadata_name) + else { + return; + }; + raw.exact_contract = Some(contract.clone()); + if !interface_iid.eq_ignore_ascii_case(contract.declaring_iid) + || raw.vtable_index != contract.vtable_index + { + return; + } + match contract.kind { + RawExactMethodContractKind::FixedCapacityBytes => { + if !raw_imf_get_blob_metadata_shape(raw) { + return; + } + let relation = raw.params[contract.buffer_param_index] + .native_array + .as_mut() + .expect("validated GetBlob NativeArrayInfo"); + relation.actual_length_param_index = contract.actual_length_param_index; + relation.unit = RawCountUnit::Bytes; + relation.projected_capacity = true; + relation.constness = Some(RawConstness::Mutable); + relation.evidence.push(RawEvidence::Override { + reason: contract.reason, + citation: contract.citation, + }); + let actual = contract + .actual_length_param_index + .expect("fixed-capacity GetBlob has an actual byte count"); + raw.params[actual].direction = RawParamDirection::Out; + compatibility.params[actual].direction = ParamDirection::Out; + } + RawExactMethodContractKind::UnsafePrivateData => { + let Some(buffer) = raw.params.get(contract.buffer_param_index) else { + return; + }; + if !raw_private_data_shape(raw, buffer.optional) { + return; + } + } + } +} + +fn known_exact_method_contract( + namespace: &str, + interface: &str, + iid: &str, + method: &str, + slot: usize, +) -> Option { + registered_exact_method_contract(namespace, interface, method).filter(|contract| { + iid.eq_ignore_ascii_case(contract.declaring_iid) && slot == contract.vtable_index + }) +} + +fn registered_exact_method_contract( + namespace: &str, + interface: &str, + method: &str, +) -> Option { + let (kind, buffer, capacity, actual, reason, citation) = match (namespace, interface, method) { + ("Windows.Win32.Media.MediaFoundation", "IMFAttributes", "GetBlob") => ( + RawExactMethodContractKind::FixedCapacityBytes, + 1, + 2, + Some(3), + "IMFAttributes::GetBlob documents a caller-allocated byte buffer with an input byte capacity and output actual byte count", + "https://learn.microsoft.com/windows/win32/api/mfobjects/nf-mfobjects-imfattributes-getblob", + ), + ("Windows.Win32.Graphics.Dxgi", "IDXGIObject", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "IDXGIObject::GetPrivateData may return an AddRef'd interface pointer set by SetPrivateDataInterface, so a generic Buffer result would lose ownership", + "https://learn.microsoft.com/windows/win32/api/dxgi/nf-dxgi-idxgiobject-getprivatedata", + ), + ("Windows.Win32.Graphics.Direct3D10", "ID3D10DeviceChild", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "ID3D10DeviceChild::GetPrivateData may return an AddRef'd interface pointer, and its documentation gives destructive rather than sizing semantics for NULL data", + "https://learn.microsoft.com/windows/win32/api/d3d10/nf-d3d10-id3d10devicechild-getprivatedata", + ), + ("Windows.Win32.Graphics.Direct3D10", "ID3D10Device", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "ID3D10Device::GetPrivateData may return an AddRef'd interface pointer, and its documentation gives destructive rather than sizing semantics for NULL data", + "https://learn.microsoft.com/windows/win32/api/d3d10/nf-d3d10-id3d10device-getprivatedata", + ), + ("Windows.Win32.Graphics.Direct3D11", "ID3D11DeviceChild", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "ID3D11DeviceChild::GetPrivateData may return an AddRef'd interface pointer set by SetPrivateDataInterface, so a generic Buffer result would lose ownership", + "https://learn.microsoft.com/windows/win32/api/d3d11/nf-d3d11-id3d11devicechild-getprivatedata", + ), + ("Windows.Win32.Graphics.Direct3D11", "ID3D11Device", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "ID3D11Device::GetPrivateData may return an AddRef'd interface pointer set by SetPrivateDataInterface, so a generic Buffer result would lose ownership", + "https://learn.microsoft.com/windows/win32/api/d3d11/nf-d3d11-id3d11device-getprivatedata", + ), + ("Windows.Win32.Graphics.Direct3D12", "ID3D12Object", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "ID3D12Object::GetPrivateData may return an AddRef'd interface pointer set by SetPrivateDataInterface, so a generic Buffer result would lose ownership", + "https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12object-getprivatedata", + ), + ("Windows.Win32.AI.MachineLearning.DirectML", "IDMLObject", "GetPrivateData") => ( + RawExactMethodContractKind::UnsafePrivateData, + 2, + 1, + Some(1), + "IDMLObject::GetPrivateData may return an AddRef'd interface pointer set by SetPrivateDataInterface, so a generic Buffer result would lose ownership", + "https://learn.microsoft.com/windows/win32/api/directml/nf-directml-idmlobject-getprivatedata", + ), + _ => return None, + }; + Some(RawExactMethodContract { + kind, + declaring_namespace: match interface { + "IMFAttributes" => "Windows.Win32.Media.MediaFoundation", + "IDXGIObject" => "Windows.Win32.Graphics.Dxgi", + "ID3D10DeviceChild" | "ID3D10Device" => "Windows.Win32.Graphics.Direct3D10", + "ID3D11DeviceChild" | "ID3D11Device" => "Windows.Win32.Graphics.Direct3D11", + "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", + "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", + _ => unreachable!("matched exact method interface"), + }, + declaring_interface: match interface { + "IMFAttributes" => "IMFAttributes", + "IDXGIObject" => "IDXGIObject", + "ID3D10DeviceChild" => "ID3D10DeviceChild", + "ID3D10Device" => "ID3D10Device", + "ID3D11DeviceChild" => "ID3D11DeviceChild", + "ID3D11Device" => "ID3D11Device", + "ID3D12Object" => "ID3D12Object", + "IDMLObject" => "IDMLObject", + _ => unreachable!("matched exact method interface"), + }, + declaring_iid: match kind { + RawExactMethodContractKind::FixedCapacityBytes => { + "2cd2d921-c447-44a7-a13c-4adabfc247e3" + } + RawExactMethodContractKind::UnsafePrivateData => match interface { + "IDXGIObject" => "aec22fb8-76f3-4639-9be0-28eb43a67a2e", + "ID3D10DeviceChild" => "9b7e4c00-342c-4106-a19f-4f2704f689f0", + "ID3D10Device" => "9b7e4c0f-342c-4106-a19f-4f2704f689f0", + "ID3D11DeviceChild" => "1841e5c8-16b0-489b-bcc8-44cfb0d5deae", + "ID3D11Device" => "db6f6ddb-ac77-4e88-8253-819df9bbf140", + "ID3D12Object" => "c4fec28f-7966-4e95-9f94-f431cb56c3b8", + "IDMLObject" => "c8263aac-9e0c-4a2d-9b8e-007521a3317c", + _ => unreachable!("matched exact private-data interface"), + }, + }, + method_name: match kind { + RawExactMethodContractKind::FixedCapacityBytes => "GetBlob", + RawExactMethodContractKind::UnsafePrivateData => "GetPrivateData", + }, + vtable_index: match (interface, method) { + ("IMFAttributes", "GetBlob") => 15, + ("IDXGIObject", "GetPrivateData") => 5, + ("ID3D10DeviceChild", "GetPrivateData") => 4, + ("ID3D10Device", "GetPrivateData") => 66, + ("ID3D11DeviceChild", "GetPrivateData") => 4, + ("ID3D11Device", "GetPrivateData") => 34, + ("ID3D12Object", "GetPrivateData") | ("IDMLObject", "GetPrivateData") => 3, + _ => unreachable!("matched exact method identity"), + }, + buffer_param_index: buffer, + capacity_param_index: capacity, + actual_length_param_index: actual, + citation, + reason, + }) +} + +fn raw_imf_get_blob_metadata_shape(raw: &RawComMethod) -> bool { + raw.params.len() == 4 + && raw.metadata_name == "GetBlob" + && raw.params[0].name == "guidKey" + && raw_refguid(&raw.params[0]) + && raw.params[1].name == "pBuf" + && raw_mutable_pointer( + &raw.params[1], + RawNativeType::U8, + RawParamDirection::Out, + false, + ) + && raw.params[1].native_array.as_ref().is_some_and(|relation| { + relation.count_param_index == Some(2) + && relation.actual_length_param_index.is_none() + && relation.unit == RawCountUnit::Elements + && !relation.two_call + && !relation.projected_capacity + }) + && raw.params[2].name == "cbBufSize" + && raw_u32_scalar(&raw.params[2], RawParamDirection::In, false) + && raw.params[3].name == "pcbBlobSize" + && raw_mutable_pointer( + &raw.params[3], + RawNativeType::U32, + RawParamDirection::InOut, + true, + ) + && raw_hresult(&raw.return_type) + && raw.semantic_hresult.is_none() + && raw.enumerator_next.is_none() +} + +fn raw_private_data_shape(raw: &RawComMethod, buffer_optional: bool) -> bool { + raw.params.len() == 3 + && raw.metadata_name == "GetPrivateData" + && raw_refguid(&raw.params[0]) + && raw_mutable_pointer( + &raw.params[1], + RawNativeType::U32, + RawParamDirection::InOut, + false, + ) + && raw_mutable_pointer( + &raw.params[2], + RawNativeType::Void, + RawParamDirection::Out, + buffer_optional, + ) + && raw.params.iter().all(|param| param.native_array.is_none()) + && raw_hresult(&raw.return_type) + && raw.semantic_hresult.is_none() + && raw.enumerator_next.is_none() +} + +fn raw_refguid(param: &RawComParam) -> bool { + param.direction == RawParamDirection::In + && !param.optional + && param.const_attribute + && param.typ.pointer_depth == 1 + && param.typ.constness == RawConstness::Mutable + && matches!( + ¶m.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "System" && name == "Guid" + ) + && param.free_with.is_none() +} + +fn raw_mutable_pointer( + param: &RawComParam, + native_type: RawNativeType, + direction: RawParamDirection, + optional: bool, +) -> bool { + param.direction == direction + && param.optional == optional + && !param.const_attribute + && param.typ.pointer_depth == 1 + && param.typ.constness == RawConstness::Mutable + && std::mem::discriminant(¶m.typ.native_type) == std::mem::discriminant(&native_type) + && param.free_with.is_none() +} + +fn raw_u32_scalar(param: &RawComParam, direction: RawParamDirection, optional: bool) -> bool { + param.direction == direction + && param.optional == optional + && !param.const_attribute + && param.typ.pointer_depth == 0 + && matches!(param.typ.native_type, RawNativeType::U32) + && param.free_with.is_none() +} + +fn raw_hresult(typ: &RawComType) -> bool { + typ.pointer_depth == 0 + && matches!( + &typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Foundation" && name == "HRESULT" + ) + && typ + .underlying + .as_deref() + .is_some_and(|underlying| matches!(underlying.native_type, RawNativeType::I32)) +} + +pub(crate) fn validate_exact_method_contract( + current_namespace: &str, + current_interface: &str, + current_iid: &str, + raw: &RawComMethod, + contract: &RawExactMethodContract, +) -> Result<(), String> { + let expected = known_exact_method_contract( + contract.declaring_namespace, + contract.declaring_interface, + contract.declaring_iid, + contract.method_name, + contract.vtable_index, + ) + .ok_or_else(|| "exact method contract is not registered".to_string())?; + if &expected != contract { + return Err("exact method contract evidence does not match the registry".into()); + } + if current_namespace == contract.declaring_namespace + && current_interface == contract.declaring_interface + && !current_iid.eq_ignore_ascii_case(contract.declaring_iid) + { + return Err(format!( + "{}.{} IID no longer matches exact contract evidence", + contract.declaring_namespace, contract.declaring_interface + )); + } + if raw.metadata_name != contract.method_name + || raw.projected_name != contract.method_name + || raw.vtable_index != contract.vtable_index + { + return Err(format!( + "{}.{} method identity or slot no longer matches exact contract evidence", + contract.declaring_interface, contract.method_name + )); + } + let valid_shape = match contract.kind { + RawExactMethodContractKind::FixedCapacityBytes => { + raw.params.len() == 4 + && raw.params[0].name == "guidKey" + && raw_refguid(&raw.params[0]) + && raw.params[1].name == "pBuf" + && raw_mutable_pointer( + &raw.params[1], + RawNativeType::U8, + RawParamDirection::Out, + false, + ) + && raw.params[1].native_array.as_ref().is_some_and(|relation| { + relation.count_param_index == Some(contract.capacity_param_index) + && relation.actual_length_param_index == contract.actual_length_param_index + && relation.unit == RawCountUnit::Bytes + && !relation.two_call + && relation.projected_capacity + && relation.constness == Some(RawConstness::Mutable) + && relation.evidence.iter().any(|evidence| { + matches!( + evidence, + RawEvidence::Override { reason, citation } + if *reason == contract.reason && *citation == contract.citation + ) + }) + }) + && raw.params[2].name == "cbBufSize" + && raw_u32_scalar(&raw.params[2], RawParamDirection::In, false) + && raw.params[3].name == "pcbBlobSize" + && raw_mutable_pointer( + &raw.params[3], + RawNativeType::U32, + RawParamDirection::Out, + true, + ) + && raw_hresult(&raw.return_type) + } + RawExactMethodContractKind::UnsafePrivateData => { + let optional = contract.declaring_interface != "IDXGIObject"; + raw_private_data_shape(raw, optional) + } + }; + if !valid_shape + || raw.semantic_hresult.is_some() + || raw.enumerator_next.is_some() + || contract.buffer_param_index >= raw.params.len() + || contract.capacity_param_index >= raw.params.len() + || contract + .actual_length_param_index + .is_some_and(|index| index >= raw.params.len()) + { + return Err(format!( + "{}.{} signature no longer matches exact contract evidence", + contract.declaring_interface, contract.method_name + )); + } + Ok(()) +} + +fn known_array_contract_override( + interface_namespace: &str, + interface_name: &str, + interface_iid: &str, + method_name: &str, + vtable_index: usize, + param_index: usize, + metadata: Option, +) -> Option { + if metadata.is_none() + && method_name == "Next" + && param_index == 1 + && let Some(contract) = crate::com_enumerator_registry::exact_contract( + interface_namespace, + interface_name, + interface_iid, + vtable_index, + ) + { + return Some(RawArrayRelation { + count_param_index: Some(0), + actual_length_param_index: None, + unit: RawCountUnit::Elements, + two_call: false, + projected_capacity: false, + constness: None, + evidence: vec![RawEvidence::Override { + reason: ENUMERATOR_ARRAY_REASON, + citation: contract.citation, + }], + }); + } + let exact = match ( + interface_namespace, + interface_name, + method_name, + param_index, + ) { + ("Windows.Win32.System.Com", "ISequentialStream", "Read", 0) => Some(( + 1, + Some(2), + RawCountUnit::Bytes, + false, + RawConstness::Mutable, + "ISequentialStream::Read documents pv as a cb-byte output buffer and pcbRead as the actual byte count", + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-isequentialstream-read", + false, + )), + ("Windows.Win32.System.Com", "ISequentialStream", "Write", 0) => Some(( + 1, + Some(2), + RawCountUnit::Bytes, + false, + RawConstness::Const, + "ISequentialStream::Write documents pv as a cb-byte const input buffer and pcbWritten as the actual byte count", + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-isequentialstream-write", + false, + )), + ("Windows.Win32.System.Com", "ITypeInfo", "GetNames", 1) => Some(( + 2, + Some(3), + RawCountUnit::Elements, + false, + RawConstness::Mutable, + "ITypeInfo::GetNames documents rgBstrNames as cMaxNames caller-owned slots and pcNames as the actual initialized count", + "https://learn.microsoft.com/windows/win32/api/oaidl/nf-oaidl-itypeinfo-getnames", + true, + )), + ("Windows.Win32.Storage.Imapi", "IDiscRecorder", "Init", 0) => Some(( + 1, + None, + RawCountUnit::Bytes, + false, + RawConstness::Const, + "IDiscRecorder::Init documents pbyUniqueID as a nulIDSize-byte input buffer", + "https://learn.microsoft.com/windows/win32/api/imapi/nf-imapi-idiscrecorder-init", + true, + )), + ("Windows.Win32.Storage.Imapi", "IDiscRecorder", "GetRecorderGUID", 0) => Some(( + 1, + Some(2), + RawCountUnit::Bytes, + true, + RawConstness::Mutable, + "IDiscRecorder::GetRecorderGUID explicitly documents NULL/zero sizing followed by a caller-owned byte buffer", + "https://learn.microsoft.com/windows/win32/api/imapi/nf-imapi-idiscrecorder-getrecorderguid", + true, + )), + ("Windows.Win32.Storage.Packaging.Opc", "IOpcSignatureCustomObject", "GetXml", 0) => { + Some(( + 1, + None, + RawCountUnit::Bytes, + false, + RawConstness::Mutable, + "IOpcSignatureCustomObject::GetXml documents a callee-allocated byte buffer and output byte count", + "https://learn.microsoft.com/windows/win32/api/msopc/nf-msopc-iopcsignaturecustomobject-getxml", + true, + )) + } + _ => None, + }; + let Some((count, actual, unit, two_call, constness, reason, citation, requires_metadata)) = + exact + else { + return metadata; + }; + if requires_metadata + && !metadata + .as_ref() + .is_some_and(|relation| relation.count_param_index == Some(count)) + { + return metadata; + } + let mut evidence = metadata + .map(|relation| relation.evidence) + .unwrap_or_default(); + evidence.push(RawEvidence::Override { reason, citation }); + Some(RawArrayRelation { + count_param_index: Some(count), + actual_length_param_index: actual, + unit, + two_call, + projected_capacity: false, + constness: Some(constness), + evidence, + }) +} + +const ENUMERATOR_ARRAY_REASON: &str = + "the exact registered IEnum*::Next contract defines rgelt as celt caller-owned element slots"; + +fn known_enumerator_next_override( + interface_namespace: &str, + interface_name: &str, + interface_iid: &str, + method_name: &str, + vtable_index: usize, + params: &[RawComParam], + return_type: &RawComType, +) -> Option { + let expected = crate::com_enumerator_registry::exact_contract( + interface_namespace, + interface_name, + interface_iid, + vtable_index, + )?; + let (expected_fetched_direction, expected_fetched_optional) = + crate::com_enumerator_registry::fetched_shape(interface_namespace, interface_name); + let expected_fetched_direction = match expected_fetched_direction { + crate::com_enumerator_registry::EnumeratorDirection::Out => RawParamDirection::Out, + crate::com_enumerator_registry::EnumeratorDirection::InOut => RawParamDirection::InOut, + }; + let expected_values_direction = + match crate::com_enumerator_registry::values_direction(interface_namespace, interface_name) + { + crate::com_enumerator_registry::EnumeratorDirection::Out => RawParamDirection::Out, + crate::com_enumerator_registry::EnumeratorDirection::InOut => RawParamDirection::InOut, + }; + let exact_hresult = return_type.pointer_depth == 0 + && matches!( + &return_type.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Foundation" && name == "HRESULT" + ) + && matches!( + return_type.underlying.as_deref(), + Some(RawComType { + native_type: RawNativeType::I32, + pointer_depth: 0, + .. + }) + ); + let exact_count = |param: &RawComParam, direction, pointer_depth| { + param.direction == direction + && !param.const_attribute + && param.typ.pointer_depth == pointer_depth + && matches!(param.typ.native_type, RawNativeType::U32) + && param.typ.underlying.is_none() + }; + let exact_element = params.get(1).is_some_and(|param| { + let exact_known_type = match ¶m.typ.native_type { + RawNativeType::Named { + namespace, + name, + kind, + iid, + .. + } => { + namespace == expected.element_namespace + && name == expected.element_name + && matches!( + (expected.element_kind, kind), + ( + crate::com_enumerator_registry::EnumeratorElementKind::Interface, + RawNamedKind::Interface + ) | ( + crate::com_enumerator_registry::EnumeratorElementKind::Struct, + RawNamedKind::Struct + ) | ( + crate::com_enumerator_registry::EnumeratorElementKind::Unknown, + RawNamedKind::Unknown + ) + ) + && match (expected.element_iid, iid.as_deref()) { + (Some(expected), Some(actual)) => actual.eq_ignore_ascii_case(expected), + (None, None) => true, + _ => false, + } } + _ => false, + }; + param.direction == expected_values_direction + && !param.optional + && !param.const_attribute + && (param.free_with.is_none() + || param.free_with.as_ref().is_some_and(|free_with| { + free_with.function == "SysFreeString" + && matches!( + ¶m.typ.native_type, + RawNativeType::Named { namespace, name, .. } + if namespace == "Windows.Win32.Foundation" && name == "BSTR" + ) + })) + && (param.string_pointer_array.is_none() + || (interface_namespace == "Windows.Win32.System.Com" + && interface_name == "IEnumString")) + && param.typ.pointer_depth == 1 + && param.typ.constness == RawConstness::Mutable + && exact_known_type + && param.native_array.as_ref().is_some_and(|relation| { + relation.count_param_index == Some(0) + && relation.actual_length_param_index.is_none() + && relation.unit == RawCountUnit::Elements + && !relation.two_call + && relation.evidence.iter().any(|evidence| { + matches!( + evidence, + RawEvidence::MetadataAttribute("NativeArrayInfoAttribute") + ) || matches!( + evidence, + RawEvidence::Override { reason, citation } + if *reason == ENUMERATOR_ARRAY_REASON + && *citation == expected.citation + ) + }) + }) + }); + let exact_shape = method_name == "Next" + && params.len() == 3 + && params + .first() + .is_some_and(|param| exact_count(param, RawParamDirection::In, 0) && !param.optional) + && exact_element + && params.get(2).is_some_and(|param| { + exact_count(param, expected_fetched_direction, 1) + && param.optional == expected_fetched_optional + && param.typ.constness == RawConstness::Mutable + && param.native_array.is_none() + && param.free_with.is_none() }) - .collect() + && exact_hresult; + exact_shape.then_some(RawEnumeratorNext { + capacity_param_index: 0, + values_param_index: 1, + fetched_param_index: 2, + fetched_optional_for_single: expected_fetched_optional, + evidence: RawEvidence::Override { + reason: "the standard IEnum* contract defines pceltFetched as the initialized element count and permits omission only where this exact interface metadata marks it optional", + citation: expected.citation, + }, + }) } -fn known_free_with( +fn is_registered_enumerator_interface(interface_namespace: &str, interface_name: &str) -> bool { + crate::com_enumerator_registry::contract_for_declaration(interface_namespace, interface_name) + .is_some() +} + +pub(crate) fn validate_attached_enumerator_evidence(raw: &RawComMethod) -> Result<(), String> { + if raw.metadata_name != "Next" { + return if raw.enumerator_next.is_none() { + Ok(()) + } else { + Err(format!( + "{}.{} has EnumeratorNext evidence on a non-Next method", + raw.declaring_interface, raw.metadata_name + )) + }; + } + let registered = + is_registered_enumerator_interface(&raw.declaring_namespace, &raw.declaring_interface); + if raw.declaring_interface.starts_with("IEnum") && !registered { + return Err(format!( + "{}.Next requires an exact enumerator registry entry", + raw.declaring_interface + )); + } + if !registered { + return if raw.enumerator_next.is_none() { + Ok(()) + } else { + Err(format!( + "{}.Next has unregistered EnumeratorNext evidence", + raw.declaring_interface + )) + }; + } + let expected = known_enumerator_next_override( + &raw.declaring_namespace, + &raw.declaring_interface, + &raw.declaring_iid, + &raw.metadata_name, + raw.vtable_index, + &raw.params, + &raw.return_type, + ) + .ok_or_else(|| { + format!( + "{}.Next signature no longer matches exact enumerator evidence (EnumeratorNext)", + raw.declaring_interface + ) + })?; + if raw.enumerator_next.as_ref() != Some(&expected) { + return Err(format!( + "{}.Next EnumeratorNext evidence no longer matches the registry", + raw.declaring_interface + )); + } + Ok(()) +} + +fn known_free_with_override( interface_namespace: &str, interface_name: &str, method_name: &str, typ: &windows_metadata::Type, direction: &ParamDirection, -) -> Option { +) -> Option { let (windows_metadata::Type::PtrMut(inner, depth) | windows_metadata::Type::PtrConst(inner, depth)) = typ else { return None; }; - if !matches!(direction, ParamDirection::Out | ParamDirection::InOut) { + if !matches!( + direction, + ParamDirection::Out | ParamDirection::InOut | ParamDirection::UnsupportedNativeArray { .. } + ) { return None; } + if *depth == 1 && matches!( inner.as_ref(), @@ -485,7 +1958,13 @@ fn known_free_with( if name.namespace == "Windows.Win32.Foundation" && name.name == "BSTR" ) { - return Some("SysFreeString".into()); + return Some(RawFreeWith { + function: "SysFreeString".into(), + evidence: RawEvidence::Override { + reason: "Windows.Win32 metadata omits scalar BSTR output cleanup", + citation: "https://learn.microsoft.com/windows/win32/api/oleauto/nf-oleauto-sysfreestring", + }, + }); } let is_known_cotaskmem_wide_string = matches!( (interface_namespace, interface_name, method_name), @@ -501,31 +1980,110 @@ fn known_free_with( if name.namespace == "Windows.Win32.Foundation" && name.name == "PWSTR" ) { - return Some("CoTaskMemFree".into()); + return Some(RawFreeWith { + function: "CoTaskMemFree".into(), + evidence: RawEvidence::Override { + reason: "API documentation assigns the returned string to the COM task allocator", + citation: match (interface_namespace, interface_name, method_name) { + ("Windows.Win32.UI.Shell", "IShellItem", "GetDisplayName") => { + "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellitem-getdisplayname" + } + ("Windows.Win32.UI.Shell", "IFileDialog", "GetFileName") => { + "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-getfilename" + } + ("Windows.Win32.System.Com", "IPersistFile", "GetCurFile") => { + "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile" + } + _ => unreachable!("guarded by exact override registry"), + }, + }, + }); + } + if *depth == 2 + && matches!( + (interface_namespace, interface_name, method_name), + ( + "Windows.Win32.Storage.Packaging.Opc", + "IOpcSignatureCustomObject", + "GetXml" + ) + ) + && matches!(inner.as_ref(), windows_metadata::Type::U8) + { + return Some(RawFreeWith { + function: "CoTaskMemFree".into(), + evidence: RawEvidence::Override { + reason: "IOpcSignatureCustomObject::GetXml assigns the returned byte buffer to the COM task allocator", + citation: "https://learn.microsoft.com/windows/win32/api/msopc/nf-msopc-iopcsignaturecustomobject-getxml", + }, + }); } // Windows.Win32.winmd omits FreeWith on IShellLink::GetIDList. - if *depth < 2 { + if *depth < 2 + || !matches!( + (interface_namespace, interface_name, method_name), + ("Windows.Win32.UI.Shell", "IShellLinkW", "GetIDList") + | ("Windows.Win32.UI.Shell", "IShellLinkA", "GetIDList") + ) + { return None; } match inner.as_ref() { windows_metadata::Type::Name(name) if name.namespace == "Windows.Win32.UI.Shell.Common" && name.name == "ITEMIDLIST" => { - Some("CoTaskMemFree".into()) + Some(RawFreeWith { + function: "CoTaskMemFree".into(), + evidence: RawEvidence::Override { + reason: "IShellLink::GetIDList returns a PIDL allocated by the Shell task allocator", + citation: "https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getidlist", + }, + }) } _ => None, } } -fn is_known_semantic_hresult( +#[cfg(test)] +fn known_free_with( interface_namespace: &str, interface_name: &str, method_name: &str, -) -> bool { + typ: &windows_metadata::Type, + direction: &ParamDirection, +) -> Option { + known_free_with_override( + interface_namespace, + interface_name, + method_name, + typ, + direction, + ) + .map(|free_with| free_with.function) +} + +fn known_semantic_hresult_override( + interface_namespace: &str, + interface_name: &str, + method_name: &str, +) -> Option { matches!( (interface_namespace, interface_name, method_name), ("Windows.Win32.System.Com", "IPersistFile", "GetCurFile") ) + .then_some(RawEvidence::Override { + reason: "GetCurFile uses S_OK and S_FALSE as distinct successful ownership states", + citation: "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-ipersistfile-getcurfile", + }) +} + +#[cfg(test)] +fn is_known_semantic_hresult( + interface_namespace: &str, + interface_name: &str, + method_name: &str, +) -> bool { + known_semantic_hresult_override(interface_namespace, interface_name, method_name).is_some() } fn map_parameter_type( @@ -562,6 +2120,292 @@ fn map_return_type(typ: &windows_metadata::Type, index: &reader::Index) -> TypeM } } +fn map_raw_com_type(typ: &windows_metadata::Type, index: &reader::Index) -> RawComType { + map_raw_com_type_inner(typ, index, &mut Vec::new()) +} + +fn map_raw_com_type_inner( + typ: &windows_metadata::Type, + index: &reader::Index, + layout_stack: &mut Vec<(String, String)>, +) -> RawComType { + use windows_metadata::Type; + + let scalar = |native_type| RawComType { + native_type, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + }; + match typ { + Type::PtrMut(inner, depth) => add_raw_pointer( + map_raw_com_type_inner(inner, index, layout_stack), + *depth, + RawConstness::Mutable, + ), + Type::PtrConst(inner, depth) => add_raw_pointer( + map_raw_com_type_inner(inner, index, layout_stack), + *depth, + RawConstness::Const, + ), + Type::ConstRef(inner) => add_raw_pointer( + map_raw_com_type_inner(inner, index, layout_stack), + 1, + RawConstness::Const, + ), + Type::Void => scalar(RawNativeType::Void), + Type::Bool => scalar(RawNativeType::Bool), + Type::I8 => scalar(RawNativeType::I8), + Type::U8 => scalar(RawNativeType::U8), + Type::I16 => scalar(RawNativeType::I16), + Type::U16 => scalar(RawNativeType::U16), + Type::I32 => scalar(RawNativeType::I32), + Type::U32 => scalar(RawNativeType::U32), + Type::I64 => scalar(RawNativeType::I64), + Type::U64 => scalar(RawNativeType::U64), + Type::F32 => scalar(RawNativeType::F32), + Type::F64 => scalar(RawNativeType::F64), + Type::Char => scalar(RawNativeType::Char16), + Type::ISize => scalar(RawNativeType::ISize), + Type::USize => scalar(RawNativeType::USize), + Type::String => scalar(RawNativeType::String), + Type::Object => scalar(RawNativeType::Object), + Type::Name(name) => { + if !name.generics.is_empty() { + return scalar(RawNativeType::Unknown(format!( + "closed generic type {}.{} requires a computed IID", + name.namespace, name.name + ))); + } + let definition = index.get(&name.namespace, &name.name).next(); + let underlying = definition.as_ref().and_then(|definition| { + let mut fields = definition.fields().filter(|field| { + !field + .flags() + .contains(windows_metadata::FieldAttributes::Static) + }); + let field = fields.next()?; + (matches!(field.name(), "Value" | "value__") && fields.next().is_none()) + .then(|| Box::new(map_raw_com_type_inner(&field.ty(), index, layout_stack))) + }); + let kind = definition + .as_ref() + .map_or(RawNamedKind::Unknown, |definition| { + if definition + .flags() + .contains(windows_metadata::TypeAttributes::Interface) + { + RawNamedKind::Interface + } else if parse_com_enum_def(definition).is_some() { + RawNamedKind::Enum + } else if parse_com_delegate_def(definition).is_some() { + RawNamedKind::Delegate + } else if definition.extends().is_some_and(|base| { + base.namespace() == "System" && base.name() == "ValueType" + }) { + RawNamedKind::Struct + } else { + RawNamedKind::RuntimeClass + } + }); + let iid = definition.as_ref().and_then(|definition| { + let iid = if kind == RawNamedKind::RuntimeClass { + raw_runtime_class_default_iid(definition, index)? + } else { + crate::meta::extract_iid(definition) + }; + (!iid.is_empty()).then_some(iid) + }); + let layout = (kind == RawNamedKind::Struct).then(|| { + Box::new(parse_raw_native_layouts( + index, + &name.namespace, + &name.name, + layout_stack, + )) + }); + RawComType { + native_type: RawNativeType::Named { + namespace: name.namespace.clone(), + name: name.name.clone(), + kind, + iid, + layout, + }, + underlying, + pointer_depth: 0, + constness: RawConstness::Unspecified, + } + } + Type::Array(inner) => scalar(RawNativeType::Array(Box::new(map_raw_com_type_inner( + inner, + index, + layout_stack, + )))), + Type::ArrayFixed(inner, count) => scalar(RawNativeType::FixedArray { + element: Box::new(map_raw_com_type_inner(inner, index, layout_stack)), + count: *count, + }), + unsupported => scalar(RawNativeType::Unknown(format!("{unsupported:?}"))), + } +} + +fn parse_raw_native_layouts( + index: &reader::Index, + namespace: &str, + name: &str, + layout_stack: &mut Vec<(String, String)>, +) -> RawNativeLayoutSet { + let key = (namespace.to_string(), name.to_string()); + if layout_stack.contains(&key) { + return RawNativeLayoutSet { + recursive: true, + variants: Vec::new(), + }; + } + layout_stack.push(key); + let variants = index + .get(namespace, name) + .filter(|definition| { + definition + .extends() + .is_some_and(|base| base.namespace() == "System" && base.name() == "ValueType") + }) + .map(|definition| { + let flags = definition.flags(); + let is_union = is_known_win32_union(&definition.namespace(), definition.name()); + let kind = if flags.contains(windows_metadata::TypeAttributes::SequentialLayout) { + RawLayoutKind::Sequential + } else if flags.contains(windows_metadata::TypeAttributes::ExplicitLayout) && is_union { + RawLayoutKind::Explicit + } else { + RawLayoutKind::Unknown + }; + let (packing, declared_size) = + definition + .class_layout() + .map_or((RawPacking::Default, None), |layout| { + ( + if layout.packing_size() == 0 { + RawPacking::Default + } else { + RawPacking::Explicit(layout.packing_size()) + }, + (layout.class_size() != 0).then_some(layout.class_size() as usize), + ) + }); + let fields = definition + .fields() + .filter(|field| field.name() != "value__" && field.constant().is_none()) + .map(|field| { + let field_type = field.ty(); + let (typ, fixed_count) = match field_type { + windows_metadata::Type::ArrayFixed(ref element, count) => ( + map_raw_com_type_inner(element, index, layout_stack), + Some(count), + ), + _ => ( + map_raw_com_type_inner(&field_type, index, layout_stack), + None, + ), + }; + RawNativeField { + name: field.name().to_string(), + typ, + // windows-metadata 0.59 does not expose the ECMA-335 + // FieldLayout table. Explicit Win32 layouts therefore + // remain fail-closed unless an adapter supplies offsets. + explicit_offset: None, + fixed_count, + bitfield: field.has_attribute("NativeBitfieldAttribute"), + flexible_array: field.has_attribute("FlexibleArrayAttribute"), + } + }) + .collect(); + RawNativeLayout { + architectures: supported_architecture_mask(&definition), + kind, + packing, + declared_size, + fields, + is_union, + } + }) + .collect(); + layout_stack.pop(); + RawNativeLayoutSet { + recursive: false, + variants, + } +} + +fn is_known_win32_union(namespace: &str, name: &str) -> bool { + matches!((namespace, name), ("Windows.Win32.System.Com", "BINDPTR")) +} + +#[cfg(test)] +mod explicit_layout_tests { + use super::is_known_win32_union; + + #[test] + fn explicit_layout_requires_exact_union_identity() { + assert!(is_known_win32_union("Windows.Win32.System.Com", "BINDPTR")); + assert!(!is_known_win32_union("Contoso", "BINDPTR")); + assert!(!is_known_win32_union( + "Windows.Win32.System.Com", + "EXPLICIT_STRUCT" + )); + } +} + +fn supported_architecture_mask(definition: &reader::TypeDef) -> u8 { + definition + .find_attribute("SupportedArchitectureAttribute") + .and_then(|attribute| { + attribute + .value() + .into_iter() + .next() + .and_then(|(_, value)| match value { + windows_metadata::Value::I32(value) => u8::try_from(value).ok(), + windows_metadata::Value::U32(value) => u8::try_from(value).ok(), + _ => None, + }) + }) + .unwrap_or(0b111) + & 0b111 +} + +fn raw_runtime_class_default_iid( + definition: &reader::TypeDef, + index: &reader::Index, +) -> Option { + definition + .interface_impls() + .find(|implementation| implementation.has_attribute("DefaultAttribute")) + .and_then(|implementation| match implementation.interface(&[]) { + windows_metadata::Type::Name(name) => index.get(&name.namespace, &name.name).next(), + _ => None, + }) + .map(|interface| crate::meta::extract_iid(&interface)) + .filter(|iid| !iid.is_empty()) +} + +fn add_raw_pointer(mut inner: RawComType, depth: usize, constness: RawConstness) -> RawComType { + if inner.pointer_depth > 0 + && inner.constness != RawConstness::Unspecified + && inner.constness != constness + { + inner.constness = RawConstness::Unspecified; + } else if inner.constness != RawConstness::Unspecified { + inner.constness = constness; + } else if inner.pointer_depth == 0 { + inner.constness = constness; + } + inner.pointer_depth = inner.pointer_depth.saturating_add(depth); + inner +} + fn map_com_type(typ: &windows_metadata::Type, index: &reader::Index) -> TypeMeta { match typ { windows_metadata::Type::ISize => native_isize_type(), @@ -722,6 +2566,58 @@ fn native_array_count_param(param: &reader::MethodParam) -> Option Some(count) } +fn classify_raw_string_pointer_array( + typ: &RawComType, + direction: RawParamDirection, + free_with: Option<&RawFreeWith>, +) -> Option { + if typ.pointer_depth == 0 { + return None; + } + let RawNativeType::Named { + namespace, + name, + layout, + .. + } = &typ.native_type + else { + return None; + }; + if namespace != "Windows.Win32.Foundation" { + return None; + } + let encoding = if matches!(name.as_str(), "PWSTR" | "PCWSTR" | "LPWSTR" | "LPCWSTR") { + RawStringEncoding::Utf16 + } else if matches!(name.as_str(), "PSTR" | "PCSTR" | "LPSTR" | "LPCSTR") { + RawStringEncoding::Ansi + } else { + return None; + }; + let (pointer_depth, constness) = layout + .as_deref() + .and_then(|set| set.variants.first()) + .and_then(|layout| layout.fields.first()) + .map(|field| (field.typ.pointer_depth, field.typ.constness)) + .unwrap_or(( + 1, + if matches!(name.as_str(), "PCWSTR" | "LPCWSTR" | "PCSTR" | "LPCSTR") { + RawConstness::Const + } else { + RawConstness::Mutable + }, + )); + Some(RawStringPointerArray { + encoding, + pointer_depth, + constness, + ownership: if direction == RawParamDirection::In && free_with.is_none() { + RawElementOwnership::Borrowed + } else { + RawElementOwnership::Unknown + }, + }) +} + fn classify_direction(flags: windows_metadata::ParamAttributes, is_array: bool) -> ParamDirection { let is_in = flags.contains(windows_metadata::ParamAttributes::In); let is_out = flags.contains(windows_metadata::ParamAttributes::Out); @@ -733,6 +2629,16 @@ fn classify_direction(flags: windows_metadata::ParamAttributes, is_array: bool) } } +fn raw_param_direction(flags: windows_metadata::ParamAttributes) -> RawParamDirection { + let is_in = flags.contains(windows_metadata::ParamAttributes::In); + let is_out = flags.contains(windows_metadata::ParamAttributes::Out); + match (is_in, is_out) { + (true, true) => RawParamDirection::InOut, + (_, true) => RawParamDirection::Out, + _ => RawParamDirection::In, + } +} + fn find_coclass( index: &reader::Index, namespace: &str, @@ -884,6 +2790,105 @@ pub fn discover_newest_windows_winmd() -> Option { mod tests { use super::*; + #[test] + fn safe_array_registry_matches_configured_win32_metadata() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let index = crate::meta::load_index(&winmd).expect("configured Win32 metadata must load"); + let evidence = crate::com_safe_array_registry::all_safe_array_evidence(); + let mut interfaces = std::collections::BTreeMap::new(); + for entry in evidence { + interfaces + .entry((entry.declaring_namespace, entry.declaring_interface)) + .or_insert_with(|| { + parse_com_interface_from_index( + &index, + entry.declaring_namespace, + entry.declaring_interface, + ) + .unwrap_or_else(|| { + panic!( + "{}.{} is missing", + entry.declaring_namespace, entry.declaring_interface + ) + }) + }); + } + for entry in evidence { + let interface = &interfaces[&(entry.declaring_namespace, entry.declaring_interface)]; + let method = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| { + method.declaring_namespace == entry.declaring_namespace + && method.declaring_interface == entry.declaring_interface + && method + .declaring_iid + .eq_ignore_ascii_case(entry.declaring_iid) + && method.metadata_name == entry.method_name + && method.vtable_index == entry.vtable_index + }) + .unwrap_or_else(|| { + panic!( + "{}.{}::{}@{} is missing", + entry.declaring_namespace, + entry.declaring_interface, + entry.method_name, + entry.vtable_index + ) + }); + assert!( + method.safe_array_contract_error.is_none(), + "{}.{}::{}@{}: {:?}", + entry.declaring_namespace, + entry.declaring_interface, + entry.method_name, + entry.vtable_index, + method.safe_array_contract_error + ); + assert_eq!( + method + .params + .get(entry.parameter_index) + .and_then(|param| param.safe_array_evidence.as_ref()), + Some(entry), + "{}.{}::{}@{} parameter {}", + entry.declaring_namespace, + entry.declaring_interface, + entry.method_name, + entry.vtable_index, + entry.parameter_index + ); + } + + let entry = &evidence[0]; + let interface = &interfaces[&(entry.declaring_namespace, entry.declaring_interface)]; + let mut drifted = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| { + method.declaring_namespace == entry.declaring_namespace + && method.declaring_interface == entry.declaring_interface + && method.metadata_name == entry.method_name + && method.vtable_index == entry.vtable_index + }) + .unwrap() + .clone(); + drifted.params[entry.parameter_index].typ.native_type = RawNativeType::U32; + drifted.params[entry.parameter_index].safe_array_evidence = None; + drifted.safe_array_contract_error = None; + apply_safe_array_evidence(&mut drifted); + assert!( + drifted.safe_array_contract_error.is_some(), + "registered SAFEARRAY type drift must fail closed" + ); + } + fn interface(name: &str, iid: &str, base_chain: &[&str]) -> ComInterfaceMeta { ComInterfaceMeta { interface: InterfaceMeta { @@ -899,6 +2904,8 @@ mod tests { coclass_name: None, own_methods_start: 3, referenced_enums: Vec::new(), + raw_referenced_enums: None, + raw_methods: None, } } @@ -934,6 +2941,61 @@ mod tests { ); } + #[test] + fn recognized_exact_contract_shape_drift_remains_fail_closed() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let mut interface = parse_com_interface( + &winmd, + "Windows.Win32.Media.MediaFoundation", + "IMFAttributes", + ) + .unwrap(); + let raw_index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetBlob") + .unwrap(); + let method_index = interface + .interface + .methods + .iter() + .position(|method| method.name == "GetBlob") + .unwrap(); + let raw = &mut interface.raw_methods.as_mut().unwrap()[raw_index]; + raw.params.truncate(1); + raw.exact_contract = None; + let compatibility = &mut interface.interface.methods[method_index]; + apply_exact_method_contract( + "Windows.Win32.Media.MediaFoundation", + "IMFAttributes", + "2cd2d921-c447-44a7-a13c-4adabfc247e3", + compatibility, + raw, + ); + + let contract = raw + .exact_contract + .as_ref() + .expect("recognized method must retain fail-closed contract evidence"); + assert!( + validate_exact_method_contract( + "Windows.Win32.Media.MediaFoundation", + "IMFAttributes", + "2cd2d921-c447-44a7-a13c-4adabfc247e3", + raw, + contract, + ) + .is_err() + ); + } + #[test] fn hstring_mapping_requires_the_canonical_namespace() { assert!(is_canonical_hstring_name( @@ -943,6 +3005,272 @@ mod tests { assert!(!is_canonical_hstring_name("Contoso.Interop", "HSTRING")); } + #[test] + fn mixed_pointer_constness_fails_closed_as_unspecified() { + let scalar = RawComType { + native_type: RawNativeType::U8, + underlying: None, + pointer_depth: 0, + constness: RawConstness::Unspecified, + }; + let inner = add_raw_pointer(scalar, 1, RawConstness::Const); + let mixed = add_raw_pointer(inner, 1, RawConstness::Mutable); + + assert_eq!(mixed.pointer_depth, 2); + assert_eq!(mixed.constness, RawConstness::Unspecified); + } + + #[test] + fn only_terminated_character_pointer_aliases_are_strings() { + let named = |name: &str| RawComType { + native_type: RawNativeType::Named { + namespace: "Windows.Win32.Foundation".into(), + name: name.into(), + kind: RawNamedKind::Struct, + iid: None, + layout: None, + }, + underlying: None, + pointer_depth: 1, + constness: RawConstness::Const, + }; + for name in [ + "PWSTR", "PCWSTR", "LPWSTR", "LPCWSTR", "PSTR", "PCSTR", "LPSTR", "LPCSTR", + ] { + assert!( + classify_raw_string_pointer_array(&named(name), RawParamDirection::In, None) + .is_some(), + "{name}" + ); + } + for name in ["PWCHAR", "PCWCHAR", "LPWCH", "LPCWCH", "LPCH", "LPCCH"] { + assert!( + classify_raw_string_pointer_array(&named(name), RawParamDirection::In, None) + .is_none(), + "{name}" + ); + } + } + + #[test] + fn enumerator_contracts_require_exact_registered_identity() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + for (namespace, name) in [ + ("Windows.Win32.System.Com", "IEnumGUID"), + ("Windows.Win32.System.Com", "IEnumConnectionPoints"), + ("Windows.Win32.System.Ole", "IEnumVARIANT"), + ("Windows.Win32.System.Com", "IEnumString"), + ("Windows.Win32.System.Com", "IEnumUnknown"), + ("Windows.Win32.Storage.VirtualDiskService", "IEnumVdsObject"), + ("Windows.Win32.System.Com.Events", "IEnumEventObject"), + ("Windows.Win32.UI.TextServices", "IEnumITfCompositionView"), + ] { + let interface = parse_com_interface(&winmd, namespace, name) + .unwrap_or_else(|| panic!("{namespace}.{name} is missing")); + let next = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| { + method.declaring_namespace == namespace + && method.declaring_interface == name + && method.metadata_name == "Next" + }) + .unwrap_or_else(|| panic!("{namespace}.{name}::Next is missing")); + assert!( + next.enumerator_next.is_some(), + "{namespace}.{name}: slot={}, element={:?}", + next.vtable_index, + next.params[1].typ + ); + } + + let unknown = + parse_com_interface(&winmd, "Windows.Win32.System.Com", "IEnumUnknown").unwrap(); + let next = unknown + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Next") + .unwrap(); + assert!( + known_enumerator_next_override( + "Windows.Win32.System.Com", + "IEnumUnknown", + "ffffffff-ffff-ffff-ffff-ffffffffffff", + "Next", + next.vtable_index, + &next.params, + &next.return_type, + ) + .is_none() + ); + assert!( + known_enumerator_next_override( + "Contoso", + "IEnumUnknown", + &unknown.interface.iid, + "Next", + next.vtable_index, + &next.params, + &next.return_type, + ) + .is_none() + ); + assert!( + known_enumerator_next_override( + "Windows.Win32.System.Com", + "IEnumUnknown", + &unknown.interface.iid, + "Next", + next.vtable_index + 1, + &next.params, + &next.return_type, + ) + .is_none() + ); + let mut element_drift = next.params.clone(); + { + let RawNativeType::Named { name, .. } = &mut element_drift[1].typ.native_type else { + panic!("IEnumUnknown must expose a named IUnknown element"); + }; + *name = "INotUnknown".into(); + } + assert!( + known_enumerator_next_override( + "Windows.Win32.System.Com", + "IEnumUnknown", + &unknown.interface.iid, + "Next", + next.vtable_index, + &element_drift, + &next.return_type, + ) + .is_none() + ); + { + let RawNativeType::Named { name, iid, .. } = &mut element_drift[1].typ.native_type + else { + unreachable!() + }; + *name = "IUnknown".into(); + *iid = Some("ffffffff-ffff-ffff-ffff-ffffffffffff".into()); + } + assert!( + known_enumerator_next_override( + "Windows.Win32.System.Com", + "IEnumUnknown", + &unknown.interface.iid, + "Next", + next.vtable_index, + &element_drift, + &next.return_type, + ) + .is_none() + ); + let mut signature_drift = next.params.clone(); + signature_drift[2].direction = RawParamDirection::In; + assert!( + known_enumerator_next_override( + "Windows.Win32.System.Com", + "IEnumUnknown", + &unknown.interface.iid, + "Next", + next.vtable_index, + &signature_drift, + &next.return_type, + ) + .is_none() + ); + + let mut identity_drift = next.clone(); + identity_drift.declaring_iid = "ffffffff-ffff-ffff-ffff-ffffffffffff".into(); + assert!(validate_attached_enumerator_evidence(&identity_drift).is_err()); + + let mut slot_drift = next.clone(); + slot_drift.vtable_index += 1; + assert!(validate_attached_enumerator_evidence(&slot_drift).is_err()); + + let mut element_iid_drift = next.clone(); + let RawNativeType::Named { iid, .. } = &mut element_iid_drift.params[1].typ.native_type + else { + unreachable!() + }; + *iid = Some("ffffffff-ffff-ffff-ffff-ffffffffffff".into()); + assert!(validate_attached_enumerator_evidence(&element_iid_drift).is_err()); + + for (namespace, name) in [ + ("Windows.Win32.System.Wmi", "IEnumWbemClassObject"), + ("Windows.Win32.System.WindowsSync", "IEnumItemIds"), + ("Windows.Win32.Web.MsHtml", "IEnumPrivacyRecords"), + ] { + let unregistered = parse_com_interface(&winmd, namespace, name).unwrap(); + let next = unregistered + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.declaring_interface == name && method.metadata_name == "Next") + .unwrap(); + assert!(next.enumerator_next.is_none(), "{namespace}.{name}"); + assert!( + validate_attached_enumerator_evidence(next).is_err(), + "{namespace}.{name}" + ); + } + } + + #[test] + fn registered_enumerator_contracts_match_win32_metadata() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let index = crate::meta::load_index(&winmd).unwrap(); + let mut failures = Vec::new(); + for contract in crate::com_enumerator_registry::contracts() { + let Some(interface) = parse_com_interface_from_index( + &index, + contract.interface_namespace, + contract.interface_name, + ) else { + failures.push(format!( + "{}.{} is missing", + contract.interface_namespace, contract.interface_name + )); + continue; + }; + let next = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| { + method.declaring_namespace == contract.interface_namespace + && method.declaring_interface == contract.interface_name + && method.metadata_name == "Next" + }); + match next { + Some(next) if next.enumerator_next.is_some() => {} + Some(next) => failures.push(format!( + "{}.{} slot={} element={:?}", + contract.interface_namespace, + contract.interface_name, + next.vtable_index, + next.params.get(1).map(|param| ¶m.typ) + )), + None => failures.push(format!( + "{}.{}::Next is missing", + contract.interface_namespace, contract.interface_name + )), + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + #[test] fn item_id_list_double_pointer_uses_cotaskmem_ownership() { let typ = windows_metadata::Type::PtrMut( @@ -953,7 +3281,14 @@ mod tests { 2, ); assert_eq!( - known_free_with("", "", "", &typ, &ParamDirection::Out).as_deref(), + known_free_with( + "Windows.Win32.UI.Shell", + "IShellLinkW", + "GetIDList", + &typ, + &ParamDirection::Out + ) + .as_deref(), Some("CoTaskMemFree") ); } diff --git a/tools/dynwinrt-codegen/src/com_safe_array_registry.rs b/tools/dynwinrt-codegen/src/com_safe_array_registry.rs new file mode 100644 index 00000000..8a4b3ed9 --- /dev/null +++ b/tools/dynwinrt-codegen/src/com_safe_array_registry.rs @@ -0,0 +1,3349 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::com_metadata::{RawSafeArrayEvidence, RawSafeArrayOwnership, RawSafeArrayVartype}; + +const SAFE_ARRAY_EVIDENCE: &[RawSafeArrayEvidence] = &[ + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow", + declaring_interface: "IESEvent", + declaring_iid: "1f0e5357-af43-44e6-8547-654c645145d2", + method_name: "GetData", + vtable_index: 6, + parameter_index: 0, + parameter_name: "pbData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetData@6(pbData:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IESEvent::GetData parameter pbData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-iesevent-getdata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IESIsdbCasResponseEvent", + declaring_iid: "2017cb03-dc0f-4c24-83ca-36307b2cd19f", + method_name: "GetResponseData", + vtable_index: 11, + parameter_index: 0, + parameter_name: "pbData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetResponseData@11(pbData:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IESIsdbCasResponseEvent::GetResponseData parameter pbData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-iesisdbcasresponseevent-getresponsedata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IESLicenseRenewalResultEvent", + declaring_iid: "d5a48ef5-a81b-4df0-acaa-5e35e7ea45d4", + method_name: "GetEntitlementToken", + vtable_index: 17, + parameter_index: 0, + parameter_name: "pbData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEntitlementToken@17(pbData:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IESLicenseRenewalResultEvent::GetEntitlementToken parameter pbData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-ieslicenserenewalresultevent-getentitlementtoken", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IESOpenMmiEvent", + declaring_iid: "ba4b6526-1a35-4635-8b56-3ec612746a8c", + method_name: "GetDialogData", + vtable_index: 10, + parameter_index: 0, + parameter_name: "pbData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetDialogData@10(pbData:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IESOpenMmiEvent::GetDialogData parameter pbData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-iesopenmmievent-getdialogdata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Media.DirectShow.Tv", + declaring_interface: "IESValueUpdatedEvent", + declaring_iid: "8a24c46e-bb63-4664-8602-5d9c718c146d", + method_name: "GetValueNames", + vtable_index: 8, + parameter_index: 0, + parameter_name: "pbstrNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetValueNames@8(pbstrNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IESValueUpdatedEvent::GetValueNames parameter pbstrNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/tuner/nf-tuner-iesvalueupdatedevent-getvaluenames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnConnectionManager", + declaring_iid: "dcbbbab6-201d-4bbb-aaee-338e368af6fa", + method_name: "GetConnections", + vtable_index: 4, + parameter_index: 0, + parameter_name: "mbnConnections", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("dcbbbab6-200d-4bbb-aaee-338e368af6fa"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetConnections@4(mbnConnections:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnConnectionManager::GetConnections parameter mbnConnections as SAFEARRAY(IMbnConnection*), requiring VT_UNKNOWN with IID dcbbbab6-200d-4bbb-aaee-338e368af6fa", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnconnectionmanager-getconnections", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnConnectionProfileManager", + declaring_iid: "dcbbbab6-200f-4bbb-aaee-338e368af6fa", + method_name: "GetConnectionProfiles", + vtable_index: 3, + parameter_index: 1, + parameter_name: "connectionProfiles", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("dcbbbab6-2010-4bbb-aaee-338e368af6fa"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetConnectionProfiles@3(mbnInterface:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnInterface[Interface]{dcbbbab6-2001-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,connectionProfiles:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnConnectionProfileManager::GetConnectionProfiles parameter connectionProfiles as SAFEARRAY(IMbnConnectionProfile*), requiring VT_UNKNOWN with IID dcbbbab6-2010-4bbb-aaee-338e368af6fa", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnconnectionprofilemanager-getconnectionprofiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceService", + declaring_iid: "b3bb9a71-dc70-4be9-a4da-7886ae8b191b", + method_name: "SetCommand", + vtable_index: 6, + parameter_index: 1, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SetCommand@6(commandID:in:required:noconstattr:u32/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceService::SetCommand parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservice-setcommand", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceService", + declaring_iid: "b3bb9a71-dc70-4be9-a4da-7886ae8b191b", + method_name: "QueryCommand", + vtable_index: 7, + parameter_index: 1, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "QueryCommand@7(commandID:in:required:noconstattr:u32/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceService::QueryCommand parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservice-querycommand", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceService", + declaring_iid: "b3bb9a71-dc70-4be9-a4da-7886ae8b191b", + method_name: "WriteData", + vtable_index: 10, + parameter_index: 0, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "WriteData@10(deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceService::WriteData parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservice-writedata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceServicesEvents", + declaring_iid: "0a900c19-6824-4e97-b76e-cf239d0ca642", + method_name: "OnQuerySupportedCommandsComplete", + vtable_index: 3, + parameter_index: 1, + parameter_name: "commandIDList", + element_vartype: RawSafeArrayVartype::Ui4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnQuerySupportedCommandsComplete@3(deviceService:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnDeviceService[Interface]{b3bb9a71-dc70-4be9-a4da-7886ae8b191b}/ptr0/Unspecified,commandIDList:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,status:in:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,requestID:in:required:noconstattr:u32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceServicesEvents::OnQuerySupportedCommandsComplete parameter commandIDList as SAFEARRAY(ULONG), requiring VT_UI4", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservicesevents-onquerysupportedcommandscomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceServicesEvents", + declaring_iid: "0a900c19-6824-4e97-b76e-cf239d0ca642", + method_name: "OnSetCommandComplete", + vtable_index: 6, + parameter_index: 2, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnSetCommandComplete@6(deviceService:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnDeviceService[Interface]{b3bb9a71-dc70-4be9-a4da-7886ae8b191b}/ptr0/Unspecified,responseID:in:required:noconstattr:u32/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,status:in:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,requestID:in:required:noconstattr:u32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceServicesEvents::OnSetCommandComplete parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservicesevents-onsetcommandcomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceServicesEvents", + declaring_iid: "0a900c19-6824-4e97-b76e-cf239d0ca642", + method_name: "OnQueryCommandComplete", + vtable_index: 7, + parameter_index: 2, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnQueryCommandComplete@7(deviceService:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnDeviceService[Interface]{b3bb9a71-dc70-4be9-a4da-7886ae8b191b}/ptr0/Unspecified,responseID:in:required:noconstattr:u32/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,status:in:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,requestID:in:required:noconstattr:u32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceServicesEvents::OnQueryCommandComplete parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservicesevents-onquerycommandcomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceServicesEvents", + declaring_iid: "0a900c19-6824-4e97-b76e-cf239d0ca642", + method_name: "OnEventNotification", + vtable_index: 8, + parameter_index: 2, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnEventNotification@8(deviceService:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnDeviceService[Interface]{b3bb9a71-dc70-4be9-a4da-7886ae8b191b}/ptr0/Unspecified,eventID:in:required:noconstattr:u32/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceServicesEvents::OnEventNotification parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservicesevents-oneventnotification", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnDeviceServicesEvents", + declaring_iid: "0a900c19-6824-4e97-b76e-cf239d0ca642", + method_name: "OnReadData", + vtable_index: 12, + parameter_index: 1, + parameter_name: "deviceServiceData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnReadData@12(deviceService:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnDeviceService[Interface]{b3bb9a71-dc70-4be9-a4da-7886ae8b191b}/ptr0/Unspecified,deviceServiceData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnDeviceServicesEvents::OnReadData parameter deviceServiceData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbndeviceservicesevents-onreaddata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnInterfaceManager", + declaring_iid: "dcbbbab6-201b-4bbb-aaee-338e368af6fa", + method_name: "GetInterfaces", + vtable_index: 4, + parameter_index: 0, + parameter_name: "mbnInterfaces", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("dcbbbab6-2001-4bbb-aaee-338e368af6fa"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetInterfaces@4(mbnInterfaces:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnInterfaceManager::GetInterfaces parameter mbnInterfaces as SAFEARRAY(IMbnInterface*), requiring VT_UNKNOWN with IID dcbbbab6-2001-4bbb-aaee-338e368af6fa", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbninterfacemanager-getinterfaces", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnMultiCarrier", + declaring_iid: "dcbbbab6-2020-4bbb-aaee-338e368af6fa", + method_name: "GetSupportedCellularClasses", + vtable_index: 6, + parameter_index: 0, + parameter_name: "cellularClasses", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSupportedCellularClasses@6(cellularClasses:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnMultiCarrier::GetSupportedCellularClasses parameter cellularClasses as SAFEARRAY(MBN_CELLULAR_CLASS), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnmulticarrier-getsupportedcellularclasses", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnPinManager", + declaring_iid: "dcbbbab6-2005-4bbb-aaee-338e368af6fa", + method_name: "GetPinList", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pinList", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("dcbbbab6-2007-4bbb-aaee-338e368af6fa"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetPinList@3(pinList:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnPinManager::GetPinList parameter pinList as SAFEARRAY(IMbnPin*), requiring VT_UNKNOWN with IID dcbbbab6-2007-4bbb-aaee-338e368af6fa", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnpinmanager-getpinlist", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnServiceActivation", + declaring_iid: "dcbbbab6-2017-4bbb-aaee-338e368af6fa", + method_name: "Activate", + vtable_index: 3, + parameter_index: 0, + parameter_name: "vendorSpecificData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "Activate@3(vendorSpecificData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnServiceActivation::Activate parameter vendorSpecificData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnserviceactivation-activate", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnServiceActivationEvents", + declaring_iid: "dcbbbab6-2018-4bbb-aaee-338e368af6fa", + method_name: "OnActivationComplete", + vtable_index: 3, + parameter_index: 1, + parameter_name: "vendorSpecificData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnActivationComplete@3(serviceActivation:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnServiceActivation[Interface]{dcbbbab6-2017-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,vendorSpecificData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:in:required:noconstattr:u32/ptr0/Unspecified,status:in:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,networkError:in:required:noconstattr:u32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnServiceActivationEvents::OnActivationComplete parameter vendorSpecificData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnserviceactivationevents-onactivationcomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSms", + declaring_iid: "dcbbbab6-2015-4bbb-aaee-338e368af6fa", + method_name: "SmsSendCdma", + vtable_index: 6, + parameter_index: 4, + parameter_name: "message", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SmsSendCdma@6(address:in:required:constattr:Windows.Win32.Foundation.PWSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,encoding:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.MBN_SMS_CDMA_ENCODING[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,language:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.MBN_SMS_CDMA_LANG[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,sizeInCharacters:in:required:noconstattr:u32/ptr0/Unspecified,message:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSms::SmsSendCdma parameter message as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsms-smssendcdma", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSms", + declaring_iid: "dcbbbab6-2015-4bbb-aaee-338e368af6fa", + method_name: "SmsSendCdmaPdu", + vtable_index: 7, + parameter_index: 0, + parameter_name: "message", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SmsSendCdmaPdu@7(message:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSms::SmsSendCdmaPdu parameter message as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsms-smssendcdmapdu", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSmsEvents", + declaring_iid: "dcbbbab6-2016-4bbb-aaee-338e368af6fa", + method_name: "OnSmsReadComplete", + vtable_index: 6, + parameter_index: 2, + parameter_name: "readMsgs", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("00000000-0000-0000-c000-000000000046"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnSmsReadComplete@6(sms:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnSms[Interface]{dcbbbab6-2015-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,smsFormat:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.MBN_SMS_FORMAT[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,readMsgs:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,moreMsgs:in:required:noconstattr:Windows.Win32.Foundation.VARIANT_BOOL[Struct]/ptr0/Unspecified/underlying=i16/ptr0/Unspecified,requestID:in:required:noconstattr:u32/ptr0/Unspecified,status:in:required:noconstattr:Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSmsEvents::OnSmsReadComplete parameter readMsgs as SAFEARRAY(IUnknown*), requiring VT_UNKNOWN with IID 00000000-0000-0000-c000-000000000046", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsmsevents-onsmsreadcomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSmsEvents", + declaring_iid: "dcbbbab6-2016-4bbb-aaee-338e368af6fa", + method_name: "OnSmsNewClass0Message", + vtable_index: 7, + parameter_index: 2, + parameter_name: "readMsgs", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("00000000-0000-0000-c000-000000000046"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnSmsNewClass0Message@7(sms:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnSms[Interface]{dcbbbab6-2015-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,smsFormat:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.MBN_SMS_FORMAT[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,readMsgs:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSmsEvents::OnSmsNewClass0Message parameter readMsgs as SAFEARRAY(IUnknown*), requiring VT_UNKNOWN with IID 00000000-0000-0000-c000-000000000046", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsmsevents-onsmsnewclass0message", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSmsReadMsgPdu", + declaring_iid: "dcbbbab6-2013-4bbb-aaee-338e368af6fa", + method_name: "get_Message", + vtable_index: 6, + parameter_index: 0, + parameter_name: "Message", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Message@6(Message:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSmsReadMsgPdu::get_Message parameter Message as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsmsreadmsgpdu-get_message", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSmsReadMsgTextCdma", + declaring_iid: "dcbbbab6-2014-4bbb-aaee-338e368af6fa", + method_name: "get_Message", + vtable_index: 10, + parameter_index: 0, + parameter_name: "Message", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Message@10(Message:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSmsReadMsgTextCdma::get_Message parameter Message as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsmsreadmsgtextcdma-get_message", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnSubscriberInformation", + declaring_iid: "459ecc43-bcf5-11dc-a8a8-001321f1405f", + method_name: "get_TelephoneNumbers", + vtable_index: 5, + parameter_index: 0, + parameter_name: "TelephoneNumbers", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_TelephoneNumbers@5(TelephoneNumbers:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnSubscriberInformation::get_TelephoneNumbers parameter TelephoneNumbers as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnsubscriberinformation-get_telephonenumbers", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnVendorSpecificEvents", + declaring_iid: "dcbbbab6-201a-4bbb-aaee-338e368af6fa", + method_name: "OnEventNotification", + vtable_index: 3, + parameter_index: 1, + parameter_name: "vendorSpecificData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnEventNotification@3(vendorOperation:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnVendorSpecificOperation[Interface]{dcbbbab6-2019-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,vendorSpecificData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnVendorSpecificEvents::OnEventNotification parameter vendorSpecificData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnvendorspecificevents-oneventnotification", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnVendorSpecificEvents", + declaring_iid: "dcbbbab6-201a-4bbb-aaee-338e368af6fa", + method_name: "OnSetVendorSpecificComplete", + vtable_index: 4, + parameter_index: 1, + parameter_name: "vendorSpecificData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnSetVendorSpecificComplete@4(vendorOperation:in:required:noconstattr:Windows.Win32.NetworkManagement.MobileBroadband.IMbnVendorSpecificOperation[Interface]{dcbbbab6-2019-4bbb-aaee-338e368af6fa}/ptr0/Unspecified,vendorSpecificData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:in:required:noconstattr:u32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnVendorSpecificEvents::OnSetVendorSpecificComplete parameter vendorSpecificData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnvendorspecificevents-onsetvendorspecificcomplete", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.NetworkManagement.MobileBroadband", + declaring_interface: "IMbnVendorSpecificOperation", + declaring_iid: "dcbbbab6-2019-4bbb-aaee-338e368af6fa", + method_name: "SetVendorSpecific", + vtable_index: 3, + parameter_index: 0, + parameter_name: "vendorSpecificData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SetVendorSpecific@3(vendorSpecificData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,requestID:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMbnVendorSpecificOperation::SetVendorSpecific parameter vendorSpecificData as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/mbnapi/nf-mbnapi-imbnvendorspecificoperation-setvendorspecific", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmActionReport", + declaring_iid: "2dbe63c4-b340-48a0-a5b0-158e07fc567e", + method_name: "get_ReportTypes", + vtable_index: 12, + parameter_index: 0, + parameter_name: "reportTypes", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ReportTypes@12(reportTypes:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmActionReport::get_ReportTypes parameter reportTypes as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrm/nf-fsrm-ifsrmactionreport-get_reporttypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmActionReport", + declaring_iid: "2dbe63c4-b340-48a0-a5b0-158e07fc567e", + method_name: "put_ReportTypes", + vtable_index: 13, + parameter_index: 0, + parameter_name: "reportTypes", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ReportTypes@13(reportTypes:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmActionReport::put_ReportTypes parameter reportTypes as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrm/nf-fsrm-ifsrmactionreport-put_reporttypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmAutoApplyQuota", + declaring_iid: "f82e5729-6aba-4740-bfc7-c7f58f75fb7b", + method_name: "get_ExcludeFolders", + vtable_index: 28, + parameter_index: 0, + parameter_name: "folders", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ExcludeFolders@28(folders:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmAutoApplyQuota::get_ExcludeFolders parameter folders as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmquota/nf-fsrmquota-ifsrmautoapplyquota-get_excludefolders", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmAutoApplyQuota", + declaring_iid: "f82e5729-6aba-4740-bfc7-c7f58f75fb7b", + method_name: "put_ExcludeFolders", + vtable_index: 29, + parameter_index: 0, + parameter_name: "folders", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ExcludeFolders@29(folders:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmAutoApplyQuota::put_ExcludeFolders parameter folders as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmquota/nf-fsrmquota-ifsrmautoapplyquota-put_excludefolders", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassificationManager", + declaring_iid: "d2dc89da-ee91-48a0-85d8-cc72a56f7d04", + method_name: "get_ClassificationReportFormats", + vtable_index: 7, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ClassificationReportFormats@7(formats:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassificationManager::get_ClassificationReportFormats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassificationmanager-get_classificationreportformats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassificationManager", + declaring_iid: "d2dc89da-ee91-48a0-85d8-cc72a56f7d04", + method_name: "put_ClassificationReportFormats", + vtable_index: 8, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ClassificationReportFormats@8(formats:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassificationManager::put_ClassificationReportFormats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassificationmanager-put_classificationreportformats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassificationManager2", + declaring_iid: "0004c1c9-127e-4765-ba07-6a3147bca112", + method_name: "ClassifyFiles", + vtable_index: 34, + parameter_index: 0, + parameter_name: "filePaths", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "ClassifyFiles@34(filePaths:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyValues:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,options:in:required:noconstattr:Windows.Win32.Storage.FileServerResourceManager.FsrmGetFilePropertyOptions[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassificationManager2::ClassifyFiles parameter filePaths as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassificationmanager2-classifyfiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassificationManager2", + declaring_iid: "0004c1c9-127e-4765-ba07-6a3147bca112", + method_name: "ClassifyFiles", + vtable_index: 34, + parameter_index: 1, + parameter_name: "propertyNames", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "ClassifyFiles@34(filePaths:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyValues:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,options:in:required:noconstattr:Windows.Win32.Storage.FileServerResourceManager.FsrmGetFilePropertyOptions[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassificationManager2::ClassifyFiles parameter propertyNames as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassificationmanager2-classifyfiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassificationManager2", + declaring_iid: "0004c1c9-127e-4765-ba07-6a3147bca112", + method_name: "ClassifyFiles", + vtable_index: 34, + parameter_index: 2, + parameter_name: "propertyValues", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "ClassifyFiles@34(filePaths:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,propertyValues:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,options:in:required:noconstattr:Windows.Win32.Storage.FileServerResourceManager.FsrmGetFilePropertyOptions[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassificationManager2::ClassifyFiles parameter propertyValues as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassificationmanager2-classifyfiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassifierModuleDefinition", + declaring_iid: "bb36ea26-6318-4b8c-8592-f72dd602e7a5", + method_name: "get_PropertiesAffected", + vtable_index: 31, + parameter_index: 0, + parameter_name: "propertiesAffected", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_PropertiesAffected@31(propertiesAffected:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassifierModuleDefinition::get_PropertiesAffected parameter propertiesAffected as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassifiermoduledefinition-get_propertiesaffected", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassifierModuleDefinition", + declaring_iid: "bb36ea26-6318-4b8c-8592-f72dd602e7a5", + method_name: "put_PropertiesAffected", + vtable_index: 32, + parameter_index: 0, + parameter_name: "propertiesAffected", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_PropertiesAffected@32(propertiesAffected:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassifierModuleDefinition::put_PropertiesAffected parameter propertiesAffected as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassifiermoduledefinition-put_propertiesaffected", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassifierModuleDefinition", + declaring_iid: "bb36ea26-6318-4b8c-8592-f72dd602e7a5", + method_name: "get_PropertiesUsed", + vtable_index: 33, + parameter_index: 0, + parameter_name: "propertiesUsed", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_PropertiesUsed@33(propertiesUsed:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassifierModuleDefinition::get_PropertiesUsed parameter propertiesUsed as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassifiermoduledefinition-get_propertiesused", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassifierModuleDefinition", + declaring_iid: "bb36ea26-6318-4b8c-8592-f72dd602e7a5", + method_name: "put_PropertiesUsed", + vtable_index: 34, + parameter_index: 0, + parameter_name: "propertiesUsed", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_PropertiesUsed@34(propertiesUsed:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassifierModuleDefinition::put_PropertiesUsed parameter propertiesUsed as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassifiermoduledefinition-put_propertiesused", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmClassifierModuleImplementation", + declaring_iid: "4c968fc6-6edb-4051-9c18-73b7291ae106", + method_name: "OnBeginFile", + vtable_index: 11, + parameter_index: 1, + parameter_name: "arrayRuleIds", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnBeginFile@11(propertyBag:in:required:noconstattr:Windows.Win32.Storage.FileServerResourceManager.IFsrmPropertyBag[Interface]{774589d1-d300-4f7a-9a24-f7b766800250}/ptr0/Unspecified,arrayRuleIds:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmClassifierModuleImplementation::OnBeginFile parameter arrayRuleIds as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmclassifiermoduleimplementation-onbeginfile", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "get_NamespaceRoots", + vtable_index: 14, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_NamespaceRoots@14(namespaceRoots:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::get_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-get_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "put_NamespaceRoots", + vtable_index: 15, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_NamespaceRoots@15(namespaceRoots:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::put_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-put_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "get_Notifications", + vtable_index: 23, + parameter_index: 0, + parameter_name: "notifications", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Notifications@23(notifications:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::get_Notifications parameter notifications as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-get_notifications", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "get_Formats", + vtable_index: 28, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Formats@28(formats:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::get_Formats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-get_formats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "put_Formats", + vtable_index: 29, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Formats@29(formats:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::put_Formats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-put_formats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "get_Parameters", + vtable_index: 43, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Parameters@43(parameters:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::get_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-get_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJob", + declaring_iid: "0770687e-9f36-4d6f-8778-599d188461c9", + method_name: "put_Parameters", + vtable_index: 44, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Parameters@44(parameters:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJob::put_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjob-put_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJobManager", + declaring_iid: "ee321ecb-d95e-48e9-907c-c7685a013235", + method_name: "get_ActionVariables", + vtable_index: 7, + parameter_index: 0, + parameter_name: "variables", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariables@7(variables:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJobManager::get_ActionVariables parameter variables as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjobmanager-get_actionvariables", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileManagementJobManager", + declaring_iid: "ee321ecb-d95e-48e9-907c-c7685a013235", + method_name: "get_ActionVariableDescriptions", + vtable_index: 8, + parameter_index: 0, + parameter_name: "descriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariableDescriptions@8(descriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileManagementJobManager::get_ActionVariableDescriptions parameter descriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmfilemanagementjobmanager-get_actionvariabledescriptions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileScreenManager", + declaring_iid: "ff4fa04e-5a94-4bda-a3a0-d5b4d3c52eba", + method_name: "get_ActionVariables", + vtable_index: 7, + parameter_index: 0, + parameter_name: "variables", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariables@7(variables:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileScreenManager::get_ActionVariables parameter variables as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmscreen/nf-fsrmscreen-ifsrmfilescreenmanager-get_actionvariables", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmFileScreenManager", + declaring_iid: "ff4fa04e-5a94-4bda-a3a0-d5b4d3c52eba", + method_name: "get_ActionVariableDescriptions", + vtable_index: 8, + parameter_index: 0, + parameter_name: "descriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariableDescriptions@8(descriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmFileScreenManager::get_ActionVariableDescriptions parameter descriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmscreen/nf-fsrmscreen-ifsrmfilescreenmanager-get_actionvariabledescriptions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPathMapper", + declaring_iid: "6f4dbfff-6920-4821-a6c3-b7e94c1fd60c", + method_name: "GetSharePathsForLocalPath", + vtable_index: 7, + parameter_index: 1, + parameter_name: "sharePaths", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSharePathsForLocalPath@7(localPath:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,sharePaths:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPathMapper::GetSharePathsForLocalPath parameter sharePaths as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrm/nf-fsrm-ifsrmpathmapper-getsharepathsforlocalpath", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPipelineModuleDefinition", + declaring_iid: "515c1277-2c81-440e-8fcf-367921ed4f59", + method_name: "get_SupportedExtensions", + vtable_index: 27, + parameter_index: 0, + parameter_name: "supportedExtensions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedExtensions@27(supportedExtensions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPipelineModuleDefinition::get_SupportedExtensions parameter supportedExtensions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpipelinemoduledefinition-get_supportedextensions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPipelineModuleDefinition", + declaring_iid: "515c1277-2c81-440e-8fcf-367921ed4f59", + method_name: "put_SupportedExtensions", + vtable_index: 28, + parameter_index: 0, + parameter_name: "supportedExtensions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_SupportedExtensions@28(supportedExtensions:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPipelineModuleDefinition::put_SupportedExtensions parameter supportedExtensions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpipelinemoduledefinition-put_supportedextensions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPipelineModuleDefinition", + declaring_iid: "515c1277-2c81-440e-8fcf-367921ed4f59", + method_name: "get_Parameters", + vtable_index: 29, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Parameters@29(parameters:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPipelineModuleDefinition::get_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpipelinemoduledefinition-get_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPipelineModuleDefinition", + declaring_iid: "515c1277-2c81-440e-8fcf-367921ed4f59", + method_name: "put_Parameters", + vtable_index: 30, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Parameters@30(parameters:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPipelineModuleDefinition::put_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpipelinemoduledefinition-put_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmProperty", + declaring_iid: "4a73fee4-4102-4fcc-9ffb-38614f9ee768", + method_name: "get_Sources", + vtable_index: 9, + parameter_index: 0, + parameter_name: "sources", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Sources@9(sources:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmProperty::get_Sources parameter sources as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmproperty-get_sources", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyBag", + declaring_iid: "774589d1-d300-4f7a-9a24-f7b766800250", + method_name: "get_FilePropertyNames", + vtable_index: 21, + parameter_index: 0, + parameter_name: "filePropertyNames", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_FilePropertyNames@21(filePropertyNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyBag::get_FilePropertyNames parameter filePropertyNames as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertybag-get_filepropertynames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyBag", + declaring_iid: "774589d1-d300-4f7a-9a24-f7b766800250", + method_name: "get_Messages", + vtable_index: 22, + parameter_index: 0, + parameter_name: "messages", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Messages@22(messages:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyBag::get_Messages parameter messages as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertybag-get_messages", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "get_PossibleValues", + vtable_index: 16, + parameter_index: 0, + parameter_name: "possibleValues", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_PossibleValues@16(possibleValues:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::get_PossibleValues parameter possibleValues as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-get_possiblevalues", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "put_PossibleValues", + vtable_index: 17, + parameter_index: 0, + parameter_name: "possibleValues", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_PossibleValues@17(possibleValues:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::put_PossibleValues parameter possibleValues as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-put_possiblevalues", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "get_ValueDescriptions", + vtable_index: 18, + parameter_index: 0, + parameter_name: "valueDescriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ValueDescriptions@18(valueDescriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::get_ValueDescriptions parameter valueDescriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-get_valuedescriptions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "put_ValueDescriptions", + vtable_index: 19, + parameter_index: 0, + parameter_name: "valueDescriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ValueDescriptions@19(valueDescriptions:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::put_ValueDescriptions parameter valueDescriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-put_valuedescriptions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "get_Parameters", + vtable_index: 20, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Parameters@20(parameters:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::get_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-get_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmPropertyDefinition", + declaring_iid: "ede0150f-e9a3-419c-877c-01fe5d24c5d3", + method_name: "put_Parameters", + vtable_index: 21, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Parameters@21(parameters:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmPropertyDefinition::put_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmpropertydefinition-put_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmQuotaBase", + declaring_iid: "1568a795-3924-4118-b74b-68d8f0fa5daf", + method_name: "get_Thresholds", + vtable_index: 16, + parameter_index: 0, + parameter_name: "thresholds", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Thresholds@16(thresholds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmQuotaBase::get_Thresholds parameter thresholds as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmquota/nf-fsrmquota-ifsrmquotabase-get_thresholds", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmQuotaManager", + declaring_iid: "8bb68c7d-19d8-4ffb-809e-be4fc1734014", + method_name: "get_ActionVariables", + vtable_index: 7, + parameter_index: 0, + parameter_name: "variables", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariables@7(variables:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmQuotaManager::get_ActionVariables parameter variables as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmquota/nf-fsrmquota-ifsrmquotamanager-get_actionvariables", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmQuotaManager", + declaring_iid: "8bb68c7d-19d8-4ffb-809e-be4fc1734014", + method_name: "get_ActionVariableDescriptions", + vtable_index: 8, + parameter_index: 0, + parameter_name: "descriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ActionVariableDescriptions@8(descriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmQuotaManager::get_ActionVariableDescriptions parameter descriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmquota/nf-fsrmquota-ifsrmquotamanager-get_actionvariabledescriptions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmReportJob", + declaring_iid: "38e87280-715c-4c7d-a280-ea1651a19fef", + method_name: "get_NamespaceRoots", + vtable_index: 14, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_NamespaceRoots@14(namespaceRoots:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmReportJob::get_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmreportjob-get_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmReportJob", + declaring_iid: "38e87280-715c-4c7d-a280-ea1651a19fef", + method_name: "put_NamespaceRoots", + vtable_index: 15, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_NamespaceRoots@15(namespaceRoots:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmReportJob::put_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmreportjob-put_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmReportJob", + declaring_iid: "38e87280-715c-4c7d-a280-ea1651a19fef", + method_name: "get_Formats", + vtable_index: 16, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Formats@16(formats:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmReportJob::get_Formats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmreportjob-get_formats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmReportJob", + declaring_iid: "38e87280-715c-4c7d-a280-ea1651a19fef", + method_name: "put_Formats", + vtable_index: 17, + parameter_index: 0, + parameter_name: "formats", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Formats@17(formats:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmReportJob::put_Formats parameter formats as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmreports/nf-fsrmreports-ifsrmreportjob-put_formats", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmRule", + declaring_iid: "cb0df960-16f5-4495-9079-3f9360d831df", + method_name: "get_NamespaceRoots", + vtable_index: 17, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_NamespaceRoots@17(namespaceRoots:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmRule::get_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmrule-get_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmRule", + declaring_iid: "cb0df960-16f5-4495-9079-3f9360d831df", + method_name: "put_NamespaceRoots", + vtable_index: 18, + parameter_index: 0, + parameter_name: "namespaceRoots", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_NamespaceRoots@18(namespaceRoots:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmRule::put_NamespaceRoots parameter namespaceRoots as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmrule-put_namespaceroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmRule", + declaring_iid: "cb0df960-16f5-4495-9079-3f9360d831df", + method_name: "get_Parameters", + vtable_index: 21, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Parameters@21(parameters:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmRule::get_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmrule-get_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.FileServerResourceManager", + declaring_interface: "IFsrmRule", + declaring_iid: "cb0df960-16f5-4495-9079-3f9360d831df", + method_name: "put_Parameters", + vtable_index: 22, + parameter_index: 0, + parameter_name: "parameters", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Parameters@22(parameters:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFsrmRule::put_Parameters parameter parameters as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/fsrmpipeline/nf-fsrmpipeline-ifsrmrule-put_parameters", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IBlockRangeList", + declaring_iid: "b507ca26-2204-11dd-966a-001aa01bbc58", + method_name: "get_BlockRanges", + vtable_index: 7, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_BlockRanges@7(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IBlockRangeList::get_BlockRanges parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-iblockrangelist-get_blockranges", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2", + declaring_iid: "27354152-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedMediaTypes", + vtable_index: 11, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedMediaTypes@11(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2::get_SupportedMediaTypes parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2-get_supportedmediatypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2Data", + declaring_iid: "27354153-9f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeeds", + vtable_index: 36, + parameter_index: 0, + parameter_name: "supportedSpeeds", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeeds@36(supportedSpeeds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2Data::get_SupportedWriteSpeeds parameter supportedSpeeds as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2data-get_supportedwritespeeds", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2Data", + declaring_iid: "27354153-9f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeedDescriptors", + vtable_index: 37, + parameter_index: 0, + parameter_name: "supportedSpeedDescriptors", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeedDescriptors@37(supportedSpeedDescriptors:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2Data::get_SupportedWriteSpeedDescriptors parameter supportedSpeedDescriptors as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2data-get_supportedwritespeeddescriptors", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2Data", + declaring_iid: "27354153-9f64-5b0f-8f00-5d77afbe261e", + method_name: "get_MultisessionInterfaces", + vtable_index: 40, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_MultisessionInterfaces@40(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2Data::get_MultisessionInterfaces parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2data-get_multisessioninterfaces", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2RawCD", + declaring_iid: "27354155-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedSectorTypes", + vtable_index: 25, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedSectorTypes@25(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2RawCD::get_SupportedSectorTypes parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2rawcd-get_supportedsectortypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2RawCD", + declaring_iid: "27354155-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeeds", + vtable_index: 34, + parameter_index: 0, + parameter_name: "supportedSpeeds", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeeds@34(supportedSpeeds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2RawCD::get_SupportedWriteSpeeds parameter supportedSpeeds as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2rawcd-get_supportedwritespeeds", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2RawCD", + declaring_iid: "27354155-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeedDescriptors", + vtable_index: 35, + parameter_index: 0, + parameter_name: "supportedSpeedDescriptors", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeedDescriptors@35(supportedSpeedDescriptors:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2RawCD::get_SupportedWriteSpeedDescriptors parameter supportedSpeedDescriptors as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2rawcd-get_supportedwritespeeddescriptors", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2TrackAtOnce", + declaring_iid: "27354154-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_ExpectedTableOfContents", + vtable_index: 27, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ExpectedTableOfContents@27(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2TrackAtOnce::get_ExpectedTableOfContents parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2trackatonce-get_expectedtableofcontents", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2TrackAtOnce", + declaring_iid: "27354154-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeeds", + vtable_index: 35, + parameter_index: 0, + parameter_name: "supportedSpeeds", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeeds@35(supportedSpeeds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2TrackAtOnce::get_SupportedWriteSpeeds parameter supportedSpeeds as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2trackatonce-get_supportedwritespeeds", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscFormat2TrackAtOnce", + declaring_iid: "27354154-8f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedWriteSpeedDescriptors", + vtable_index: 36, + parameter_index: 0, + parameter_name: "supportedSpeedDescriptors", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedWriteSpeedDescriptors@36(supportedSpeedDescriptors:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscFormat2TrackAtOnce::get_SupportedWriteSpeedDescriptors parameter supportedSpeedDescriptors as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscformat2trackatonce-get_supportedwritespeeddescriptors", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_VolumePathNames", + vtable_index: 19, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_VolumePathNames@19(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_VolumePathNames parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_volumepathnames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedFeaturePages", + vtable_index: 22, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedFeaturePages@22(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_SupportedFeaturePages parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_supportedfeaturepages", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_CurrentFeaturePages", + vtable_index: 23, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CurrentFeaturePages@23(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_CurrentFeaturePages parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_currentfeaturepages", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedProfiles", + vtable_index: 24, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedProfiles@24(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_SupportedProfiles parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_supportedprofiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_CurrentProfiles", + vtable_index: 25, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CurrentProfiles@25(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_CurrentProfiles parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_currentprofiles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IDiscRecorder2", + declaring_iid: "27354133-7f64-5b0f-8f00-5d77afbe261e", + method_name: "get_SupportedModePages", + vtable_index: 26, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_SupportedModePages@26(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDiscRecorder2::get_SupportedModePages parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-idiscrecorder2-get_supportedmodepages", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage", + declaring_iid: "2c941fe1-975b-59be-a960-9a2a262853a5", + method_name: "get_UDFRevisionsSupported", + vtable_index: 33, + parameter_index: 0, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_UDFRevisionsSupported@33(pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage::get_UDFRevisionsSupported parameter pVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage-get_udfrevisionssupported", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage", + declaring_iid: "2c941fe1-975b-59be-a960-9a2a262853a5", + method_name: "get_ISO9660InterchangeLevelsSupported", + vtable_index: 38, + parameter_index: 0, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ISO9660InterchangeLevelsSupported@38(pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage::get_ISO9660InterchangeLevelsSupported parameter pVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage-get_iso9660interchangelevelssupported", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage", + declaring_iid: "2c941fe1-975b-59be-a960-9a2a262853a5", + method_name: "get_MultisessionInterfaces", + vtable_index: 55, + parameter_index: 0, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_MultisessionInterfaces@55(pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage::get_MultisessionInterfaces parameter pVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage-get_multisessioninterfaces", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage", + declaring_iid: "2c941fe1-975b-59be-a960-9a2a262853a5", + method_name: "put_MultisessionInterfaces", + vtable_index: 56, + parameter_index: 0, + parameter_name: "newVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_MultisessionInterfaces@56(newVal:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage::put_MultisessionInterfaces parameter newVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage-put_multisessioninterfaces", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage2", + declaring_iid: "d7644b2c-1537-4767-b62f-f1387b02ddfd", + method_name: "get_BootImageOptionsArray", + vtable_index: 57, + parameter_index: 0, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_BootImageOptionsArray@57(pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage2::get_BootImageOptionsArray parameter pVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage2-get_bootimageoptionsarray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IFileSystemImage2", + declaring_iid: "d7644b2c-1537-4767-b62f-f1387b02ddfd", + method_name: "put_BootImageOptionsArray", + vtable_index: 58, + parameter_index: 0, + parameter_name: "newVal", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_BootImageOptionsArray@58(newVal:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IFileSystemImage2::put_BootImageOptionsArray parameter newVal as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2fs/nf-imapi2fs-ifilesystemimage2-put_bootimageoptionsarray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IRawCDImageCreator", + declaring_iid: "25983550-9d65-49ce-b335-40630d901227", + method_name: "get_ExpectedTableOfContents", + vtable_index: 25, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ExpectedTableOfContents@25(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawCDImageCreator::get_ExpectedTableOfContents parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-irawcdimagecreator-get_expectedtableofcontents", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.Storage.Imapi", + declaring_interface: "IRawCDImageTrackInfo", + declaring_iid: "25983551-9d65-49ce-b335-40630d901227", + method_name: "get_TrackIndexes", + vtable_index: 17, + parameter_index: 0, + parameter_name: "value", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_TrackIndexes@17(value:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawCDImageTrackInfo::get_TrackIndexes parameter value as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/imapi2/nf-imapi2-irawcdimagetrackinfo-get_trackindexes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetMultipleComponentsInfo", + vtable_index: 23, + parameter_index: 2, + parameter_name: "ppsaVarCLSIDs", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetMultipleComponentsInfo@23(bstrApplIdOrName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarFileNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarClassNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarFileFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarComponentFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetMultipleComponentsInfo parameter ppsaVarCLSIDs as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-getmultiplecomponentsinfo", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetMultipleComponentsInfo", + vtable_index: 23, + parameter_index: 3, + parameter_name: "ppsaVarClassNames", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetMultipleComponentsInfo@23(bstrApplIdOrName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarFileNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarClassNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarFileFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarComponentFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetMultipleComponentsInfo parameter ppsaVarClassNames as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-getmultiplecomponentsinfo", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetMultipleComponentsInfo", + vtable_index: 23, + parameter_index: 4, + parameter_name: "ppsaVarFileFlags", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetMultipleComponentsInfo@23(bstrApplIdOrName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarFileNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarClassNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarFileFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarComponentFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetMultipleComponentsInfo parameter ppsaVarFileFlags as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-getmultiplecomponentsinfo", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetMultipleComponentsInfo", + vtable_index: 23, + parameter_index: 5, + parameter_name: "ppsaVarComponentFlags", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetMultipleComponentsInfo@23(bstrApplIdOrName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarFileNames:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarClassNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarFileFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarComponentFlags:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetMultipleComponentsInfo parameter ppsaVarComponentFlags as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-getmultiplecomponentsinfo", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "QueryApplicationFile", + vtable_index: 27, + parameter_index: 5, + parameter_name: "ppsaVarFileNames", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "QueryApplicationFile@27(bstrApplicationFile:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,pbstrApplicationName:out:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr1/Mutable/underlying=char16/ptr1/Mutable:free=SysFreeString,pbstrApplicationDescription:out:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr1/Mutable/underlying=char16/ptr1/Mutable:free=SysFreeString,pbHasUsers:out:required:noconstattr:Windows.Win32.Foundation.VARIANT_BOOL[Struct]/ptr1/Mutable/underlying=i16/ptr0/Unspecified,pbIsProxy:out:required:noconstattr:Windows.Win32.Foundation.VARIANT_BOOL[Struct]/ptr1/Mutable/underlying=i16/ptr0/Unspecified,ppsaVarFileNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::QueryApplicationFile parameter ppsaVarFileNames as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-queryapplicationfile", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetEventClassesForIID", + vtable_index: 32, + parameter_index: 1, + parameter_name: "ppsaVarCLSIDs", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEventClassesForIID@32(bstrIID:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarProgIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarDescriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetEventClassesForIID parameter ppsaVarCLSIDs as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-geteventclassesforiid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetEventClassesForIID", + vtable_index: 32, + parameter_index: 2, + parameter_name: "ppsaVarProgIDs", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEventClassesForIID@32(bstrIID:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarProgIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarDescriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetEventClassesForIID parameter ppsaVarProgIDs as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-geteventclassesforiid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICOMAdminCatalog", + declaring_iid: "dd662187-dfc2-11d1-a2cf-00805fc79235", + method_name: "GetEventClassesForIID", + vtable_index: 32, + parameter_index: 3, + parameter_name: "ppsaVarDescriptions", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEventClassesForIID@32(bstrIID:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,ppsaVarCLSIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarProgIDs:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,ppsaVarDescriptions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICOMAdminCatalog::GetEventClassesForIID parameter ppsaVarDescriptions as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icomadmincatalog-geteventclassesforiid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.ComponentServices", + declaring_interface: "ICatalogCollection", + declaring_iid: "6eb22872-8a19-11d0-81b6-00a0c9231c29", + method_name: "PopulateByKey", + vtable_index: 21, + parameter_index: 0, + parameter_name: "psaKeys", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "PopulateByKey@21(psaKeys:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ICatalogCollection::PopulateByKey parameter psaKeys as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/comadmin/nf-comadmin-icatalogcollection-populatebykey", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.DesktopSharing", + declaring_interface: "IRDPSRAPIFrameBuffer", + declaring_iid: "3d67e7d2-b27b-448e-81b3-c6110ed8b4be", + method_name: "GetFrameBufferBits", + vtable_index: 10, + parameter_index: 4, + parameter_name: "ppBits", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetFrameBufferBits@10(x:in:required:noconstattr:i32/ptr0/Unspecified,y:in:required:noconstattr:i32/ptr0/Unspecified,Width:in:required:noconstattr:i32/ptr0/Unspecified,Heigth:in:required:noconstattr:i32/ptr0/Unspecified,ppBits:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRDPSRAPIFrameBuffer::GetFrameBufferBits parameter ppBits as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/rdpencomapi/nf-rdpencomapi-irdpsrapiframebuffer-getframebufferbits", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IAlertDataCollector", + declaring_iid: "03837516-098b-11d8-9414-505054503030", + method_name: "get_AlertThresholds", + vtable_index: 32, + parameter_index: 0, + parameter_name: "alerts", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_AlertThresholds@32(alerts:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IAlertDataCollector::get_AlertThresholds parameter alerts as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/4eec695c-3db7-48b2-acc9-4614050eb73e", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IAlertDataCollector", + declaring_iid: "03837516-098b-11d8-9414-505054503030", + method_name: "put_AlertThresholds", + vtable_index: 33, + parameter_index: 0, + parameter_name: "alerts", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_AlertThresholds@33(alerts:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IAlertDataCollector::put_AlertThresholds parameter alerts as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/5a4acb29-3360-4f6b-9b4f-445d6149d0c8", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "get_IncludeModules", + vtable_index: 40, + parameter_index: 0, + parameter_name: "includemodules", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_IncludeModules@40(includemodules:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::get_IncludeModules parameter includemodules as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/8c6ec48b-3a2b-4f7f-a77b-93f311175d72", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "put_IncludeModules", + vtable_index: 41, + parameter_index: 0, + parameter_name: "includemodules", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_IncludeModules@41(includemodules:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::put_IncludeModules parameter includemodules as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/4a15bef7-2231-4626-883a-76c608fe144e", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "get_IncludeApis", + vtable_index: 42, + parameter_index: 0, + parameter_name: "includeapis", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_IncludeApis@42(includeapis:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::get_IncludeApis parameter includeapis as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/4a23e92d-3a98-4c9b-bffa-730eb94d300e", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "put_IncludeApis", + vtable_index: 43, + parameter_index: 0, + parameter_name: "includeapis", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_IncludeApis@43(includeapis:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::put_IncludeApis parameter includeapis as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/7d22d37a-c3e7-43c7-9d37-99eef3f2a76e", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "get_ExcludeApis", + vtable_index: 44, + parameter_index: 0, + parameter_name: "excludeapis", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ExcludeApis@44(excludeapis:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::get_ExcludeApis parameter excludeapis as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/522d5831-3675-4e8a-a464-804f8aae23d1", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IApiTracingDataCollector", + declaring_iid: "0383751a-098b-11d8-9414-505054503030", + method_name: "put_ExcludeApis", + vtable_index: 45, + parameter_index: 0, + parameter_name: "excludeapis", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ExcludeApis@45(excludeapis:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IApiTracingDataCollector::put_ExcludeApis parameter excludeapis as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/d4e1cca9-b5ff-43a2-9460-09cc28fdfbb3", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "get_Files", + vtable_index: 38, + parameter_index: 0, + parameter_name: "Files", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Files@38(Files:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::get_Files parameter Files as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/2e5e0b1f-58b9-4c3e-b871-b2926181618b", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "put_Files", + vtable_index: 39, + parameter_index: 0, + parameter_name: "Files", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Files@39(Files:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::put_Files parameter Files as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/b818eebc-4ac6-4e4d-8b37-9bf16bd73dbe", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "get_ManagementQueries", + vtable_index: 40, + parameter_index: 0, + parameter_name: "Queries", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_ManagementQueries@40(Queries:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::get_ManagementQueries parameter Queries as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/075523bd-fe49-4418-a35c-1a6304a2d96f", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "put_ManagementQueries", + vtable_index: 41, + parameter_index: 0, + parameter_name: "Queries", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_ManagementQueries@41(Queries:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::put_ManagementQueries parameter Queries as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/4014616b-e79c-4c31-a341-4b93682f4b86", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "get_RegistryKeys", + vtable_index: 44, + parameter_index: 0, + parameter_name: "query", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_RegistryKeys@44(query:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::get_RegistryKeys parameter query as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/8cd3e9f0-7fc4-4145-97e2-1e11068d51cf", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IConfigurationDataCollector", + declaring_iid: "03837514-098b-11d8-9414-505054503030", + method_name: "put_RegistryKeys", + vtable_index: 45, + parameter_index: 0, + parameter_name: "query", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_RegistryKeys@45(query:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IConfigurationDataCollector::put_RegistryKeys parameter query as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/af80e2b4-f631-4d9f-851e-00af476b596b", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IDataCollectorSet", + declaring_iid: "03837520-098b-11d8-9414-505054503030", + method_name: "get_Keywords", + vtable_index: 16, + parameter_index: 0, + parameter_name: "keywords", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Keywords@16(keywords:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IDataCollectorSet::get_Keywords parameter keywords as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/e0d56db0-adbe-4596-bd30-6fa7ed22afdd", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IDataCollectorSet", + declaring_iid: "03837520-098b-11d8-9414-505054503030", + method_name: "put_Keywords", + vtable_index: 17, + parameter_index: 0, + parameter_name: "keywords", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_Keywords@17(keywords:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IDataCollectorSet::put_Keywords parameter keywords as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/48c9bab4-ba47-4486-8b01-fb9e8294870b", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IPerformanceCounterDataCollector", + declaring_iid: "03837506-098b-11d8-9414-505054503030", + method_name: "get_PerformanceCounters", + vtable_index: 34, + parameter_index: 0, + parameter_name: "counters", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_PerformanceCounters@34(counters:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IPerformanceCounterDataCollector::get_PerformanceCounters parameter counters as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/f78f5a32-4fbb-4991-9618-432968c4b0c4", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "IPerformanceCounterDataCollector", + declaring_iid: "03837506-098b-11d8-9414-505054503030", + method_name: "put_PerformanceCounters", + vtable_index: 35, + parameter_index: 0, + parameter_name: "counters", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_PerformanceCounters@35(counters:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft Open Specifications define IPerformanceCounterDataCollector::put_PerformanceCounters parameter counters as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-pla/9cce1255-a3a3-420d-bd3f-42996d685ac8", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "ITraceDataProvider", + declaring_iid: "03837512-098b-11d8-9414-505054503030", + method_name: "get_FilterData", + vtable_index: 19, + parameter_index: 0, + parameter_name: "ppData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_FilterData@19(ppData:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft API documentation defines ITraceDataProvider::get_FilterData parameter ppData as a SAFEARRAY of bytes, requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/pla/nf-pla-itracedataprovider-get_filterdata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Performance", + declaring_interface: "ITraceDataProvider", + declaring_iid: "03837512-098b-11d8-9414-505054503030", + method_name: "put_FilterData", + vtable_index: 20, + parameter_index: 0, + parameter_name: "pData", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "put_FilterData@20(pData:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft API documentation defines ITraceDataProvider::put_FilterData parameter pData as a SAFEARRAY of bytes, requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/pla/nf-pla-itracedataprovider-put_filterdata", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "ITsSbGlobalStore", + declaring_iid: "9ab60f7b-bd72-4d9f-8a3a-a0ea5574e635", + method_name: "EnumerateFarms", + vtable_index: 5, + parameter_index: 2, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "EnumerateFarms@5(ProviderName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,pdwCount:out:required:noconstattr:u32/ptr1/Mutable,pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITsSbGlobalStore::EnumerateFarms parameter pVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/sbtsv/nf-sbtsv-itssbglobalstore-enumeratefarms", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "ITsSbResourcePluginStore", + declaring_iid: "5c38f65f-bcf1-4036-a6bf-9e3cccae0b63", + method_name: "EnumerateFarms", + vtable_index: 9, + parameter_index: 1, + parameter_name: "pVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "EnumerateFarms@9(pdwCount:out:required:noconstattr:u32/ptr1/Mutable,pVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITsSbResourcePluginStore::EnumerateFarms parameter pVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/sbtsv/nf-sbtsv-itssbresourcepluginstore-enumeratefarms", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "ITsSbTaskInfo", + declaring_iid: "523d1083-89be-48dd-99ea-04e82ffa7265", + method_name: "get_Context", + vtable_index: 9, + parameter_index: 0, + parameter_name: "pContext", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_Context@9(pContext:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITsSbTaskInfo::get_Context parameter pContext as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/sbtsv/nf-sbtsv-itssbtaskinfo-get_context", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "ITsSbTaskPluginNotifySink", + declaring_iid: "6aaf899e-c2ec-45ee-aa37-45e60895261a", + method_name: "OnSetTaskTime", + vtable_index: 5, + parameter_index: 8, + parameter_name: "saContext", + element_vartype: RawSafeArrayVartype::Ui1, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "OnSetTaskTime@5(szTargetName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,TaskStartTime:in:required:noconstattr:Windows.Win32.Foundation.FILETIME[Struct]/ptr0/Unspecified,TaskEndTime:in:required:noconstattr:Windows.Win32.Foundation.FILETIME[Struct]/ptr0/Unspecified,TaskDeadline:in:required:noconstattr:Windows.Win32.Foundation.FILETIME[Struct]/ptr0/Unspecified,szTaskLabel:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,szTaskIdentifier:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,szTaskPlugin:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,dwTaskStatus:in:required:noconstattr:u32/ptr0/Unspecified,saContext:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITsSbTaskPluginNotifySink::OnSetTaskTime parameter saContext as SAFEARRAY(BYTE), requiring VT_UI1", + citation: "https://learn.microsoft.com/windows/win32/api/sbtsv/nf-sbtsv-itssbtaskpluginnotifysink-onsettasktime", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "IWorkspace", + declaring_iid: "b922bbb8-4c55-4fea-8496-beb0b44285e5", + method_name: "GetWorkspaceNames", + vtable_index: 3, + parameter_index: 0, + parameter_name: "psaWkspNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetWorkspaceNames@3(psaWkspNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWorkspace::GetWorkspaceNames parameter psaWkspNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/workspaceruntime/nf-workspaceruntime-iworkspace-getworkspacenames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "IWorkspace", + declaring_iid: "b922bbb8-4c55-4fea-8496-beb0b44285e5", + method_name: "StartRemoteApplication", + vtable_index: 4, + parameter_index: 1, + parameter_name: "psaParams", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "StartRemoteApplication@4(bstrWorkspaceId:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,psaParams:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWorkspace::StartRemoteApplication parameter psaParams as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/workspaceruntime/nf-workspaceruntime-iworkspace-startremoteapplication", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "IWorkspace2", + declaring_iid: "96d8d7cf-783e-4286-834c-ebc0e95f783c", + method_name: "StartRemoteApplicationEx", + vtable_index: 6, + parameter_index: 5, + parameter_name: "psaParams", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "StartRemoteApplicationEx@6(bstrWorkspaceId:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,bstrRequestingAppId:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,bstrRequestingAppFamilyName:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,bLaunchIntoImmersiveClient:in:required:noconstattr:Windows.Win32.Foundation.VARIANT_BOOL[Struct]/ptr0/Unspecified/underlying=i16/ptr0/Unspecified,bstrImmersiveClientActivationContext:in:required:noconstattr:Windows.Win32.Foundation.BSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,psaParams:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWorkspace2::StartRemoteApplicationEx parameter psaParams as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/workspaceruntime/nf-workspaceruntime-iworkspace2-startremoteapplicationex", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.RemoteDesktop", + declaring_interface: "IWorkspaceResTypeRegistry", + declaring_iid: "1d428c79-6e2e-4351-a361-c0401a03a0ba", + method_name: "GetRegisteredFileExtensions", + vtable_index: 9, + parameter_index: 1, + parameter_name: "psaFileExtensions", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRegisteredFileExtensions@9(fMachineWide:in:required:noconstattr:Windows.Win32.Foundation.VARIANT_BOOL[Struct]/ptr0/Unspecified/underlying=i16/ptr0/Unspecified,psaFileExtensions:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft API documentation defines IWorkspaceResTypeRegistry::GetRegisteredFileExtensions parameter psaFileExtensions as a SAFEARRAY of BSTR file extensions, requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/workspaceax/nf-workspaceax-iworkspacerestyperegistry-getregisteredfileextensions", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Wmi", + declaring_interface: "IWbemClassObject", + declaring_iid: "dc12a681-737f-11cf-884d-00aa004b2e24", + method_name: "GetNames", + vtable_index: 7, + parameter_index: 3, + parameter_name: "pNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetNames@7(wszQualifierName:in:required:constattr:Windows.Win32.Foundation.PWSTR[Struct]/ptr0/Unspecified/underlying=char16/ptr1/Mutable,lFlags:in:required:noconstattr:Windows.Win32.System.Wmi.WBEM_CONDITION_FLAG_TYPE[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,pQualifierVal:in:required:noconstattr:Windows.Win32.System.Variant.VARIANT[Struct]/ptr1/Mutable,pNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWbemClassObject::GetNames parameter pNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/wbemcli/nf-wbemcli-iwbemclassobject-getnames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Wmi", + declaring_interface: "IWbemContext", + declaring_iid: "44aca674-e8fc-11d0-a07c-00c04fb68820", + method_name: "GetNames", + vtable_index: 4, + parameter_index: 1, + parameter_name: "pNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetNames@4(lFlags:in:required:noconstattr:i32/ptr0/Unspecified,pNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWbemContext::GetNames parameter pNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/wbemcli/nf-wbemcli-iwbemcontext-getnames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.Wmi", + declaring_interface: "IWbemQualifierSet", + declaring_iid: "dc12a680-737f-11cf-884d-00aa004b2e24", + method_name: "GetNames", + vtable_index: 6, + parameter_index: 1, + parameter_name: "pNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetNames@6(lFlags:in:required:noconstattr:i32/ptr0/Unspecified,pNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IWbemQualifierSet::GetNames parameter pNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/wbemcli/nf-wbemcli-iwbemqualifierset-getnames", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.System.WindowsProgramming", + declaring_interface: "ICameraUIControl", + declaring_iid: "b8733adf-3d68-4b8f-bb08-e28a0bed0376", + method_name: "GetSelectedItems", + vtable_index: 9, + parameter_index: 0, + parameter_name: "ppSelectedItemPaths", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSelectedItems@9(ppSelectedItemPaths:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft API documentation defines ICameraUIControl::GetSelectedItems parameter ppSelectedItemPaths as a SAFEARRAY of BSTR captured-item paths, requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/camerauicontrol/nf-camerauicontrol-icamerauicontrol-getselecteditems", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationClientInfoSource", + declaring_iid: "f4b8a2e1-9c3d-4a7e-8f6b-2d5e4c1a9b8f", + method_name: "GetConnectedClients", + vtable_index: 5, + parameter_index: 0, + parameter_name: "clients", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("b2e8a3f1-4c5d-4e7a-8f6b-3d2e1c9a0b8f"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetConnectedClients@5(clients:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft API documentation defines IUIAutomationClientInfoSource::GetConnectedClients parameter clients as a SAFEARRAY of IUIAutomationClientInfo interface pointers, requiring VT_UNKNOWN with IID b2e8a3f1-4c5d-4e7a-8f6b-3d2e1c9a0b8f", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iuiautomationclientinfosource-getconnectedclients", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IAccessibleEx", + declaring_iid: "f8b80ada-2c44-48d0-89be-5ff23c9cd875", + method_name: "GetRuntimeId", + vtable_index: 5, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRuntimeId@5(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IAccessibleEx::GetRuntimeId parameter pRetVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iaccessibleex-getruntimeid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IAccessibleHostingElementProviders", + declaring_iid: "33ac331b-943e-4020-b295-db37784974a3", + method_name: "GetEmbeddedFragmentRoots", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("620ce2a5-ab8f-40a9-86cb-de3c75599b58"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEmbeddedFragmentRoots@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IAccessibleHostingElementProviders::GetEmbeddedFragmentRoots parameter pRetVal as SAFEARRAY(IRawElementProviderFragmentRoot*), requiring VT_UNKNOWN with IID 620ce2a5-ab8f-40a9-86cb-de3c75599b58", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iaccessiblehostingelementproviders-getembeddedfragmentroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IAccessibleWindowlessSite", + declaring_iid: "bf3abd9c-76da-4389-9eb6-1427d25abab7", + method_name: "QueryObjectIdRanges", + vtable_index: 5, + parameter_index: 1, + parameter_name: "psaRanges", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "QueryObjectIdRanges@5(pRangesOwner:in:required:noconstattr:Windows.Win32.UI.Accessibility.IAccessibleHandler[Interface]{03022430-abc4-11d0-bde2-00aa001a1953}/ptr0/Unspecified,psaRanges:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IAccessibleWindowlessSite::QueryObjectIdRanges parameter psaRanges as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/oleacc/nf-oleacc-iaccessiblewindowlesssite-queryobjectidranges", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IDragProvider", + declaring_iid: "6aa7bbbb-7ff9-497d-904f-d20b897929d8", + method_name: "get_DropEffects", + vtable_index: 5, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_DropEffects@5(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDragProvider::get_DropEffects parameter pRetVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-idragprovider-get_dropeffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IDragProvider", + declaring_iid: "6aa7bbbb-7ff9-497d-904f-d20b897929d8", + method_name: "GetGrabbedItems", + vtable_index: 6, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetGrabbedItems@6(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDragProvider::GetGrabbedItems parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-idragprovider-getgrabbeditems", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IDropTargetProvider", + declaring_iid: "bae82bfd-358a-481c-85a0-d8b4d90a5d61", + method_name: "get_DropTargetEffects", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_DropTargetEffects@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IDropTargetProvider::get_DropTargetEffects parameter pRetVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-idroptargetprovider-get_droptargeteffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ILegacyIAccessibleProvider", + declaring_iid: "e44c3566-915d-4070-99c6-047bff5a08f5", + method_name: "GetSelection", + vtable_index: 15, + parameter_index: 0, + parameter_name: "pvarSelectedChildren", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSelection@15(pvarSelectedChildren:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ILegacyIAccessibleProvider::GetSelection parameter pvarSelectedChildren as SAFEARRAY(IRawElementProviderSimple *), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-ilegacyiaccessibleprovider-getselection", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IMultipleViewProvider", + declaring_iid: "6278cab1-b556-4a1a-b4e0-418acc523201", + method_name: "GetSupportedViews", + vtable_index: 6, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSupportedViews@6(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IMultipleViewProvider::GetSupportedViews parameter pRetVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-imultipleviewprovider-getsupportedviews", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IProxyProviderWinEventSink", + declaring_iid: "4fd82b78-a43e-46ac-9803-0a6969c7c183", + method_name: "AddStructureChangedEvent", + vtable_index: 5, + parameter_index: 2, + parameter_name: "runtimeId", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "AddStructureChangedEvent@5(pProvider:in:required:noconstattr:Windows.Win32.UI.Accessibility.IRawElementProviderSimple[Interface]{d6dd68d1-86fd-4332-8666-9abedea2d24c}/ptr0/Unspecified,structureChangeType:in:required:noconstattr:Windows.Win32.UI.Accessibility.StructureChangeType[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,runtimeId:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IProxyProviderWinEventSink::AddStructureChangedEvent parameter runtimeId as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iproxyproviderwineventsink-addstructurechangedevent", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderAdviseEvents", + declaring_iid: "a407b27b-0f6d-4427-9292-473c7bf93258", + method_name: "AdviseEventAdded", + vtable_index: 3, + parameter_index: 1, + parameter_name: "propertyIDs", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "AdviseEventAdded@3(eventId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_EVENT_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,propertyIDs:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderAdviseEvents::AdviseEventAdded parameter propertyIDs as SAFEARRAY(PROPERTYID), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementprovideradviseevents-adviseeventadded", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderAdviseEvents", + declaring_iid: "a407b27b-0f6d-4427-9292-473c7bf93258", + method_name: "AdviseEventRemoved", + vtable_index: 4, + parameter_index: 1, + parameter_name: "propertyIDs", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "AdviseEventRemoved@4(eventId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_EVENT_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,propertyIDs:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderAdviseEvents::AdviseEventRemoved parameter propertyIDs as SAFEARRAY(PROPERTYID), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementprovideradviseevents-adviseeventremoved", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderFragment", + declaring_iid: "f7063da8-8359-439c-9297-bbc5299a7d87", + method_name: "GetRuntimeId", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRuntimeId@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderFragment::GetRuntimeId parameter pRetVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderfragment-getruntimeid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderFragment", + declaring_iid: "f7063da8-8359-439c-9297-bbc5299a7d87", + method_name: "GetEmbeddedFragmentRoots", + vtable_index: 6, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("620ce2a5-ab8f-40a9-86cb-de3c75599b58"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEmbeddedFragmentRoots@6(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderFragment::GetEmbeddedFragmentRoots parameter pRetVal as SAFEARRAY(IRawElementProviderFragmentRoot*), requiring VT_UNKNOWN with IID 620ce2a5-ab8f-40a9-86cb-de3c75599b58, and explicitly allow successful NULL output", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderfragment-getembeddedfragmentroots", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderHostingAccessibles", + declaring_iid: "24be0b07-d37d-487a-98cf-a13ed465e9b3", + method_name: "GetEmbeddedAccessibles", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("618736e0-3c3d-11cf-810c-00aa00389b71"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetEmbeddedAccessibles@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderHostingAccessibles::GetEmbeddedAccessibles parameter pRetVal as SAFEARRAY(IAccessible*), requiring VT_UNKNOWN with IID 618736e0-3c3d-11cf-810c-00aa00389b71", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderhostingaccessibles-getembeddedaccessibles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IRawElementProviderWindowlessSite", + declaring_iid: "0a2a93cc-bfad-42ac-9b2e-0991fb0d3ea0", + method_name: "GetRuntimeIdPrefix", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRuntimeIdPrefix@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IRawElementProviderWindowlessSite::GetRuntimeIdPrefix parameter pRetVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderwindowlesssite-getruntimeidprefix", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ISelectionProvider", + declaring_iid: "fb8b03af-3bdf-48d4-bd36-1a65793be168", + method_name: "GetSelection", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSelection@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ISelectionProvider::GetSelection parameter pRetVal as SAFEARRAY(IRawElementProviderSimple *), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-iselectionprovider-getselection", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ISpreadsheetItemProvider", + declaring_iid: "eaed4660-7b3d-4879-a2e6-365ce603f3d0", + method_name: "GetAnnotationObjects", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetAnnotationObjects@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ISpreadsheetItemProvider::GetAnnotationObjects parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-ispreadsheetitemprovider-getannotationobjects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ISpreadsheetItemProvider", + declaring_iid: "eaed4660-7b3d-4879-a2e6-365ce603f3d0", + method_name: "GetAnnotationTypes", + vtable_index: 5, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetAnnotationTypes@5(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ISpreadsheetItemProvider::GetAnnotationTypes parameter pRetVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-ispreadsheetitemprovider-getannotationtypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITableItemProvider", + declaring_iid: "b9734fa6-771f-4d78-9c90-2517999349cd", + method_name: "GetRowHeaderItems", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRowHeaderItems@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITableItemProvider::GetRowHeaderItems parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itableitemprovider-getrowheaderitems", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITableItemProvider", + declaring_iid: "b9734fa6-771f-4d78-9c90-2517999349cd", + method_name: "GetColumnHeaderItems", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetColumnHeaderItems@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITableItemProvider::GetColumnHeaderItems parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itableitemprovider-getcolumnheaderitems", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITableProvider", + declaring_iid: "9c860395-97b3-490a-b52a-858cc22af166", + method_name: "GetRowHeaders", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRowHeaders@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITableProvider::GetRowHeaders parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itableprovider-getrowheaders", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITableProvider", + declaring_iid: "9c860395-97b3-490a-b52a-858cc22af166", + method_name: "GetColumnHeaders", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetColumnHeaders@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITableProvider::GetColumnHeaders parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itableprovider-getcolumnheaders", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITextProvider", + declaring_iid: "3589c92c-63f3-4367-99bb-ada653b77cf2", + method_name: "GetSelection", + vtable_index: 3, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("5347ad7b-c355-46f8-aff5-909033582f63"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetSelection@3(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITextProvider::GetSelection parameter pRetVal as SAFEARRAY(ITextRangeProvider *), requiring VT_UNKNOWN with IID 5347ad7b-c355-46f8-aff5-909033582f63", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextprovider-getselection", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITextProvider", + declaring_iid: "3589c92c-63f3-4367-99bb-ada653b77cf2", + method_name: "GetVisibleRanges", + vtable_index: 4, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("5347ad7b-c355-46f8-aff5-909033582f63"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetVisibleRanges@4(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITextProvider::GetVisibleRanges parameter pRetVal as SAFEARRAY(ITextRangeProvider *), requiring VT_UNKNOWN with IID 5347ad7b-c355-46f8-aff5-909033582f63", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextprovider-getvisibleranges", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITextRangeProvider", + declaring_iid: "5347ad7b-c355-46f8-aff5-909033582f63", + method_name: "GetBoundingRectangles", + vtable_index: 10, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::R8, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetBoundingRectangles@10(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITextRangeProvider::GetBoundingRectangles parameter pRetVal as SAFEARRAY(double), requiring VT_R8", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextrangeprovider-getboundingrectangles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "ITextRangeProvider", + declaring_iid: "5347ad7b-c355-46f8-aff5-909033582f63", + method_name: "GetChildren", + vtable_index: 20, + parameter_index: 0, + parameter_name: "pRetVal", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d6dd68d1-86fd-4332-8666-9abedea2d24c"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetChildren@20(pRetVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define ITextRangeProvider::GetChildren parameter pRetVal as SAFEARRAY(IRawElementProviderSimple*), requiring VT_UNKNOWN with IID d6dd68d1-86fd-4332-8666-9abedea2d24c", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextrangeprovider-getchildren", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "CompareRuntimeIds", + vtable_index: 4, + parameter_index: 0, + parameter_name: "runtimeId1", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "CompareRuntimeIds@4(runtimeId1:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,runtimeId2:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,areSame:out:required:noconstattr:Windows.Win32.Foundation.BOOL[Struct]/ptr1/Mutable/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::CompareRuntimeIds parameter runtimeId1 as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-compareruntimeids", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "CompareRuntimeIds", + vtable_index: 4, + parameter_index: 1, + parameter_name: "runtimeId2", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "CompareRuntimeIds@4(runtimeId1:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,runtimeId2:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,areSame:out:required:noconstattr:Windows.Win32.Foundation.BOOL[Struct]/ptr1/Mutable/underlying=i32/ptr0/Unspecified)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::CompareRuntimeIds parameter runtimeId2 as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-compareruntimeids", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "CreateAndConditionFromArray", + vtable_index: 26, + parameter_index: 0, + parameter_name: "conditions", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("352ffba8-0973-437c-a61f-f64cafd81df9"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "CreateAndConditionFromArray@26(conditions:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,newCondition:out:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationCondition[Interface]{352ffba8-0973-437c-a61f-f64cafd81df9}/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::CreateAndConditionFromArray parameter conditions as SAFEARRAY(IUIAutomationCondition), requiring VT_UNKNOWN with IID 352ffba8-0973-437c-a61f-f64cafd81df9", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createandconditionfromarray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "CreateOrConditionFromArray", + vtable_index: 29, + parameter_index: 0, + parameter_name: "conditions", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("352ffba8-0973-437c-a61f-f64cafd81df9"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "CreateOrConditionFromArray@29(conditions:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,newCondition:out:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationCondition[Interface]{352ffba8-0973-437c-a61f-f64cafd81df9}/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::CreateOrConditionFromArray parameter conditions as SAFEARRAY(IUIAutomationCondition), requiring VT_UNKNOWN with IID 352ffba8-0973-437c-a61f-f64cafd81df9", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createorconditionfromarray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "AddPropertyChangedEventHandler", + vtable_index: 35, + parameter_index: 4, + parameter_name: "propertyArray", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "AddPropertyChangedEventHandler@35(element:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,scope:in:required:noconstattr:Windows.Win32.UI.Accessibility.TreeScope[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,cacheRequest:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationCacheRequest[Interface]{b32a92b5-bc25-4078-9c08-d7ee95c48e03}/ptr0/Unspecified,handler:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationPropertyChangedEventHandler[Interface]{40cd37d4-c756-4b0c-8c6f-bddfeeb13b50}/ptr0/Unspecified,propertyArray:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::AddPropertyChangedEventHandler parameter propertyArray as SAFEARRAY(PROPERTYID), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-addpropertychangedeventhandler", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "IntNativeArrayToSafeArray", + vtable_index: 42, + parameter_index: 2, + parameter_name: "safeArray", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "IntNativeArrayToSafeArray@42(array:in:required:noconstattr:i32/ptr1/Mutable:array=Some(1)/None/Elements/false/false/None,arrayCount:in:required:noconstattr:i32/ptr0/Unspecified,safeArray:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::IntNativeArrayToSafeArray parameter safeArray as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-intnativearraytosafearray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "IntSafeArrayToNativeArray", + vtable_index: 43, + parameter_index: 0, + parameter_name: "intArray", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "IntSafeArrayToNativeArray@43(intArray:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,array:out:required:noconstattr:i32/ptr2/Mutable:array=Some(2)/None/Elements/false/false/None,arrayCount:out:required:noconstattr:i32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::IntSafeArrayToNativeArray parameter intArray as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-intsafearraytonativearray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "SafeArrayToRectNativeArray", + vtable_index: 46, + parameter_index: 0, + parameter_name: "rects", + element_vartype: RawSafeArrayVartype::R8, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SafeArrayToRectNativeArray@46(rects:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable,rectArray:out:required:noconstattr:Windows.Win32.Foundation.RECT[Struct]/ptr2/Mutable:array=Some(2)/None/Elements/false/false/None,rectArrayCount:out:required:noconstattr:i32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::SafeArrayToRectNativeArray parameter rects as SAFEARRAY(double), requiring VT_R8", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-safearraytorectnativearray", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "PollForPotentialSupportedPatterns", + vtable_index: 51, + parameter_index: 1, + parameter_name: "patternIds", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "PollForPotentialSupportedPatterns@51(pElement:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,patternIds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,patternNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::PollForPotentialSupportedPatterns parameter patternIds as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-pollforpotentialsupportedpatterns", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "PollForPotentialSupportedPatterns", + vtable_index: 51, + parameter_index: 2, + parameter_name: "patternNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "PollForPotentialSupportedPatterns@51(pElement:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,patternIds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,patternNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::PollForPotentialSupportedPatterns parameter patternNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-pollforpotentialsupportedpatterns", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "PollForPotentialSupportedProperties", + vtable_index: 52, + parameter_index: 1, + parameter_name: "propertyIds", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "PollForPotentialSupportedProperties@52(pElement:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,propertyIds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,propertyNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::PollForPotentialSupportedProperties parameter propertyIds as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-pollforpotentialsupportedproperties", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomation", + declaring_iid: "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee", + method_name: "PollForPotentialSupportedProperties", + vtable_index: 52, + parameter_index: 2, + parameter_name: "propertyNames", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "PollForPotentialSupportedProperties@52(pElement:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,propertyIds:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,propertyNames:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomation::PollForPotentialSupportedProperties parameter propertyNames as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-pollforpotentialsupportedproperties", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationAndCondition", + declaring_iid: "a7d0af36-b912-45fe-9855-091ddc174aec", + method_name: "GetChildren", + vtable_index: 5, + parameter_index: 0, + parameter_name: "childArray", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("352ffba8-0973-437c-a61f-f64cafd81df9"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetChildren@5(childArray:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationAndCondition::GetChildren parameter childArray as SAFEARRAY(IUIAutomationCondition), requiring VT_UNKNOWN with IID 352ffba8-0973-437c-a61f-f64cafd81df9", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationandcondition-getchildren", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationDragPattern", + declaring_iid: "1dc7b570-1f54-4bad-bcda-d36a722fb7bd", + method_name: "get_CurrentDropEffects", + vtable_index: 7, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CurrentDropEffects@7(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationDragPattern::get_CurrentDropEffects parameter retVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-get_currentdropeffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationDragPattern", + declaring_iid: "1dc7b570-1f54-4bad-bcda-d36a722fb7bd", + method_name: "get_CachedDropEffects", + vtable_index: 8, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CachedDropEffects@8(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationDragPattern::get_CachedDropEffects parameter retVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-get_cacheddropeffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationDropTargetPattern", + declaring_iid: "69a095f7-eee4-430e-a46b-fb73b1ae39a5", + method_name: "get_CurrentDropTargetEffects", + vtable_index: 5, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CurrentDropTargetEffects@5(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationDropTargetPattern::get_CurrentDropTargetEffects parameter retVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationdroptargetpattern-get_currentdroptargeteffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationDropTargetPattern", + declaring_iid: "69a095f7-eee4-430e-a46b-fb73b1ae39a5", + method_name: "get_CachedDropTargetEffects", + vtable_index: 6, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CachedDropTargetEffects@6(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationDropTargetPattern::get_CachedDropTargetEffects parameter retVal as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationdroptargetpattern-get_cacheddroptargeteffects", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationElement", + declaring_iid: "d22108aa-8ac5-49a5-837b-37bbb3d7591e", + method_name: "GetRuntimeId", + vtable_index: 4, + parameter_index: 0, + parameter_name: "runtimeId", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetRuntimeId@4(runtimeId:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationElement::GetRuntimeId parameter runtimeId as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getruntimeid", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationElement4", + declaring_iid: "3b6e233c-52fb-4063-a4c9-77c075c2a06b", + method_name: "get_CurrentAnnotationTypes", + vtable_index: 97, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CurrentAnnotationTypes@97(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationElement4::get_CurrentAnnotationTypes parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement4-get_currentannotationtypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationElement4", + declaring_iid: "3b6e233c-52fb-4063-a4c9-77c075c2a06b", + method_name: "get_CachedAnnotationTypes", + vtable_index: 102, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "get_CachedAnnotationTypes@102(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationElement4::get_CachedAnnotationTypes parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement4-get_cachedannotationtypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationMultipleViewPattern", + declaring_iid: "8d253c91-1dc5-4bb5-b18f-ade16fa495e8", + method_name: "GetCurrentSupportedViews", + vtable_index: 6, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetCurrentSupportedViews@6(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationMultipleViewPattern::GetCurrentSupportedViews parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationmultipleviewpattern-getcurrentsupportedviews", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationMultipleViewPattern", + declaring_iid: "8d253c91-1dc5-4bb5-b18f-ade16fa495e8", + method_name: "GetCachedSupportedViews", + vtable_index: 8, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetCachedSupportedViews@8(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationMultipleViewPattern::GetCachedSupportedViews parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationmultipleviewpattern-getcachedsupportedviews", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationOrCondition", + declaring_iid: "8753f032-3db1-47b5-a1fc-6e34a266c712", + method_name: "GetChildren", + vtable_index: 5, + parameter_index: 0, + parameter_name: "childArray", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("352ffba8-0973-437c-a61f-f64cafd81df9"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetChildren@5(childArray:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationOrCondition::GetChildren parameter childArray as SAFEARRAY(IUIAutomationCondition), requiring VT_UNKNOWN with IID 352ffba8-0973-437c-a61f-f64cafd81df9", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationorcondition-getchildren", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationProxyFactoryEntry", + declaring_iid: "d50e472e-b64b-490c-bca1-d30696f9f289", + method_name: "SetWinEventsForAutomationEvent", + vtable_index: 14, + parameter_index: 2, + parameter_name: "winEvents", + element_vartype: RawSafeArrayVartype::Ui4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SetWinEventsForAutomationEvent@14(eventId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_EVENT_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,propertyId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_PROPERTY_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,winEvents:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationProxyFactoryEntry::SetWinEventsForAutomationEvent parameter winEvents as SAFEARRAY(UINT), requiring VT_UI4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationproxyfactoryentry-setwineventsforautomationevent", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationProxyFactoryEntry", + declaring_iid: "d50e472e-b64b-490c-bca1-d30696f9f289", + method_name: "GetWinEventsForAutomationEvent", + vtable_index: 15, + parameter_index: 2, + parameter_name: "winEvents", + element_vartype: RawSafeArrayVartype::Ui4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetWinEventsForAutomationEvent@15(eventId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_EVENT_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,propertyId:in:required:noconstattr:Windows.Win32.UI.Accessibility.UIA_PROPERTY_ID[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,winEvents:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationProxyFactoryEntry::GetWinEventsForAutomationEvent parameter winEvents as SAFEARRAY(UINT), requiring VT_UI4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationproxyfactoryentry-getwineventsforautomationevent", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationProxyFactoryMapping", + declaring_iid: "09e31e18-872d-4873-93d1-1e541ec133fd", + method_name: "GetTable", + vtable_index: 4, + parameter_index: 0, + parameter_name: "table", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d50e472e-b64b-490c-bca1-d30696f9f289"), + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetTable@4(table:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationProxyFactoryMapping::GetTable parameter table as SAFEARRAY(IUIAutomationProxyFactoryEntry), requiring VT_UNKNOWN with IID d50e472e-b64b-490c-bca1-d30696f9f289", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationproxyfactorymapping-gettable", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationProxyFactoryMapping", + declaring_iid: "09e31e18-872d-4873-93d1-1e541ec133fd", + method_name: "SetTable", + vtable_index: 6, + parameter_index: 0, + parameter_name: "factoryList", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d50e472e-b64b-490c-bca1-d30696f9f289"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "SetTable@6(factoryList:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationProxyFactoryMapping::SetTable parameter factoryList as SAFEARRAY(IUIAutomationProxyFactoryEntry), requiring VT_UNKNOWN with IID d50e472e-b64b-490c-bca1-d30696f9f289", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationproxyfactorymapping-settable", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationProxyFactoryMapping", + declaring_iid: "09e31e18-872d-4873-93d1-1e541ec133fd", + method_name: "InsertEntries", + vtable_index: 7, + parameter_index: 1, + parameter_name: "factoryList", + element_vartype: RawSafeArrayVartype::Unknown, + element_iid: Some("d50e472e-b64b-490c-bca1-d30696f9f289"), + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "InsertEntries@7(before:in:required:noconstattr:u32/ptr0/Unspecified,factoryList:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationProxyFactoryMapping::InsertEntries parameter factoryList as SAFEARRAY(IUIAutomationProxyFactoryEntry), requiring VT_UNKNOWN with IID d50e472e-b64b-490c-bca1-d30696f9f289", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationproxyfactorymapping-insertentries", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationSpreadsheetItemPattern", + declaring_iid: "7d4fb86c-8d34-40e1-8e83-62c15204e335", + method_name: "GetCurrentAnnotationTypes", + vtable_index: 5, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetCurrentAnnotationTypes@5(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationSpreadsheetItemPattern::GetCurrentAnnotationTypes parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcurrentannotationtypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationSpreadsheetItemPattern", + declaring_iid: "7d4fb86c-8d34-40e1-8e83-62c15204e335", + method_name: "GetCachedAnnotationTypes", + vtable_index: 8, + parameter_index: 0, + parameter_name: "retVal", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetCachedAnnotationTypes@8(retVal:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationSpreadsheetItemPattern::GetCachedAnnotationTypes parameter retVal as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcachedannotationtypes", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationStructureChangedEventHandler", + declaring_iid: "e81d1b4e-11c5-42f8-9754-e7036c79f054", + method_name: "HandleStructureChangedEvent", + vtable_index: 3, + parameter_index: 2, + parameter_name: "runtimeId", + element_vartype: RawSafeArrayVartype::I4, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "HandleStructureChangedEvent@3(sender:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,changeType:in:required:noconstattr:Windows.Win32.UI.Accessibility.StructureChangeType[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,runtimeId:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationStructureChangedEventHandler::HandleStructureChangedEvent parameter runtimeId as SAFEARRAY(int), requiring VT_I4", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationstructurechangedeventhandler-handlestructurechangedevent", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationTextEditTextChangedEventHandler", + declaring_iid: "92faa680-e704-4156-931a-e32d5bb38f3f", + method_name: "HandleTextEditTextChangedEvent", + vtable_index: 3, + parameter_index: 2, + parameter_name: "eventStrings", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::BorrowedInput, + raw_method_shape: "HandleTextEditTextChangedEvent@3(sender:in:required:noconstattr:Windows.Win32.UI.Accessibility.IUIAutomationElement[Interface]{d22108aa-8ac5-49a5-837b-37bbb3d7591e}/ptr0/Unspecified,textEditChangeType:in:required:noconstattr:Windows.Win32.UI.Accessibility.TextEditChangeType[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,eventStrings:in:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationTextEditTextChangedEventHandler::HandleTextEditTextChangedEvent parameter eventStrings as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextedittextchangedeventhandler-handletextedittextchangedevent", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationTextRange", + declaring_iid: "a543cc6a-f4ae-494b-8239-c814481187a8", + method_name: "GetBoundingRectangles", + vtable_index: 10, + parameter_index: 0, + parameter_name: "boundingRects", + element_vartype: RawSafeArrayVartype::R8, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetBoundingRectangles@10(boundingRects:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationTextRange::GetBoundingRectangles parameter boundingRects as SAFEARRAY(double), requiring VT_R8", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-getboundingrectangles", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Accessibility", + declaring_interface: "IUIAutomationTextRange3", + declaring_iid: "6a315d69-5512-4c2e-85f0-53fce6dd4bc2", + method_name: "GetAttributeValues", + vtable_index: 24, + parameter_index: 2, + parameter_name: "attributeValues", + element_vartype: RawSafeArrayVartype::Variant, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetAttributeValues@24(attributeIds:in:required:constattr:Windows.Win32.UI.Accessibility.UIA_TEXTATTRIBUTE_ID[Enum]/ptr1/Mutable/underlying=i32/ptr0/Unspecified:array=Some(1)/None/Elements/false/false/None,attributeIdCount:in:required:noconstattr:i32/ptr0/Unspecified,attributeValues:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IUIAutomationTextRange3::GetAttributeValues parameter attributeValues as SAFEARRAY(VARIANT), requiring VT_VARIANT", + citation: "https://learn.microsoft.com/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange3-getattributevalues", + }, + RawSafeArrayEvidence { + declaring_namespace: "Windows.Win32.UI.Input.Ime", + declaring_interface: "IImePlugInDictDictionaryList", + declaring_iid: "98752974-b0a6-489b-8f6f-bff3769c8eeb", + method_name: "GetDictionariesInUse", + vtable_index: 3, + parameter_index: 0, + parameter_name: "prgDictionaryGUID", + element_vartype: RawSafeArrayVartype::Bstr, + element_iid: None, + ownership: RawSafeArrayOwnership::OwnedOutput, + raw_method_shape: "GetDictionariesInUse@3(prgDictionaryGUID:out:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,prgDateCreated:inout:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable,prgfEncrypted:inout:required:noconstattr:Windows.Win32.System.Com.SAFEARRAY[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next", + reason: "Microsoft SDK IDL and API documentation define IImePlugInDictDictionaryList::GetDictionariesInUse parameter prgDictionaryGUID as SAFEARRAY(BSTR), requiring VT_BSTR", + citation: "https://learn.microsoft.com/windows/win32/api/msimeapi/nf-msimeapi-iimeplugindictdictionarylist-getdictionariesinuse", + }, +]; + +pub(crate) fn registered_safe_array_evidence( + namespace: &str, + interface: &str, + interface_iid: &str, + method: &str, + vtable_index: usize, + parameter_index: usize, +) -> Option { + SAFE_ARRAY_EVIDENCE + .iter() + .find(|evidence| { + evidence.declaring_namespace == namespace + && evidence.declaring_interface == interface + && evidence.declaring_iid.eq_ignore_ascii_case(interface_iid) + && evidence.method_name == method + && evidence.vtable_index == vtable_index + && evidence.parameter_index == parameter_index + }) + .cloned() +} + +pub(crate) fn safe_array_evidence_for_declaration( + namespace: &str, + interface: &str, + method: &str, + parameter_index: usize, +) -> Option { + SAFE_ARRAY_EVIDENCE + .iter() + .find(|evidence| { + evidence.declaring_namespace == namespace + && evidence.declaring_interface == interface + && evidence.method_name == method + && evidence.parameter_index == parameter_index + }) + .cloned() +} + +pub(crate) fn safe_array_output_allows_null(evidence: &RawSafeArrayEvidence) -> bool { + if evidence.declaring_namespace != "Windows.Win32.UI.Accessibility" { + return false; + } + if evidence.declaring_interface == "IRawElementProviderFragment" + && evidence + .declaring_iid + .eq_ignore_ascii_case("f7063da8-8359-439c-9297-bbc5299a7d87") + && evidence.method_name == "GetRuntimeId" + && evidence.vtable_index == 4 + && evidence.parameter_index == 0 + && evidence.parameter_name == "pRetVal" + && evidence.ownership == RawSafeArrayOwnership::OwnedOutput + && evidence.element_vartype == RawSafeArrayVartype::I4 + && evidence.element_iid.is_none() + && evidence.citation + == "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderfragment-getruntimeid" + { + return true; + } + if evidence.parameter_index != 0 + || evidence.parameter_name != "pRetVal" + || evidence.ownership != RawSafeArrayOwnership::OwnedOutput + || evidence.element_vartype != RawSafeArrayVartype::Unknown + { + return false; + } + (evidence.declaring_interface == "ITextProvider" + && evidence + .declaring_iid + .eq_ignore_ascii_case("3589c92c-63f3-4367-99bb-ada653b77cf2") + && evidence.method_name == "GetSelection" + && evidence.vtable_index == 3 + && evidence.element_iid == Some("5347ad7b-c355-46f8-aff5-909033582f63") + && evidence.citation + == "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-itextprovider-getselection") + || (evidence.declaring_interface == "IRawElementProviderFragment" + && evidence + .declaring_iid + .eq_ignore_ascii_case("f7063da8-8359-439c-9297-bbc5299a7d87") + && evidence.method_name == "GetEmbeddedFragmentRoots" + && evidence.vtable_index == 6 + && evidence.element_iid == Some("620ce2a5-ab8f-40a9-86cb-de3c75599b58") + && evidence.citation + == "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-irawelementproviderfragment-getembeddedfragmentroots") + || (evidence.declaring_interface == "IDragProvider" + && evidence + .declaring_iid + .eq_ignore_ascii_case("6aa7bbbb-7ff9-497d-904f-d20b897929d8") + && evidence.method_name == "GetGrabbedItems" + && evidence.vtable_index == 6 + && evidence.element_iid == Some("d6dd68d1-86fd-4332-8666-9abedea2d24c") + && evidence.citation + == "https://learn.microsoft.com/windows/win32/api/uiautomationcore/nf-uiautomationcore-idragprovider-getgrabbeditems") +} + +#[cfg(test)] +pub(crate) fn all_safe_array_evidence() -> &'static [RawSafeArrayEvidence] { + SAFE_ARRAY_EVIDENCE +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn registry_keys_and_evidence_are_exact() { + let mut keys = std::collections::BTreeSet::new(); + assert_eq!(SAFE_ARRAY_EVIDENCE.len(), 209); + for evidence in SAFE_ARRAY_EVIDENCE { + assert!(keys.insert(( + evidence.declaring_namespace, + evidence.declaring_interface, + evidence.declaring_iid, + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + ))); + assert!( + evidence + .citation + .starts_with("https://learn.microsoft.com/") + ); + assert!(!evidence.reason.is_empty()); + assert!(!evidence.raw_method_shape.is_empty()); + assert_eq!( + evidence.element_iid.is_some(), + evidence.element_vartype == RawSafeArrayVartype::Unknown + ); + assert_eq!( + registered_safe_array_evidence( + evidence.declaring_namespace, + evidence.declaring_interface, + evidence.declaring_iid, + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + ) + .as_ref(), + Some(evidence) + ); + } + assert_eq!( + SAFE_ARRAY_EVIDENCE + .iter() + .filter(|evidence| safe_array_output_allows_null(evidence)) + .map(|evidence| ( + evidence.declaring_interface, + evidence.method_name, + evidence.vtable_index, + evidence.parameter_index, + )) + .collect::>(), + std::collections::BTreeSet::from([ + ( + "IRawElementProviderFragment", + "GetEmbeddedFragmentRoots", + 6, + 0 + ), + ("IRawElementProviderFragment", "GetRuntimeId", 4, 0), + ("IDragProvider", "GetGrabbedItems", 6, 0), + ("ITextProvider", "GetSelection", 3, 0), + ]) + ); + } + + #[test] + fn documented_vartype_values_match_automation_constants() { + use windows::Win32::System::Variant::{ + VT_BSTR, VT_I4, VT_R8, VT_UI1, VT_UI4, VT_UNKNOWN, VT_VARIANT, + }; + + assert_eq!(RawSafeArrayVartype::I4.value(), VT_I4.0); + assert_eq!(RawSafeArrayVartype::R8.value(), VT_R8.0); + assert_eq!(RawSafeArrayVartype::Bstr.value(), VT_BSTR.0); + assert_eq!(RawSafeArrayVartype::Variant.value(), VT_VARIANT.0); + assert_eq!(RawSafeArrayVartype::Unknown.value(), VT_UNKNOWN.0); + assert_eq!(RawSafeArrayVartype::Ui1.value(), VT_UI1.0); + assert_eq!(RawSafeArrayVartype::Ui4.value(), VT_UI4.0); + } + + #[test] + fn documented_interface_iids_match_windows_rs() { + use windows::Win32::UI::Accessibility::{ + IRawElementProviderFragmentRoot, IRawElementProviderSimple, ITextRangeProvider, + IUIAutomationCondition, + }; + use windows::core::Interface; + + assert_eq!( + ITextRangeProvider::IID, + windows::core::GUID::from_u128(0x5347ad7b_c355_46f8_aff5_909033582f63) + ); + assert_eq!( + IRawElementProviderSimple::IID, + windows::core::GUID::from_u128(0xd6dd68d1_86fd_4332_8666_9abedea2d24c) + ); + assert_eq!( + IRawElementProviderFragmentRoot::IID, + windows::core::GUID::from_u128(0x620ce2a5_ab8f_40a9_86cb_de3c75599b58) + ); + assert_eq!( + IUIAutomationCondition::IID, + windows::core::GUID::from_u128(0x352ffba8_0973_437c_a61f_f64cafd81df9) + ); + } +} diff --git a/tools/dynwinrt-codegen/src/lib.rs b/tools/dynwinrt-codegen/src/lib.rs index f3e29f4a..34795fa1 100644 --- a/tools/dynwinrt-codegen/src/lib.rs +++ b/tools/dynwinrt-codegen/src/lib.rs @@ -2,7 +2,10 @@ // Licensed under the MIT License. pub mod codegen; +mod com_borrowed_handle_registry; +mod com_enumerator_registry; pub mod com_metadata; +mod com_safe_array_registry; pub mod meta; pub mod types; pub mod xml_doc; diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 9cb952f9..30f3ca96 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -1217,6 +1217,7 @@ fn write_js_barrel_and_manifest(output_dir: &Path, index_content: &str) -> Resul fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { let mut modules: BTreeMap> = BTreeMap::new(); + let mut contents: BTreeMap = BTreeMap::new(); let entries = fs::read_dir(com_output_dir).map_err(|error| { format!( "Failed to read COM output directory {}: {error}", @@ -1239,8 +1240,10 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { let exports = collect_com_cjs_exports(&content); if !exports.is_empty() { modules.insert(module.to_string(), exports); + contents.insert(module.to_string(), content); } } + deduplicate_com_barrel_exports(&mut modules, &contents)?; let mut index = String::from("// Generated by dynwinrt-codegen - do not edit\n"); for (module, exports) in &modules { @@ -1249,6 +1252,7 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { exports.iter().cloned().collect::>().join(", ") )); } + let cjs_index = typescript::esm_index_to_cjs_getter(&index); let esm_index = typescript::esm_index_to_esm(&index); fs::write(com_output_dir.join("index.js"), &cjs_index) @@ -1264,6 +1268,51 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { Ok(()) } +fn deduplicate_com_barrel_exports( + modules: &mut BTreeMap>, + contents: &BTreeMap, +) -> Result<(), String> { + let mut owners = BTreeMap::)>::new(); + for (module, exports) in modules.iter_mut() { + let content = &contents[module]; + let names = exports.iter().cloned().collect::>(); + for name in names { + let signature = native_pod_factory_signature(content, &name); + if let Some((owner, owner_signature)) = owners.get(&name) { + if signature.is_some() && signature.as_ref() == owner_signature.as_ref() { + exports.remove(&name); + } else { + return Err(format!( + "COM barrel export `{name}` is ambiguous between `{owner}.js` and `{module}.js`" + )); + } + } else { + owners.insert(name, (module.clone(), signature)); + } + } + } + Ok(()) +} + +fn native_pod_factory_signature(content: &str, export_name: &str) -> Option { + let pod_name = export_name.strip_prefix("create")?; + if pod_name.is_empty() { + return None; + } + let pod_name = pod_name.strip_suffix("Array").unwrap_or(pod_name); + [ + format!("const _nativeLayout_{pod_name} = "), + format!("const _nativeUnionLayout_{pod_name} = "), + ] + .into_iter() + .find_map(|prefix| { + content + .lines() + .find(|line| line.starts_with(&prefix)) + .map(str::to_string) + }) +} + fn finalize_com_generation(output_dir: &Path) -> Result<(), String> { if !has_winrt_root(output_dir) { write_com_root_compatibility_barrels(output_dir)?; @@ -2989,6 +3038,74 @@ mod tests { )) } + #[test] + fn com_barrel_deduplicates_only_identical_pod_factories() { + let descriptor = + "const _nativeLayout_RECT = '{\"name\":\"Windows.Win32.Foundation.RECT\"}';"; + let mut modules = BTreeMap::from([ + ( + "IFirst".into(), + BTreeSet::from(["IFirst".into(), "createRECT".into()]), + ), + ( + "ISecond".into(), + BTreeSet::from(["ISecond".into(), "createRECT".into()]), + ), + ]); + let contents = BTreeMap::from([ + ( + "IFirst".into(), + format!( + "{descriptor}\nexports.IFirst = IFirst;\nexports.createRECT = createRECT;\n" + ), + ), + ( + "ISecond".into(), + format!( + "{descriptor}\nexports.ISecond = ISecond;\nexports.createRECT = createRECT;\n" + ), + ), + ]); + + deduplicate_com_barrel_exports(&mut modules, &contents).unwrap(); + assert!(modules["IFirst"].contains("createRECT")); + assert!(!modules["ISecond"].contains("createRECT")); + + let mut conflicting_modules = modules.clone(); + conflicting_modules + .get_mut("ISecond") + .unwrap() + .insert("createRECT".into()); + let mut conflicting_contents = contents; + conflicting_contents.insert( + "ISecond".into(), + "const _nativeLayout_RECT = 'different';\nexports.createRECT = createRECT;\n".into(), + ); + assert!( + deduplicate_com_barrel_exports(&mut conflicting_modules, &conflicting_contents) + .is_err() + ); + + let union_descriptor = "const _nativeUnionLayout_VALUE = '{\"name\":\"Contoso.VALUE\"}';"; + let mut union_modules = BTreeMap::from([ + ("IFirst".into(), BTreeSet::from(["createVALUE".into()])), + ("ISecond".into(), BTreeSet::from(["createVALUE".into()])), + ]); + let union_contents = BTreeMap::from([ + ( + "IFirst".into(), + format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), + ), + ( + "ISecond".into(), + format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), + ), + ]); + deduplicate_com_barrel_exports(&mut union_modules, &union_contents).unwrap(); + assert!(union_modules["IFirst"].contains("createVALUE")); + assert!(!union_modules["ISecond"].contains("createVALUE")); + } + #[test] fn distinct_classes_with_the_same_short_name_are_rejected() { let classes = vec![ diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts index ae963063..cafe9f88 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.d.ts @@ -1,16 +1,17 @@ // Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; import type { DynWinRtValue } from '@microsoft/dynwinrt/com'; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HWND = bigint | number; -export declare const IID_IDataTransferManagerInterop: unknown; +export declare const IID_IDataTransferManagerInterop: WinGuid; export declare class IDataTransferManagerInterop { static readonly IID: typeof IID_IDataTransferManagerInterop; protected constructor(obj: unknown); /** Activate the projected WinRT class and QI to the interop. - * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */ + * `initializeCom()` must be called once (e.g. at process startup) before this is used. */ static create(): IDataTransferManagerInterop; /** Wrap an existing native COM pointer (for QueryInterface bridging). */ static _fromNative(obj: unknown): IDataTransferManagerInterop; diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js index 2cdb160b..47627523 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, DynWinRtValue, WinGuid } = require('@microsoft/dynwinrt/com'); +const { DynCom, DynComMethodSig, DynWinRtValue, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); const IID_IDataTransferManagerInterop = WinGuid.parse('3a3dcd6c-3eab-43dc-bcde-45671ce800c8'); const IID_DataTransferManager_default = WinGuid.parse('a5caee9b-8708-49d1-8d36-67d25a8da00c'); @@ -25,7 +25,7 @@ class IDataTransferManagerInterop { this._obj.release(); } /** Create a new `IDataTransferManagerInterop` by activating the `Windows.ApplicationModel.DataTransfer.DataTransferManager` factory and QI'ing to the interop. - * `DynCom.initialize()` must be called once (e.g. at process startup) before this is used. */ + * `initializeCom()` must be called once (e.g. at process startup) before this is used. */ static create() { const factory = DynWinRtValue.activationFactory('Windows.ApplicationModel.DataTransfer.DataTransferManager'); const _obj = factory.cast(IID_IDataTransferManagerInterop); diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts new file mode 100644 index 00000000..7760e1da --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts @@ -0,0 +1,61 @@ +// Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; +import { SHOW_WINDOW_CMD } from './SHOW_WINDOW_CMD.js'; +import type { DynWinRtValue } from '@microsoft/dynwinrt/com'; +import type { DynComNativeStruct } from '@microsoft/dynwinrt/com'; + +/** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ +export type HWND = bigint | number; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`. */ +export type PWSTR = string | Buffer | Uint8Array | bigint; + +/** Validated native POD bytes (Windows.Win32.Storage.FileSystem-specific size selected at runtime). */ +export type WIN32_FIND_DATAW = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.Storage.FileSystem.WIN32_FIND_DATAW' }; +export declare function createWIN32_FIND_DATAW(bytes?: Buffer): WIN32_FIND_DATAW; + +export declare const IID_IShellLinkW: WinGuid; + +export declare class IShellLinkW { + static readonly IID: typeof IID_IShellLinkW; + protected constructor(obj: unknown); + /** Wrap an existing native COM pointer (for QueryInterface bridging). */ + static _fromNative(obj: unknown): IShellLinkW; + /** Release the underlying native COM reference. Safe to call more than once. */ + release(): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getpath} */ + getPath(cch: number, pfd: WIN32_FIND_DATAW | null, fFlags: number): [string, WIN32_FIND_DATAW | null]; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getidlist} */ + getIDList(): DynWinRtValue; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setidlist} */ + setIDList(pidl: bigint | Buffer): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription} */ + getDescription(cch?: number): string; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setdescription} */ + setDescription(name: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getworkingdirectory} */ + getWorkingDirectory(cch?: number): string; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setworkingdirectory} */ + setWorkingDirectory(dir: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getarguments} */ + getArguments(cch?: number): string; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setarguments} */ + setArguments(args: PWSTR): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-gethotkey} */ + getHotkey(): number; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-sethotkey} */ + setHotkey(wHotkey: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getshowcmd} */ + getShowCmd(): SHOW_WINDOW_CMD; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setshowcmd} */ + setShowCmd(iShowCmd: SHOW_WINDOW_CMD): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-geticonlocation} */ + getIconLocation(cch?: number): [string, number]; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-seticonlocation} */ + setIconLocation(iconPath: PWSTR, iIcon: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setrelativepath} */ + setRelativePath(pathRel: PWSTR, reserved: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-resolve} */ + resolve(hwnd: HWND | Buffer | Uint8Array, fFlags: number): void; + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setpath} */ + setPath(file: PWSTR): void; +} diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js new file mode 100644 index 00000000..2649e29b --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js @@ -0,0 +1,154 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); +const { SHOW_WINDOW_CMD } = require('./SHOW_WINDOW_CMD.js'); + +const _nativeLayout_WIN32_FIND_DATAW = '{"name":"Windows.Win32.Storage.FileSystem.WIN32_FIND_DATAW","x86":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"x64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"arm64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]}}'; +function createWIN32_FIND_DATAW(bytes) { return DynCom.createNativeStruct(_nativeLayout_WIN32_FIND_DATAW, bytes); } + +function _normalizeStringBufferCount(value, name) { + if (!Number.isInteger(value) || value <= 0) throw new TypeError(`${name} must be a positive integer`); + return value; +} +function _decodeWideString(buffer) { + let end = 0; + while (end + 1 < buffer.length && buffer.readUInt16LE(end) !== 0) end += 2; + return buffer.subarray(0, end).toString('utf16le'); +} + +const IID_IShellLinkW = WinGuid.parse('000214f9-0000-0000-c000-000000000046'); + +let _IShellLinkWCache; +const _IShellLinkW = new Proxy({}, { + get(_target, prop) { + _IShellLinkWCache ??= DynCom.registerIUnknownInterface('Windows.Win32.UI.Shell.IShellLinkW', IID_IShellLinkW) + .addMethodAt(3, 'GetPath', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type()).addInOut(DynCom.nativeStructPointerType(_nativeLayout_WIN32_FIND_DATAW, true)).addIn(DynCom.u32Type())) + .addMethodAt(4, 'GetIDList', new DynComMethodSig().addOut(DynCom.coTaskMemPointerType())) + .addMethodAt(5, 'SetIDList', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(6, 'GetDescription', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(7, 'SetDescription', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(8, 'GetWorkingDirectory', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(9, 'SetWorkingDirectory', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(10, 'GetArguments', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(11, 'SetArguments', new DynComMethodSig().addIn(DynCom.pointerType())) + .addMethodAt(12, 'GetHotkey', new DynComMethodSig().addOut(DynCom.u16Type())) + .addMethodAt(13, 'SetHotkey', new DynComMethodSig().addIn(DynCom.u16Type())) + .addMethodAt(14, 'GetShowCmd', new DynComMethodSig().addOut(DynCom.i32Type())) + .addMethodAt(15, 'SetShowCmd', new DynComMethodSig().addIn(DynCom.i32Type())) + .addMethodAt(16, 'GetIconLocation', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type()).addOut(DynCom.i32Type())) + .addMethodAt(17, 'SetIconLocation', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())) + .addMethodAt(18, 'SetRelativePath', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) + .addMethodAt(19, 'Resolve', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) + .addMethodAt(20, 'SetPath', new DynComMethodSig().addIn(DynCom.pointerType())); + const value = _IShellLinkWCache[prop]; + return typeof value === 'function' ? value.bind(_IShellLinkWCache) : value; + }, +}); + +class IShellLinkW { + static IID = IID_IShellLinkW; + _obj; + constructor(obj) { this._obj = obj; } + static _fromNative(obj) { return Object.assign(Object.create(IShellLinkW.prototype), { _obj: obj }); } + /** Release the underlying native COM reference. Safe to call more than once. */ + release() { + this._obj.release(); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getpath} */ + getPath(cch, pfd, fFlags) { + cch = _normalizeStringBufferCount(cch, 'cch'); + const _buffer = Buffer.alloc(cch * 2); + const _out = _IShellLinkW.method(3).invoke(this._obj, [DynCom.pointer(_buffer), DynCom.i32(cch), pfd === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_WIN32_FIND_DATAW, pfd), DynCom.u32(fFlags)]); + const _text = _decodeWideString(_buffer); + return [_text, ((value) => DynCom.isNullNativeStructPointer(value) ? null : DynCom.nativeStructBytes(_nativeLayout_WIN32_FIND_DATAW, value))(_out)]; + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getidlist} */ + getIDList() { + const _out = _IShellLinkW.method(4).invoke(this._obj, []); + return DynCom.adoptCoTaskMemPointer(_out); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setidlist} */ + setIDList(pidl) { + _IShellLinkW.method(5).invoke(this._obj, [DynCom.pointer(pidl)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription} */ + getDescription(cch = 260) { + cch = _normalizeStringBufferCount(cch, 'cch'); + const _buffer = Buffer.alloc(cch * 2); + _IShellLinkW.method(6).invoke(this._obj, [DynCom.pointer(_buffer), DynCom.i32(cch)]); + const _text = _decodeWideString(_buffer); + return _text; + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setdescription} */ + setDescription(name) { + _IShellLinkW.method(7).invoke(this._obj, [DynCom.wideStringPointer(name)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getworkingdirectory} */ + getWorkingDirectory(cch = 260) { + cch = _normalizeStringBufferCount(cch, 'cch'); + const _buffer = Buffer.alloc(cch * 2); + _IShellLinkW.method(8).invoke(this._obj, [DynCom.pointer(_buffer), DynCom.i32(cch)]); + const _text = _decodeWideString(_buffer); + return _text; + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setworkingdirectory} */ + setWorkingDirectory(dir) { + _IShellLinkW.method(9).invoke(this._obj, [DynCom.wideStringPointer(dir)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getarguments} */ + getArguments(cch = 260) { + cch = _normalizeStringBufferCount(cch, 'cch'); + const _buffer = Buffer.alloc(cch * 2); + _IShellLinkW.method(10).invoke(this._obj, [DynCom.pointer(_buffer), DynCom.i32(cch)]); + const _text = _decodeWideString(_buffer); + return _text; + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setarguments} */ + setArguments(args) { + _IShellLinkW.method(11).invoke(this._obj, [DynCom.wideStringPointer(args)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-gethotkey} */ + getHotkey() { + const _out = _IShellLinkW.method(12).invoke(this._obj, []); + return DynCom.toNumber(_out); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-sethotkey} */ + setHotkey(wHotkey) { + _IShellLinkW.method(13).invoke(this._obj, [DynCom.u16(wHotkey)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getshowcmd} */ + getShowCmd() { + const _out = _IShellLinkW.method(14).invoke(this._obj, []); + return DynCom.toNumber(_out); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setshowcmd} */ + setShowCmd(iShowCmd) { + _IShellLinkW.method(15).invoke(this._obj, [DynCom.i32(iShowCmd)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-geticonlocation} */ + getIconLocation(cch = 260) { + cch = _normalizeStringBufferCount(cch, 'cch'); + const _buffer = Buffer.alloc(cch * 2); + const _out = _IShellLinkW.method(16).invoke(this._obj, [DynCom.pointer(_buffer), DynCom.i32(cch)]); + const _text = _decodeWideString(_buffer); + return [_text, DynCom.toNumber(_out)]; + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-seticonlocation} */ + setIconLocation(iconPath, iIcon) { + _IShellLinkW.method(17).invoke(this._obj, [DynCom.wideStringPointer(iconPath), DynCom.i32(iIcon)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setrelativepath} */ + setRelativePath(pathRel, reserved) { + _IShellLinkW.method(18).invoke(this._obj, [DynCom.wideStringPointer(pathRel), DynCom.u32(reserved)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-resolve} */ + resolve(hwnd, fFlags) { + _IShellLinkW.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(fFlags)]); + } + /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-setpath} */ + setPath(file) { + _IShellLinkW.method(20).invoke(this._obj, [DynCom.wideStringPointer(file)]); + } +} +exports.createWIN32_FIND_DATAW = createWIN32_FIND_DATAW; +exports.IID_IShellLinkW = IID_IShellLinkW; +exports.IShellLinkW = IShellLinkW; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts index 3194de17..1270d6de 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.d.ts @@ -1,9 +1,10 @@ // Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HWND = bigint | number; -export declare const IID_ITaskbarList: unknown; +export declare const IID_ITaskbarList: WinGuid; export declare class ITaskbarList { static readonly IID: typeof IID_ITaskbarList; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js index 8ee04d3e..79dab23d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); const IID_ITaskbarList = WinGuid.parse('56fdf342-fd6d-11d0-958a-006097c9a090'); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts index d971c8a8..9d9d9901 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.d.ts @@ -1,9 +1,10 @@ // Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HWND = bigint | number; -export declare const IID_ITaskbarList2: unknown; +export declare const IID_ITaskbarList2: WinGuid; export declare class ITaskbarList2 { static readonly IID: typeof IID_ITaskbarList2; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js index 42beba4f..0bf652d5 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); const IID_ITaskbarList2 = WinGuid.parse('602d4995-b13a-429b-a66e-1935e44f4317'); diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts index b089fbbf..27242455 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts @@ -1,5 +1,7 @@ // Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; import { TBPFLAG } from './TBPFLAG.js'; +import type { DynComNativeStruct, DynComNativeStructArray } from '@microsoft/dynwinrt/com'; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HICON = bigint | number; @@ -10,7 +12,16 @@ export type HWND = bigint | number; /** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`. */ export type PWSTR = string | Buffer | Uint8Array | bigint; -export declare const IID_ITaskbarList3: unknown; +/** Validated native POD bytes (Windows.Win32.Foundation-specific size selected at runtime). */ +export type RECT = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.Foundation.RECT' }; +export declare function createRECT(bytes?: Buffer): RECT; +/** Validated native POD bytes (Windows.Win32.UI.Shell-specific size selected at runtime). */ +export type THUMBBUTTON = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.UI.Shell.THUMBBUTTON' }; +export declare function createTHUMBBUTTON(bytes?: Buffer): THUMBBUTTON; +export type THUMBBUTTONArray = DynComNativeStructArray & { readonly __dynComNativeStructArrayLayout: 'Windows.Win32.UI.Shell.THUMBBUTTON' }; +export declare function createTHUMBBUTTONArray(bytes: Buffer): THUMBBUTTONArray; + +export declare const IID_ITaskbarList3: WinGuid; export declare class ITaskbarList3 { static readonly IID: typeof IID_ITaskbarList3; @@ -44,9 +55,9 @@ export declare class ITaskbarList3 { /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ setTabActive(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array, reserved: number): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ - thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, pButton: THUMBBUTTONArray): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ - thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, pButton: THUMBBUTTONArray): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd: HWND | Buffer | Uint8Array, himl: HIMAGELIST): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ @@ -54,5 +65,5 @@ export declare class ITaskbarList3 { /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ setThumbnailTooltip(hwnd: HWND | Buffer | Uint8Array, tip: PWSTR): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ - setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: bigint | Buffer): void; + setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: RECT | null): void; } diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js index 1970f747..c83841c8 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js @@ -1,7 +1,13 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); const { TBPFLAG } = require('./TBPFLAG.js'); +const _nativeLayout_RECT = '{"name":"Windows.Win32.Foundation.RECT","x86":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"x64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"arm64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]}}'; +function createRECT(bytes) { return DynCom.createNativeStruct(_nativeLayout_RECT, bytes); } +const _nativeLayout_THUMBBUTTON = '{"name":"Windows.Win32.UI.Shell.THUMBBUTTON","x86":{"size":540,"alignment":4,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":12,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":16,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":536,"count":1,"type":{"kind":"i32"}}]},"x64":{"size":552,"alignment":8,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":16,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":24,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":544,"count":1,"type":{"kind":"i32"}}]},"arm64":{"size":552,"alignment":8,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":16,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":24,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":544,"count":1,"type":{"kind":"i32"}}]}}'; +function createTHUMBBUTTON(bytes) { return DynCom.createNativeStruct(_nativeLayout_THUMBBUTTON, bytes); } +function createTHUMBBUTTONArray(bytes) { return DynCom.createNativeStructArray(_nativeLayout_THUMBBUTTON, bytes); } + const IID_ITaskbarList3 = WinGuid.parse('ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf'); let _ITaskbarList3Cache; @@ -20,12 +26,12 @@ const _ITaskbarList3 = new Proxy({}, { .addMethodAt(12, 'UnregisterTab', new DynComMethodSig().addIn(DynCom.pointerType())) .addMethodAt(13, 'SetTabOrder', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(14, 'SetTabActive', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) - .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) - .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addInputBuffer(DynCom.nativeStructType(_nativeLayout_THUMBBUTTON), 1, undefined, false)) + .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addInputBuffer(DynCom.nativeStructType(_nativeLayout_THUMBBUTTON), 1, undefined, false)) .addMethodAt(17, 'ThumbBarSetImageList', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(18, 'SetOverlayIcon', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(19, 'SetThumbnailTooltip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())); + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.nativeStructPointerType(_nativeLayout_RECT, true))); const value = _ITaskbarList3Cache[prop]; return typeof value === 'function' ? value.bind(_ITaskbarList3Cache) : value; }, @@ -89,12 +95,12 @@ class ITaskbarList3 { _ITaskbarList3.method(14).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi)), DynCom.u32(reserved)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ - thumbBarAddButtons(hwnd, cButtons, pButton) { - _ITaskbarList3.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + thumbBarAddButtons(hwnd, pButton) { + _ITaskbarList3.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.nativeStructBuffer(_nativeLayout_THUMBBUTTON, pButton)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ - thumbBarUpdateButtons(hwnd, cButtons, pButton) { - _ITaskbarList3.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + thumbBarUpdateButtons(hwnd, pButton) { + _ITaskbarList3.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.nativeStructBuffer(_nativeLayout_THUMBBUTTON, pButton)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd, himl) { @@ -110,8 +116,11 @@ class ITaskbarList3 { } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ setThumbnailClip(hwnd, prcClip) { - _ITaskbarList3.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(prcClip)]); + _ITaskbarList3.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), prcClip === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_RECT, prcClip)]); } } +exports.createRECT = createRECT; +exports.createTHUMBBUTTON = createTHUMBBUTTON; +exports.createTHUMBBUTTONArray = createTHUMBBUTTONArray; exports.IID_ITaskbarList3 = IID_ITaskbarList3; exports.ITaskbarList3 = ITaskbarList3; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts index b0ca74a4..1f54c959 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts @@ -1,6 +1,8 @@ // Generated by dynwinrt-codegen — do not edit +import type { WinGuid } from '@microsoft/dynwinrt/com'; import { TBPFLAG } from './TBPFLAG.js'; import { STPFLAG } from './STPFLAG.js'; +import type { DynComNativeStruct, DynComNativeStructArray } from '@microsoft/dynwinrt/com'; /** Opaque Win32 handle value. Pass a raw pointer value as a `bigint` (full pointer width) or `number` (safe integer). */ export type HICON = bigint | number; @@ -11,7 +13,16 @@ export type HWND = bigint | number; /** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically via DynCom.wideStringPointer), a `Buffer`/`Uint8Array` holding UTF-16LE bytes (including the NUL terminator), or a raw pointer as `bigint`. */ export type PWSTR = string | Buffer | Uint8Array | bigint; -export declare const IID_ITaskbarList4: unknown; +/** Validated native POD bytes (Windows.Win32.Foundation-specific size selected at runtime). */ +export type RECT = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.Foundation.RECT' }; +export declare function createRECT(bytes?: Buffer): RECT; +/** Validated native POD bytes (Windows.Win32.UI.Shell-specific size selected at runtime). */ +export type THUMBBUTTON = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.UI.Shell.THUMBBUTTON' }; +export declare function createTHUMBBUTTON(bytes?: Buffer): THUMBBUTTON; +export type THUMBBUTTONArray = DynComNativeStructArray & { readonly __dynComNativeStructArrayLayout: 'Windows.Win32.UI.Shell.THUMBBUTTON' }; +export declare function createTHUMBBUTTONArray(bytes: Buffer): THUMBBUTTONArray; + +export declare const IID_ITaskbarList4: WinGuid; export declare class ITaskbarList4 { static readonly IID: typeof IID_ITaskbarList4; @@ -45,9 +56,9 @@ export declare class ITaskbarList4 { /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-settabactive} */ setTabActive(tab: HWND | Buffer | Uint8Array, mdi: HWND | Buffer | Uint8Array, reserved: number): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ - thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + thumbBarAddButtons(hwnd: HWND | Buffer | Uint8Array, pButton: THUMBBUTTONArray): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ - thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, cButtons: number, pButton: bigint | Buffer): void; + thumbBarUpdateButtons(hwnd: HWND | Buffer | Uint8Array, pButton: THUMBBUTTONArray): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd: HWND | Buffer | Uint8Array, himl: HIMAGELIST): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setoverlayicon} */ @@ -55,7 +66,7 @@ export declare class ITaskbarList4 { /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailtooltip} */ setThumbnailTooltip(hwnd: HWND | Buffer | Uint8Array, tip: PWSTR): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ - setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: bigint | Buffer): void; + setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: RECT | null): void; /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist4-settabproperties} */ setTabProperties(tab: HWND | Buffer | Uint8Array, stpFlags: STPFLAG): void; } diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js index 344990d4..f053d074 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js @@ -1,8 +1,14 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com'); +const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); const { TBPFLAG } = require('./TBPFLAG.js'); const { STPFLAG } = require('./STPFLAG.js'); +const _nativeLayout_RECT = '{"name":"Windows.Win32.Foundation.RECT","x86":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"x64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]},"arm64":{"size":16,"alignment":4,"fields":[{"name":"left","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"top","offset":4,"count":1,"type":{"kind":"i32"}},{"name":"right","offset":8,"count":1,"type":{"kind":"i32"}},{"name":"bottom","offset":12,"count":1,"type":{"kind":"i32"}}]}}'; +function createRECT(bytes) { return DynCom.createNativeStruct(_nativeLayout_RECT, bytes); } +const _nativeLayout_THUMBBUTTON = '{"name":"Windows.Win32.UI.Shell.THUMBBUTTON","x86":{"size":540,"alignment":4,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":12,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":16,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":536,"count":1,"type":{"kind":"i32"}}]},"x64":{"size":552,"alignment":8,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":16,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":24,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":544,"count":1,"type":{"kind":"i32"}}]},"arm64":{"size":552,"alignment":8,"fields":[{"name":"dwMask","offset":0,"count":1,"type":{"kind":"i32"}},{"name":"iId","offset":4,"count":1,"type":{"kind":"u32"}},{"name":"iBitmap","offset":8,"count":1,"type":{"kind":"u32"}},{"name":"hIcon","offset":16,"count":1,"type":{"kind":"pointer"}},{"name":"szTip","offset":24,"count":260,"type":{"kind":"u16"}},{"name":"dwFlags","offset":544,"count":1,"type":{"kind":"i32"}}]}}'; +function createTHUMBBUTTON(bytes) { return DynCom.createNativeStruct(_nativeLayout_THUMBBUTTON, bytes); } +function createTHUMBBUTTONArray(bytes) { return DynCom.createNativeStructArray(_nativeLayout_THUMBBUTTON, bytes); } + const IID_ITaskbarList4 = WinGuid.parse('c43dc798-95d1-4bea-9030-bb99e2983a1a'); let _ITaskbarList4Cache; @@ -21,12 +27,12 @@ const _ITaskbarList4 = new Proxy({}, { .addMethodAt(12, 'UnregisterTab', new DynComMethodSig().addIn(DynCom.pointerType())) .addMethodAt(13, 'SetTabOrder', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(14, 'SetTabActive', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.u32Type())) - .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) - .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addIn(DynCom.pointerType())) + .addMethodAt(15, 'ThumbBarAddButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addInputBuffer(DynCom.nativeStructType(_nativeLayout_THUMBBUTTON), 1, undefined, false)) + .addMethodAt(16, 'ThumbBarUpdateButtons', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.u32Type()).addInputBuffer(DynCom.nativeStructType(_nativeLayout_THUMBBUTTON), 1, undefined, false)) .addMethodAt(17, 'ThumbBarSetImageList', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(18, 'SetOverlayIcon', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) .addMethodAt(19, 'SetThumbnailTooltip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) - .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.pointerType())) + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.nativeStructPointerType(_nativeLayout_RECT, true))) .addMethodAt(21, 'SetTabProperties', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type())); const value = _ITaskbarList4Cache[prop]; return typeof value === 'function' ? value.bind(_ITaskbarList4Cache) : value; @@ -91,12 +97,12 @@ class ITaskbarList4 { _ITaskbarList4.method(14).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.pointer(DynCom.handleValue(mdi)), DynCom.u32(reserved)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbaraddbuttons} */ - thumbBarAddButtons(hwnd, cButtons, pButton) { - _ITaskbarList4.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + thumbBarAddButtons(hwnd, pButton) { + _ITaskbarList4.method(15).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.nativeStructBuffer(_nativeLayout_THUMBBUTTON, pButton)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarupdatebuttons} */ - thumbBarUpdateButtons(hwnd, cButtons, pButton) { - _ITaskbarList4.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.u32(cButtons), DynCom.pointer(pButton)]); + thumbBarUpdateButtons(hwnd, pButton) { + _ITaskbarList4.method(16).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.nativeStructBuffer(_nativeLayout_THUMBBUTTON, pButton)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-thumbbarsetimagelist} */ thumbBarSetImageList(hwnd, himl) { @@ -112,12 +118,15 @@ class ITaskbarList4 { } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ setThumbnailClip(hwnd, prcClip) { - _ITaskbarList4.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(prcClip)]); + _ITaskbarList4.method(20).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), prcClip === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_RECT, prcClip)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist4-settabproperties} */ setTabProperties(tab, stpFlags) { _ITaskbarList4.method(21).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.i32(stpFlags)]); } } +exports.createRECT = createRECT; +exports.createTHUMBBUTTON = createTHUMBBUTTON; +exports.createTHUMBBUTTONArray = createTHUMBBUTTONArray; exports.IID_ITaskbarList4 = IID_ITaskbarList4; exports.ITaskbarList4 = ITaskbarList4; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js index 02128f7f..0bccfa46 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynCom } = require('@microsoft/dynwinrt/com'); +const { DynCom } = require('@microsoft/dynwinrt/com/unsafe'); const { ITaskbarList4, IID_ITaskbarList4 } = require('./ITaskbarList4.js'); const CLSID_TaskbarList = '56fdf344-fd6d-11d0-958a-006097c9a090'; diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 1c15a036..44cd0e87 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -19,6 +19,7 @@ use std::process::Command; use dynwinrt_codegen::codegen::com; use dynwinrt_codegen::codegen::project::{get_import_name, set_import_name}; use dynwinrt_codegen::com_metadata; +use dynwinrt_codegen::com_metadata::{RawNativeType, RawParamDirection}; use dynwinrt_codegen::meta; use dynwinrt_codegen::types::TypeMeta; @@ -34,6 +35,43 @@ fn win32_available() -> bool { Path::new(&win32_winmd()).exists() } +fn isolate_com_method( + interface: &com_metadata::ComInterfaceMeta, + method_name: &str, +) -> com_metadata::ComInterfaceMeta { + let raw_index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == method_name) + .unwrap(); + let method_index = interface + .interface + .methods + .iter() + .position(|method| method.name == method_name) + .unwrap(); + let mut isolated = interface.clone(); + isolated.raw_methods = Some(vec![ + isolated.raw_methods.as_ref().unwrap()[raw_index].clone(), + ]); + isolated.interface.methods = vec![isolated.interface.methods[method_index].clone()]; + isolated.own_methods_start = 0; + isolated +} + +fn project_isolated_com_method( + namespace: &str, + interface_name: &str, + method_name: &str, +) -> com::ComGeneratedOutput { + let interface = + com_metadata::parse_com_interface(&win32_winmd(), namespace, interface_name).unwrap(); + com::generate_com_interface_files(&isolate_com_method(&interface, method_name), &win32_winmd()) + .unwrap() +} + #[test] fn required_win32_metadata_is_present() { if std::env::var("DYNWINRT_REQUIRE_WIN32_METADATA").as_deref() == Ok("1") { @@ -45,1120 +83,3636 @@ fn required_win32_metadata_is_present() { } } -/// Returns a clone of `iface` with the named method removed. -/// -/// `IShellLinkW::GetPath` takes a caller-writable `WIN32_FIND_DATAW*` (`pfd`) -/// that has no safe layout/size projection (see the classic-COM-ABI skill's -/// fail-closed requirement for unsupported writable native structs), so the -/// whole interface now fails closed if it is included. Tests that only need -/// `IShellLinkW`'s *other* members use this helper to exercise them without -/// tripping that (separately, correctly, regression-tested) failure. -fn without_method( - mut iface: com_metadata::ComInterfaceMeta, - name: &str, -) -> com_metadata::ComInterfaceMeta { - iface.interface.methods.retain(|method| method.name != name); - iface -} +#[test] +fn real_metadata_preserves_automation_pointer_contracts_and_fails_closed() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } -/// Resolve a `Windows.winmd` from the newest installed Windows SDK, matching -/// the discovery logic the codegen itself uses. Returns `None` if no SDK is -/// installed on this machine (the test that calls this should skip in that -/// case, consistent with other tests in this module). -fn discovered_windows_winmd() -> Option { - com_metadata::discover_newest_windows_winmd() -} + let property_bag = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com.StructuredStorage", + "IPropertyBag", + ) + .expect("IPropertyBag must exist"); + let read = property_bag + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Read") + .unwrap(); + let variant = read + .params + .iter() + .find(|param| param.name == "pVar") + .unwrap(); + assert_eq!(variant.direction, RawParamDirection::InOut); + assert_eq!(variant.typ.pointer_depth, 1); + assert!(matches!( + &variant.typ.native_type, + RawNativeType::Named { namespace, name, .. } + if namespace == "Windows.Win32.System.Variant" && name == "VARIANT" + )); + let error = com::generate_com_interface_files(&property_bag, &win32_winmd()).unwrap_err(); + assert!(error.contains("Automation BYREF/InOut"), "{error}"); -fn run_codegen_command( - metadata: &str, - namespace: Option<&str>, - class_names: &str, - output_dir: &Path, -) { - let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); - command - .arg("generate") - .arg("--winmd") - .arg(metadata) - .arg("--class-name") - .arg(class_names) - .arg("--output") - .arg(output_dir); - if let Some(namespace) = namespace { - command.arg("--namespace").arg(namespace); - } + let property_store = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell.PropertiesSystem", + "IPropertyStore", + ) + .expect("IPropertyStore must exist"); + let get_value = property_store + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetValue") + .unwrap(); + let propvariant = get_value + .params + .iter() + .find(|param| param.name == "pv") + .unwrap(); + assert_eq!(propvariant.direction, RawParamDirection::Out); + assert_eq!(propvariant.typ.pointer_depth, 1); + assert!(matches!( + &propvariant.typ.native_type, + RawNativeType::Named { namespace, name, .. } + if namespace == "Windows.Win32.System.Com.StructuredStorage" + && name == "PROPVARIANT" + )); - let output = command.output().expect("spawn dynwinrt-codegen"); + let context = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Wmi", + "IWbemContext", + ) + .expect("IWbemContext must exist"); + let get_names = context + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetNames") + .unwrap(); + let safe_array = get_names + .params + .iter() + .find(|param| param.name == "pNames") + .unwrap(); + assert_eq!(safe_array.direction, RawParamDirection::Out); + assert_eq!(safe_array.typ.pointer_depth, 2); + assert!(matches!( + &safe_array.typ.native_type, + RawNativeType::Named { namespace, name, .. } + if namespace == "Windows.Win32.System.Com" && name == "SAFEARRAY" + )); + let raw_get_names = context + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetNames") + .unwrap(); + let projected_get_names = context + .interface + .methods + .iter() + .position(|method| method.name == "GetNames") + .unwrap(); + let mut isolated_get_names = context.clone(); + isolated_get_names.raw_methods = Some(vec![ + isolated_get_names.raw_methods.as_ref().unwrap()[raw_get_names].clone(), + ]); + isolated_get_names.interface.methods = + vec![isolated_get_names.interface.methods[projected_get_names].clone()]; + isolated_get_names.own_methods_start = 0; + let output = com::generate_com_interface_files(&isolated_get_names, &win32_winmd()) + .expect("documented IWbemContext.GetNames BSTR SAFEARRAY must project"); + assert!(output.js.contains("DynCom.safeArrayType('bstr')")); + isolated_get_names.raw_methods.as_mut().unwrap()[0] + .params + .iter_mut() + .find(|param| param.name == "pNames") + .unwrap() + .typ + .pointer_depth = 0; + let error = com::generate_com_interface_files(&isolated_get_names, &win32_winmd()) + .expect_err("bare SAFEARRAY output must fail closed"); assert!( - output.status.success(), - "generation failed:\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) + error.contains("SAFEARRAY signature no longer matches exact documented evidence"), + "{error}" + ); + isolated_get_names.raw_methods.as_mut().unwrap()[0] + .params + .iter_mut() + .find(|param| param.name == "pNames") + .unwrap() + .typ + .pointer_depth = 2; + isolated_get_names.raw_methods.as_mut().unwrap()[0].declaring_interface = + "INoSafeArrayEvidence".into(); + let error = com::generate_com_interface_files(&isolated_get_names, &win32_winmd()) + .expect_err("SAFEARRAY declaration identity drift must fail closed"); + assert!( + error.contains("SAFEARRAY evidence is no longer registered"), + "{error}" ); -} - -fn assert_mixed_package_shape(output_dir: &Path) { - assert!(output_dir.join("Uri.js").is_file()); - assert!(output_dir.join("com").join("ITaskbarList3.js").is_file()); - assert!(output_dir.join("com").join("package.json").is_file()); - - let root_index = fs::read_to_string(output_dir.join("index.d.ts")).unwrap(); - assert!(root_index.contains("Uri")); - assert!(!root_index.contains("ITaskbarList3")); - assert!(!root_index.contains("TBPFLAG")); - - let com_index = fs::read_to_string(output_dir.join("com").join("index.d.ts")).unwrap(); - assert!(com_index.contains("ITaskbarList3")); - assert!(com_index.contains("TBPFLAG")); - assert!(!com_index.contains("Uri")); - - let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); - assert!(package.contains("\"type\": \"commonjs\"")); - assert!(package.contains("\"./Uri\"")); - assert!(package.contains("\"./com\"")); - assert!(package.contains("\"./com/*\"")); - assert!(package.contains("\"types\": \"./com/*.d.ts\"")); - assert!(package.contains("\"import\": \"./com/*.js\"")); - assert!(package.contains("\"require\": \"./com/index.js\"")); - assert!(package.contains("\"require\": \"./com/*.js\"")); - let com_package = fs::read_to_string(output_dir.join("com").join("package.json")).unwrap(); - assert!(com_package.contains("\"type\": \"commonjs\"")); - assert!(output_dir.join("com").join("index.mjs").is_file()); + let type_comp = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "ITypeComp") + .expect("ITypeComp must exist"); + let bind = type_comp + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Bind") + .unwrap(); + let bind_ptr = bind + .params + .iter() + .find(|param| param.name == "pBindPtr") + .unwrap(); + assert_eq!(bind_ptr.direction, RawParamDirection::Out); + assert_eq!(bind_ptr.typ.pointer_depth, 1); + assert!(matches!( + &bind_ptr.typ.native_type, + RawNativeType::Named { + namespace, + name, + layout: Some(layout), + .. + } if namespace == "Windows.Win32.System.Com" + && name == "BINDPTR" + && layout.variants.iter().all(|variant| variant.is_union) + )); + let error = com::generate_com_interface_files(&type_comp, &win32_winmd()).unwrap_err(); + assert!( + error.contains("requires native layout projection"), + "{error}" + ); } -// ------------------------------------------------------------------------- -// NORMAL tests -// ------------------------------------------------------------------------- - -/// 1. Parse ITaskbarList3 from Win32 metadata → correct IID. #[test] -fn parse_itaskbarlist3_iid() { +fn real_metadata_projects_required_variant_by_value_inputs() { if !win32_available() { - eprintln!("Skipping: Win32 winmd not available at {}", &win32_winmd()); + eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( + + let accessible = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.UI.Accessibility", + "IAccessible", ) - .expect("ITaskbarList3 must exist in Win32 metadata"); - assert_eq!(com_iface.interface.name, "ITaskbarList3"); - assert_eq!(com_iface.interface.namespace, "Windows.Win32.UI.Shell"); + .expect("IAccessible must exist"); assert_eq!( - com_iface.interface.iid, - "ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf" + accessible.interface.iid, + "618736e0-3c3d-11cf-810c-00aa00389b71" ); -} + let acc_select = accessible + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "accSelect") + .unwrap(); + assert_eq!(acc_select.vtable_index, 21); + let child = acc_select + .params + .iter() + .find(|param| param.name == "varChild") + .unwrap(); + assert_eq!(child.direction, RawParamDirection::In); + assert!(!child.optional); + assert_eq!(child.typ.pointer_depth, 0); + assert!(matches!( + &child.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Variant" && name == "VARIANT" + )); -/// 2. Base-aware vtable slots: full interface_impls chain determines absolute slots. -/// ITaskbarList3 inherits: IUnknown (3 methods) + ITaskbarList (5) + ITaskbarList2 (1). -/// So HrInit = 3, SetProgressValue = 9, SetProgressState = 10. -#[test] -fn parse_itaskbarlist3_vtable_slots() { - if !win32_available() { - eprintln!("Skipping: Win32 winmd not available"); - return; - } - let com_iface = com_metadata::parse_com_interface( + let isolated_accessible = isolate_com_method(&accessible, "accSelect"); + let output = com::generate_com_interface_files(&isolated_accessible, &win32_winmd()) + .expect("IAccessible::accSelect by-value VARIANT must project"); + assert!(output.js.contains( + ".addMethodAt(21, 'accSelect', new DynComMethodSig().addIn(DynCom.i32Type()).addIn(DynCom.variantByValueType()))" + )); + assert!(output.js.contains("DynCom.variant(varChild)")); + assert!( + output + .dts + .contains("accSelect(flagsSelect: number, varChild: DynComVariant): void;") + ); + assert!(!output.dts.contains("varChild: DynComVariant | null")); + + let full_accessible = com::generate_com_interface_files(&accessible, &win32_winmd()) + .expect("complete IAccessible must project after by-value VARIANT support"); + assert!(full_accessible.js.contains(".addMethodAt(21, 'accSelect'")); + assert!( + full_accessible + .dts + .contains("get_accName(varChild: DynComVariant): string;") + ); + + let automation = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.UI.Accessibility", + "IUIAutomation", ) - .expect("ITaskbarList3 must exist"); + .expect("IUIAutomation must exist"); + assert_eq!( + automation.interface.iid, + "30cbe57d-d9d0-452a-ab13-7ac5ac4825ee" + ); + let create_property_condition = automation + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "CreatePropertyCondition") + .unwrap(); + assert_eq!(create_property_condition.vtable_index, 23); + let value = create_property_condition + .params + .iter() + .find(|param| param.name == "value") + .unwrap(); + assert_eq!(value.direction, RawParamDirection::In); + assert!(!value.optional); + assert_eq!(value.typ.pointer_depth, 0); + assert!(matches!( + &value.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.System.Variant" && name == "VARIANT" + )); - let by_name = |n: &str| -> usize { - com_iface - .interface - .methods - .iter() - .find(|m| m.name == n) - .unwrap_or_else(|| { - panic!( - "method {} not found (methods: {:?})", - n, - com_iface - .interface - .methods - .iter() - .map(|m| &m.name) - .collect::>() - ) - }) - .vtable_index - }; + let isolated_automation = isolate_com_method(&automation, "CreatePropertyCondition"); + let output = com::generate_com_interface_files(&isolated_automation, &win32_winmd()) + .expect("IUIAutomation::CreatePropertyCondition by-value VARIANT must project"); + assert!(output.js.contains( + ".addMethodAt(23, 'CreatePropertyCondition', new DynComMethodSig().addIn(DynCom.i32Type()).addIn(DynCom.variantByValueType()).addOut(DynCom.interfaceType(WinGuid.parse('352ffba8-0973-437c-a61f-f64cafd81df9'))))" + )); + assert!(output.js.contains("DynCom.variant(value)")); + assert!(output.dts.contains( + "createPropertyCondition(propertyId: UIA_PROPERTY_ID, value: DynComVariant): DynWinRtValue;" + )); - assert_eq!( - by_name("HrInit"), - 3, - "HrInit is the first ITaskbarList method after IUnknown" + let error = com::generate_com_interface_files(&automation, &win32_winmd()) + .expect_err("complete IUIAutomation must retain its next fail-closed blocker"); + assert!(error.contains("ElementFromPoint parameter `pt`"), "{error}"); + assert!(error.contains("native layout projection"), "{error}"); + + let mut optional = isolated_automation.clone(); + optional.raw_methods.as_mut().unwrap()[0] + .params + .iter_mut() + .find(|param| param.name == "value") + .unwrap() + .optional = true; + let error = com::generate_com_interface_files(&optional, &win32_winmd()) + .expect_err("optional aggregate VARIANT cannot fabricate null/default semantics"); + assert!( + error.contains( + "optional by-value VARIANT input has no proven native null/default semantics" + ), + "{error}" ); - assert_eq!(by_name("AddTab"), 4); - assert_eq!(by_name("DeleteTab"), 5); - assert_eq!(by_name("ActivateTab"), 6); - assert_eq!(by_name("SetActiveAlt"), 7); - assert_eq!( - by_name("MarkFullscreenWindow"), - 8, - "ITaskbarList2's only method" + + let mut wrong_direction = isolated_automation; + wrong_direction.raw_methods.as_mut().unwrap()[0] + .params + .iter_mut() + .find(|param| param.name == "value") + .unwrap() + .direction = RawParamDirection::Out; + let error = com::generate_com_interface_files(&wrong_direction, &win32_winmd()) + .expect_err("bare VARIANT output must require pointer metadata"); + assert!(error.contains("VARIANT"), "{error}"); + assert!( + error.contains("requires native layout projection"), + "{error}" ); - assert_eq!(by_name("SetProgressValue"), 9); - assert_eq!(by_name("SetProgressState"), 10); -} -/// 3. Base detection: ITaskbarList3 is IUnknown-rooted → base offset (first user -/// method slot) is 3, NOT 6. -#[test] -fn itaskbarlist3_is_iunknown_rooted() { - if !win32_available() { - eprintln!("Skipping: Win32 winmd not available"); - return; - } - let com_iface = com_metadata::parse_com_interface( + let property_bag = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.System.Com.StructuredStorage", + "IPropertyBag", ) - .unwrap(); - assert_eq!(com_iface.base_offset, 3); - assert!(com_iface.is_iunknown_rooted); - // Base chain should include ITaskbarList2, ITaskbarList (and stop at IUnknown) - let base_names: Vec<&str> = com_iface.base_chain.iter().map(|s| s.as_str()).collect(); - assert_eq!( - base_names, - ["ITaskbarList2", "ITaskbarList", "IUnknown"], - "base chain order matters" - ); + .expect("IPropertyBag must exist"); + let isolated_write = isolate_com_method(&property_bag, "Write"); + let pointer_variant = isolated_write.raw_methods.as_ref().unwrap()[0] + .params + .iter() + .find(|param| param.name == "pVar") + .unwrap(); + assert_eq!(pointer_variant.direction, RawParamDirection::In); + assert_eq!(pointer_variant.typ.pointer_depth, 1); + let output = com::generate_com_interface_files(&isolated_write, &win32_winmd()) + .expect("existing VARIANT pointer input must remain supported"); + assert!(output.js.contains(".addIn(DynCom.variantType())")); + assert!(!output.js.contains("variantByValueType")); } -/// 4. CLSID resolution: ITaskbarList3 → TaskbarList coclass → CLSID -/// 56fdf344-fd6d-11d0-958a-006097c9a090 #[test] -fn itaskbarlist3_clsid_resolution() { +fn real_metadata_projects_exact_documented_safearray_families() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .unwrap(); - assert_eq!( - com_iface.coclass_clsid.as_deref(), - Some("56fdf344-fd6d-11d0-958a-006097c9a090") + + for (namespace, interface, method, expected_abi) in [ + ( + "Windows.Win32.UI.Accessibility", + "IAccessibleEx", + "GetRuntimeId", + "DynCom.safeArrayType('i32')", + ), + ( + "Windows.Win32.UI.Accessibility", + "IUIAutomationProxyFactoryEntry", + "SetWinEventsForAutomationEvent", + "DynCom.safeArrayType('u32')", + ), + ( + "Windows.Win32.UI.Accessibility", + "ITextRangeProvider", + "GetBoundingRectangles", + "DynCom.safeArrayType('f64')", + ), + ( + "Windows.Win32.Media.DirectShow", + "IESEvent", + "GetData", + "DynCom.safeArrayType('u8')", + ), + ( + "Windows.Win32.System.Wmi", + "IWbemContext", + "GetNames", + "DynCom.safeArrayType('bstr')", + ), + ( + "Windows.Win32.System.Performance", + "IPerformanceCounterDataCollector", + "get_PerformanceCounters", + "DynCom.safeArrayType('bstr')", + ), + ( + "Windows.Win32.System.Performance", + "ITraceDataProvider", + "get_FilterData", + "DynCom.safeArrayType('u8')", + ), + ( + "Windows.Win32.System.RemoteDesktop", + "IWorkspaceResTypeRegistry", + "GetRegisteredFileExtensions", + "DynCom.safeArrayType('bstr')", + ), + ( + "Windows.Win32.System.WindowsProgramming", + "ICameraUIControl", + "GetSelectedItems", + "DynCom.safeArrayType('bstr')", + ), + ( + "Windows.Win32.Storage.FileServerResourceManager", + "IFsrmActionReport", + "get_ReportTypes", + "DynCom.safeArrayType('variant')", + ), + ( + "Windows.Win32.UI.Accessibility", + "ITextProvider", + "GetVisibleRanges", + "DynCom.safeArrayType('unknown', WinGuid.parse('5347ad7b-c355-46f8-aff5-909033582f63'))", + ), + ( + "Windows.Win32.UI.Accessibility", + "IUIAutomationClientInfoSource", + "GetConnectedClients", + "DynCom.safeArrayType('unknown', WinGuid.parse('b2e8a3f1-4c5d-4e7a-8f6b-3d2e1c9a0b8f'))", + ), + ] { + let output = project_isolated_com_method(namespace, interface, method); + assert!(output.js.contains(expected_abi), "{interface}.{method}"); + assert!( + output.dts.contains("DynComSafeArray"), + "{interface}.{method}" + ); + } + + for interface in [ + "IAlertDataCollector", + "IApiTracingDataCollector", + "IConfigurationDataCollector", + "IDataCollectorSet", + "IPerformanceCounterDataCollector", + "ITraceDataProvider", + ] { + let parsed = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Performance", + interface, + ) + .unwrap(); + com::generate_com_interface_files(&parsed, &win32_winmd()) + .unwrap_or_else(|error| panic!("{interface} must project completely: {error}")); + } + + let client_info = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Accessibility", + "IUIAutomationClientInfo", + ) + .unwrap(); + assert_eq!( + client_info.interface.iid, + "b2e8a3f1-4c5d-4e7a-8f6b-3d2e1c9a0b8f" ); - assert_eq!(com_iface.coclass_name.as_deref(), Some("TaskbarList")); } #[test] -fn taskbarlist_coclass_selects_unique_most_derived_interface() { +fn text_provider_selection_preserves_its_documented_nullable_safearray() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let coclass = - com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") - .unwrap() - .expect("TaskbarList must be recognized as a COM coclass"); - assert_eq!(coclass.clsid, "56fdf344-fd6d-11d0-958a-006097c9a090"); - assert_eq!(coclass.primary_interface.interface.name, "ITaskbarList4"); - assert_eq!( - coclass - .associated_interfaces - .iter() - .map(|interface| interface.interface.name.as_str()) - .collect::>(), - [ - "ITaskbarList", - "ITaskbarList2", - "ITaskbarList3", - "ITaskbarList4" - ] + let output = project_isolated_com_method( + "Windows.Win32.UI.Accessibility", + "ITextProvider", + "GetSelection", + ); + assert!(output.js.contains( + "DynCom.safeArrayType('unknown', WinGuid.parse('5347ad7b-c355-46f8-aff5-909033582f63'), true)" + )); + assert!(output.js.contains("DynCom.takeNullableSafeArray(")); + assert!( + output + .dts + .contains("getSelection(): DynComSafeArray | null;") ); } #[test] -fn taskbarlist_coclass_generates_newable_class_and_interface_views() { +fn fragment_embedded_roots_preserve_their_documented_nullable_safearray() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let coclass = - com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") - .unwrap() - .unwrap(); - let out = com::generate_com_coclass_files(&coclass, &win32_winmd()).unwrap(); - assert!(out.js.contains("class TaskbarList extends ITaskbarList4")); - assert!(out.js.contains("exports.TaskbarList = TaskbarList;")); + let output = project_isolated_com_method( + "Windows.Win32.UI.Accessibility", + "IRawElementProviderFragment", + "GetEmbeddedFragmentRoots", + ); + assert!(output.js.contains( + "DynCom.safeArrayType('unknown', WinGuid.parse('620ce2a5-ab8f-40a9-86cb-de3c75599b58'), true)" + )); + assert!(output.js.contains("DynCom.takeNullableSafeArray(")); assert!( - out.js - .contains("super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4))") + output + .dts + .contains("getEmbeddedFragmentRoots(): DynComSafeArray | null;") ); - assert!(out.js.contains("as(InterfaceClass)")); - assert!(out.js.contains("DynCom.tryCast")); - assert!(out.dts.contains("constructor();")); - for interface in [ - "ITaskbarList.js", - "ITaskbarList2.js", - "ITaskbarList3.js", - "ITaskbarList4.js", + + let grabbed = project_isolated_com_method( + "Windows.Win32.UI.Accessibility", + "IDragProvider", + "GetGrabbedItems", + ); + assert!(grabbed.js.contains( + "DynCom.safeArrayType('unknown', WinGuid.parse('d6dd68d1-86fd-4332-8666-9abedea2d24c'), true)" + )); + assert!(grabbed.js.contains("DynCom.takeNullableSafeArray(")); + assert!( + grabbed + .dts + .contains("getGrabbedItems(): DynComSafeArray | null;") + ); + + let runtime_id = project_isolated_com_method( + "Windows.Win32.UI.Accessibility", + "IRawElementProviderFragment", + "GetRuntimeId", + ); + assert!( + runtime_id + .js + .contains("DynCom.safeArrayType('i32', undefined, true)") + ); + assert!(runtime_id.js.contains("DynCom.takeNullableSafeArray(")); + assert!( + runtime_id + .dts + .contains("getRuntimeId(): DynComSafeArray | null;") + ); + + let hosting = project_isolated_com_method( + "Windows.Win32.UI.Accessibility", + "IAccessibleHostingElementProviders", + "GetEmbeddedFragmentRoots", + ); + assert!(hosting.js.contains( + "DynCom.safeArrayType('unknown', WinGuid.parse('620ce2a5-ab8f-40a9-86cb-de3c75599b58'))" + )); + assert!(!hosting.js.contains("DynCom.takeNullableSafeArray(")); + assert!( + hosting + .dts + .contains("getEmbeddedFragmentRoots(): DynComSafeArray;") + ); + + let fragment = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Accessibility", + "IRawElementProviderFragment", + ) + .unwrap(); + let mut drifted = isolate_com_method(&fragment, "GetEmbeddedFragmentRoots"); + drifted.raw_methods.as_mut().unwrap()[0].params[0].name = "changed".into(); + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("nullable SAFEARRAY signature drift must fail closed"); + assert!( + error.contains("SAFEARRAY signature no longer matches exact documented evidence"), + "{error}" + ); +} + +#[test] +fn nearest_unproven_safearray_shapes_remain_fail_closed() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + for (namespace, interface, method) in [ + ( + "Windows.Win32.UI.TabletPC", + "ITextInputPanelEventSink", + "TextInserting", + ), + ( + "Windows.Win32.UI.Input.Ime", + "IImePlugInDictDictionaryList", + "GetDictionariesInUse", + ), + ( + "Windows.Win32.Networking.WinHttp", + "IWinHttpRequestEvents", + "OnResponseDataAvailable", + ), + ( + "Windows.Win32.System.ComponentServices", + "ICOMAdminCatalog", + "GetCollectionByQuery", + ), + ( + "Windows.Win32.System.TaskScheduler", + "IEmailAction", + "get_Attachments", + ), + ( + "Windows.Win32.UI.Xaml.Diagnostics", + "IVisualTreeService", + "GetEnums", + ), ] { + let parsed = + com_metadata::parse_com_interface(&win32_winmd(), namespace, interface).unwrap(); + let error = + com::generate_com_interface_files(&isolate_com_method(&parsed, method), &win32_winmd()) + .expect_err("unproven SAFEARRAY shape must fail closed"); assert!( - out.extra_files.iter().any(|(name, _)| name == interface), - "missing {interface}" + error.contains("SAFEARRAY") || error.contains("safe array"), + "{interface}.{method}: {error}" ); } } -/// 5. Param type mapping: HWND → pointer/handle, TBPFLAG → enum, HRESULT → void. #[test] -fn param_type_mapping() { +fn real_metadata_projects_complete_idispatch_with_automation_compounds() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let dispatch = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IDispatch") + .expect("IDispatch must exist"); + let raw_index = dispatch + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetIDsOfNames") + .unwrap(); + let compatibility_index = dispatch + .interface + .methods + .iter() + .position(|method| method.name == "GetIDsOfNames") + .unwrap(); + let raw = &dispatch.raw_methods.as_ref().unwrap()[raw_index]; + let names = &raw.params[1]; + assert_eq!(names.direction, RawParamDirection::In); + assert_eq!(names.typ.pointer_depth, 1); + assert_eq!( + names.native_array.as_ref().unwrap().count_param_index, + Some(2) + ); + assert!(matches!( + names.string_pointer_array.as_ref(), + Some(com_metadata::RawStringPointerArray { + encoding: com_metadata::RawStringEncoding::Utf16, + pointer_depth: 1, + ownership: com_metadata::RawElementOwnership::Borrowed, + .. + }) + )); + let outputs = &raw.params[4]; + assert_eq!(outputs.direction, RawParamDirection::Out); + assert_eq!(outputs.typ.pointer_depth, 1); + assert_eq!( + outputs.native_array.as_ref().unwrap().count_param_index, + Some(2) + ); + + let mut isolated = dispatch.clone(); + isolated.raw_methods = Some(vec![ + isolated.raw_methods.as_ref().unwrap()[raw_index].clone(), + ]); + isolated.interface.methods = vec![isolated.interface.methods[compatibility_index].clone()]; + isolated.own_methods_start = 0; + let output = com::generate_com_interface_files(&isolated, &win32_winmd()) + .expect("IDispatch::GetIDsOfNames must project in isolation"); + assert!(output.js.contains(".addInputStringArray(true, 2)")); + assert!( + output + .js + .contains(".addCallerOutputBuffer(DynCom.i32Type(), 2, undefined, false, false)") + ); + assert!(output.js.contains("DynCom.wideStringArray(")); + assert!(output.js.contains("DynCom.callerOutputArray(")); + assert!(output.js.contains("DynCom.takeI32Array(")); + assert_eq!(output.js.matches(".invoke(").count(), 1); + assert!(!output.js.contains("Buffer.alloc")); + assert!(output.dts.contains("rgszNames: string[]")); + assert!(output.dts.contains("): number[];")); + assert!(!output.dts.contains("cNames:")); + assert!(!output.dts.contains("rgDispId:")); + + let invoke = dispatch + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Invoke") + .unwrap(); + assert_eq!(invoke.params.len(), 8); + assert!( + invoke.params[5..] + .iter() + .all(|param| { param.direction == RawParamDirection::Out && param.optional }) + ); + + let output = com::generate_com_interface_files(&dispatch, &win32_winmd()) + .expect("complete inherited IDispatch must project"); + assert!(output.js.contains(".addMethodAt(3, 'GetTypeInfoCount'")); + assert!(output.js.contains(".addMethodAt(4, 'GetTypeInfo'")); + assert!(output.js.contains(".addMethodAt(5, 'GetIDsOfNames'")); + assert!(output.js.contains(".addMethodAt(6, 'Invoke'")); + assert!(output.js.contains(".addIn(DynCom.dispatchParamsType())")); + assert!(output.js.contains(".addOptionalOut(DynCom.variantType())")); + assert!( + output + .js + .contains(".addOptionalOut(DynCom.excepInfoType())") + ); + assert!(output.js.contains(".addOptionalOut(DynCom.u32Type())")); + assert!(output.js.contains(".captureDispatchInvokeHresult()")); + assert!(output.js.contains("DynCom.dispatchParams(dispParams)")); + assert!(output.js.contains(".invokeDispatch(this._obj")); + assert!(output.js.contains("DynCom.takeVariant(_resultValue)")); + assert!(output.js.contains("DynCom.takeExcepInfo(_excepInfoValue)")); + assert!(output.js.contains("_error.hresult = _call.hresult")); + assert!(output.js.contains("_error.excepInfo = _excepInfo")); + assert!(output.js.contains("_error.argErr = _call.argErr")); + assert!(output.js.contains("_error.cause = new Error")); + assert!( + output + .js + .contains("_description ? `: ${_description}` : ''") + ); + assert!(output.js.contains("options.result ?? true")); + assert!(output.js.contains("options.excepInfo ?? true")); + assert!(output.js.contains("options.argErr ?? true")); + assert!(!output.js.contains("_result.excepInfo")); + assert!(!output.js.contains("_result.argErr")); + assert!(!output.js.contains("nativeStructType")); + assert!(output.dts.contains( + "invoke(dispIdMember: number, riid: bigint | Buffer, lcid: number, wFlags: DISPATCH_FLAGS, dispParams: DynComDispatchParams, options?: { result?: boolean; excepInfo?: boolean; argErr?: boolean }): { result?: DynComVariant };" + )); + + let invoke_raw_index = dispatch + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "Invoke") + .unwrap(); + let mut invalid_dispatch_output = dispatch.clone(); + invalid_dispatch_output.raw_methods.as_mut().unwrap()[invoke_raw_index].params[4].direction = + RawParamDirection::Out; + let error = com::generate_com_interface_files(&invalid_dispatch_output, &win32_winmd()) + .expect_err("DISPPARAMS output must fail closed"); + assert!( + error.contains("DISPPARAMS") || error.contains("input-only"), + "{error}" + ); + + let mut invalid_excep_input = dispatch.clone(); + invalid_excep_input.raw_methods.as_mut().unwrap()[invoke_raw_index].params[6].direction = + RawParamDirection::In; + invalid_excep_input.raw_methods.as_mut().unwrap()[invoke_raw_index].params[6].optional = false; + let error = com::generate_com_interface_files(&invalid_excep_input, &win32_winmd()) + .expect_err("EXCEPINFO input must fail closed"); + assert!( + error.contains("EXCEPINFO") || error.contains("output-only"), + "{error}" + ); + + let mut invalid_dispatch_indirection = dispatch; + invalid_dispatch_indirection.raw_methods.as_mut().unwrap()[invoke_raw_index].params[4] + .typ + .pointer_depth = 2; + let error = com::generate_com_interface_files(&invalid_dispatch_indirection, &win32_winmd()) + .expect_err("nested DISPPARAMS pointer indirection must fail closed"); + assert!( + error.contains("Invoke") || error.contains("DISPPARAMS"), + "{error}" + ); +} + +/// Resolve a `Windows.winmd` from the newest installed Windows SDK, matching +/// the discovery logic the codegen itself uses. Returns `None` if no SDK is +/// installed on this machine (the test that calls this should skip in that +/// case, consistent with other tests in this module). +fn discovered_windows_winmd() -> Option { + com_metadata::discover_newest_windows_winmd() +} + +fn run_codegen_command( + metadata: &str, + namespace: Option<&str>, + class_names: &str, + output_dir: &Path, +) { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .arg("generate") + .arg("--winmd") + .arg(metadata) + .arg("--class-name") + .arg(class_names) + .arg("--output") + .arg(output_dir); + if let Some(namespace) = namespace { + command.arg("--namespace").arg(namespace); + } + + let output = command.output().expect("spawn dynwinrt-codegen"); + assert!( + output.status.success(), + "generation failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn assert_mixed_package_shape(output_dir: &Path) { + assert!(output_dir.join("Uri.js").is_file()); + assert!(output_dir.join("com").join("ITaskbarList3.js").is_file()); + assert!(output_dir.join("com").join("package.json").is_file()); + + let root_index = fs::read_to_string(output_dir.join("index.d.ts")).unwrap(); + assert!(root_index.contains("Uri")); + assert!(!root_index.contains("ITaskbarList3")); + assert!(!root_index.contains("TBPFLAG")); + + let com_index = fs::read_to_string(output_dir.join("com").join("index.d.ts")).unwrap(); + assert!(com_index.contains("ITaskbarList3")); + assert!(com_index.contains("TBPFLAG")); + assert!(!com_index.contains("Uri")); + + let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); + assert!(package.contains("\"type\": \"commonjs\"")); + assert!(package.contains("\"./Uri\"")); + assert!(package.contains("\"./com\"")); + assert!(package.contains("\"./com/*\"")); + assert!(package.contains("\"types\": \"./com/*.d.ts\"")); + assert!(package.contains("\"import\": \"./com/*.js\"")); + assert!(package.contains("\"require\": \"./com/index.js\"")); + assert!(package.contains("\"require\": \"./com/*.js\"")); + + let com_package = fs::read_to_string(output_dir.join("com").join("package.json")).unwrap(); + assert!(com_package.contains("\"type\": \"commonjs\"")); + assert!(output_dir.join("com").join("index.mjs").is_file()); +} + +// ------------------------------------------------------------------------- +// NORMAL tests +// ------------------------------------------------------------------------- + +/// 1. Parse ITaskbarList3 from Win32 metadata → correct IID. +#[test] +fn parse_itaskbarlist3_iid() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available at {}", &win32_winmd()); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .expect("ITaskbarList3 must exist in Win32 metadata"); + assert_eq!(com_iface.interface.name, "ITaskbarList3"); + assert_eq!(com_iface.interface.namespace, "Windows.Win32.UI.Shell"); + assert_eq!( + com_iface.interface.iid, + "ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf" + ); +} + +/// 2. Base-aware vtable slots: full interface_impls chain determines absolute slots. +/// ITaskbarList3 inherits: IUnknown (3 methods) + ITaskbarList (5) + ITaskbarList2 (1). +/// So HrInit = 3, SetProgressValue = 9, SetProgressState = 10. +#[test] +fn parse_itaskbarlist3_vtable_slots() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .expect("ITaskbarList3 must exist"); + + let by_name = |n: &str| -> usize { + com_iface + .interface + .methods + .iter() + .find(|m| m.name == n) + .unwrap_or_else(|| { + panic!( + "method {} not found (methods: {:?})", + n, + com_iface + .interface + .methods + .iter() + .map(|m| &m.name) + .collect::>() + ) + }) + .vtable_index + }; + + assert_eq!( + by_name("HrInit"), + 3, + "HrInit is the first ITaskbarList method after IUnknown" + ); + assert_eq!(by_name("AddTab"), 4); + assert_eq!(by_name("DeleteTab"), 5); + assert_eq!(by_name("ActivateTab"), 6); + assert_eq!(by_name("SetActiveAlt"), 7); + assert_eq!( + by_name("MarkFullscreenWindow"), + 8, + "ITaskbarList2's only method" + ); + assert_eq!(by_name("SetProgressValue"), 9); + assert_eq!(by_name("SetProgressState"), 10); +} + +/// 3. Base detection: ITaskbarList3 is IUnknown-rooted → base offset (first user +/// method slot) is 3, NOT 6. +#[test] +fn itaskbarlist3_is_iunknown_rooted() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + assert_eq!(com_iface.base_offset, 3); + assert!(com_iface.is_iunknown_rooted); + // Base chain should include ITaskbarList2, ITaskbarList (and stop at IUnknown) + let base_names: Vec<&str> = com_iface.base_chain.iter().map(|s| s.as_str()).collect(); + assert_eq!( + base_names, + ["ITaskbarList2", "ITaskbarList", "IUnknown"], + "base chain order matters" + ); +} + +/// 4. CLSID resolution: ITaskbarList3 → TaskbarList coclass → CLSID +/// 56fdf344-fd6d-11d0-958a-006097c9a090 +#[test] +fn itaskbarlist3_clsid_resolution() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + assert_eq!( + com_iface.coclass_clsid.as_deref(), + Some("56fdf344-fd6d-11d0-958a-006097c9a090") + ); + assert_eq!(com_iface.coclass_name.as_deref(), Some("TaskbarList")); +} + +#[test] +fn taskbarlist_coclass_selects_unique_most_derived_interface() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .expect("TaskbarList must be recognized as a COM coclass"); + + assert_eq!(coclass.clsid, "56fdf344-fd6d-11d0-958a-006097c9a090"); + assert_eq!(coclass.primary_interface.interface.name, "ITaskbarList4"); + assert_eq!( + coclass + .associated_interfaces + .iter() + .map(|interface| interface.interface.name.as_str()) + .collect::>(), + [ + "ITaskbarList", + "ITaskbarList2", + "ITaskbarList3", + "ITaskbarList4" + ] + ); +} + +#[test] +fn taskbarlist_coclass_generates_newable_class_and_interface_views() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .unwrap(); + let out = com::generate_com_coclass_files(&coclass, &win32_winmd()).unwrap(); + + assert!(out.js.contains("class TaskbarList extends ITaskbarList4")); + assert!(out.js.contains("exports.TaskbarList = TaskbarList;")); + assert!( + out.js + .contains("super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4))") + ); + assert!(out.js.contains("as(InterfaceClass)")); + assert!(out.js.contains("DynCom.tryCast")); + assert!(out.dts.contains("constructor();")); + for interface in [ + "ITaskbarList.js", + "ITaskbarList2.js", + "ITaskbarList3.js", + "ITaskbarList4.js", + ] { + assert!( + out.extra_files.iter().any(|(name, _)| name == interface), + "missing {interface}" + ); + } +} + +/// 5. Param type mapping: HWND → pointer/handle, TBPFLAG → enum, HRESULT → void. +#[test] +fn param_type_mapping() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + + // Generate wrapper as a text bundle we can inspect for the mapping decisions + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + + let dts = out.dts.as_str(); + let js = out.js.as_str(); + + // HWND inputs accept Electron's pointer-width Buffer through the centralized + // runtime conversion, while the HWND value alias remains numeric. + assert!( + dts.contains("export type HWND = bigint | number;"), + "HWND value aliases should remain numeric in .d.ts, got:\n{}", + dts + ); + assert!( + dts.contains("hwnd: HWND | Buffer | Uint8Array") + && js.contains("DynCom.pointer(DynCom.handleValue(hwnd))") + && !js.contains("function _handleArg("), + "HWND inputs must use centralized DynCom.handleValue in .js, got:\n{}", + js + ); + + // ULONGLONG (U64) → bigint + // setProgressValue's completed/total params are U64 + assert!( + dts.contains("bigint"), + "U64 params should surface as bigint" + ); + + // TBPFLAG enum → surfaced by name (either an enum decl or a union) + assert!( + dts.contains("TBPFLAG") || dts.contains("TbpFlag"), + ".d.ts must reference the TBPFLAG enum:\n{}", + dts + ); + + // HRESULT-returning methods project to `void` (throw on failure); no HRESULT surface + assert!( + !dts.contains(": HRESULT") + && !dts.contains("-> HRESULT") + && !dts.contains("Promise"), + "HRESULT must not leak into the .d.ts surface:\n{}", + dts + ); + + // JS body: the SetProgressState signature must include u32 (TBPFLAG's underlying) for the enum arg + // Look for slot 10 invocation: + assert!( + js.contains("method(10)"), + ".js must call vtable slot 10 for SetProgressState" + ); + assert!( + js.contains("method(9)"), + ".js must call vtable slot 9 for SetProgressValue" + ); +} + +#[test] +fn shelllink_scalar_out_pointers_preserve_pointee_types() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") + .unwrap(); + + let get_show_cmd = interface + .interface + .methods + .iter() + .find(|method| method.name == "GetShowCmd") + .unwrap(); + assert!(matches!( + &get_show_cmd.params[0].typ, + TypeMeta::Enum { underlying, .. } if matches!(**underlying, TypeMeta::I32) + )); + let get_hotkey = interface + .interface + .methods + .iter() + .find(|method| method.name == "GetHotkey") + .unwrap(); + assert!(matches!(get_hotkey.params[0].typ, TypeMeta::U16)); + let get_icon_location = interface + .interface + .methods + .iter() + .find(|method| method.name == "GetIconLocation") + .unwrap(); + assert!(matches!(get_icon_location.params[2].typ, TypeMeta::I32)); + let get_hotkey_vtable = get_hotkey.vtable_index; + let get_show_cmd_vtable = get_show_cmd.vtable_index; + + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + assert!(output.js.contains(&format!( + ".addMethodAt({get_hotkey_vtable}, 'GetHotkey', new DynComMethodSig().addOut(DynCom.u16Type()))" + ))); + assert!(output.js.contains(&format!( + ".addMethodAt({get_show_cmd_vtable}, 'GetShowCmd', new DynComMethodSig().addOut(DynCom.i32Type()))" + ))); + assert!( + output + .dts + .contains("getIconLocation(cch?: number): [string, number];") + ); +} + +#[test] +fn nullable_native_pod_pointer_preserves_null_projection() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + + assert!( + output + .dts + .contains("setThumbnailClip(hwnd: HWND | Buffer | Uint8Array, prcClip: RECT | null)") + ); + assert!( + output + .js + .contains("DynCom.nativeStructPointerType(_nativeLayout_RECT, true)") + ); + assert!( + output + .js + .contains("prcClip === null ? DynCom.nullNativeStructPointer()") + ); +} + +/// 6. Partial generation: generating a single class-name yields ONLY that +/// interface plus its immediate deps (enum, coclass metadata), NOT the +/// entire Windows.Win32.UI.Shell namespace. +#[test] +fn partial_generation_only_emits_target_interface() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + + // Expected files: ITaskbarList3.js, ITaskbarList3.d.ts, TBPFLAG.js, TBPFLAG.d.ts + let file_names: Vec<&str> = out.extra_files.iter().map(|(n, _)| n.as_str()).collect(); + + // Should NOT include unrelated Shell types like IShellItem or IApplicationActivationManager + assert!( + !file_names.iter().any(|n| n.starts_with("IShellItem")), + "Partial generation must not include IShellItem: {:?}", + file_names + ); + assert!( + !file_names + .iter() + .any(|n| n.starts_with("IApplicationActivationManager")), + "Partial generation must not include unrelated types: {:?}", + file_names + ); + + // Should include TBPFLAG (a direct dep) + let has_tbpflag = file_names.iter().any(|n| n.starts_with("TBPFLAG")); + assert!( + has_tbpflag, + "TBPFLAG (direct enum dep) must be included: {:?}", + file_names + ); +} + +/// 7. Generated `.d.ts` has PascalCase type + camelCase methods and +/// no raw IID/vtable-index/CoCreateInstance leaked into the TYPED surface. +#[test] +fn dts_surface_is_natural_and_clean() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let dts = out.dts.as_str(); + + // PascalCase class name + assert!( + dts.contains("class ITaskbarList3"), + ".d.ts must export class ITaskbarList3, got:\n{}", + dts + ); + + // camelCase methods + for cc in &["hrInit", "setProgressValue", "setProgressState", "addTab"] { + assert!( + dts.contains(cc), + ".d.ts must declare camelCase method `{}`, got:\n{}", + cc, + dts + ); + } + // No PascalCase leaked method names + for pc in &[ + "HrInit(", + "SetProgressValue(", + "SetProgressState(", + "AddTab(", + ] { + assert!( + !dts.contains(pc), + ".d.ts must not expose PascalCase method `{}`, got:\n{}", + pc, + dts + ); + } + + // No raw IID leak in .d.ts + assert!( + !dts.contains("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"), + "raw IID must not leak into .d.ts:\n{}", + dts + ); + // No raw CLSID leak + assert!( + !dts.contains("56fdf344-fd6d-11d0-958a-006097c9a090"), + "raw CLSID must not leak into .d.ts:\n{}", + dts + ); + // No CoCreateInstance leak + assert!( + !dts.contains("CoCreateInstance") && !dts.contains("coCreateInstance"), + "CoCreateInstance must not leak into .d.ts:\n{}", + dts + ); + // No vtable index leak in .d.ts + for slot in &["method(3)", "method(9)", "method(10)", "vtable"] { + assert!( + !dts.contains(slot), + "vtable detail `{}` must not appear in .d.ts:\n{}", + slot, + dts + ); + } +} + +/// 8. Generated interface `.js` contains only IID/vtable behavior; activation +/// is emitted by the separate coclass wrapper. +#[test] +fn js_body_uses_cocreateinstance_and_correct_slots() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + + // Only the IID appears in the interface wrapper. + assert!(!js.contains("56fdf344-fd6d-11d0-958a-006097c9a090")); + assert!( + js.contains("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"), + ".js must embed the IID:\n{}", + js + ); + + assert!(!js.contains("coCreateInstance")); + + // Classic COM registration is kept out of the WinRT type namespace. + assert!( + js.contains("DynCom.registerIUnknownInterface"), + ".js must use DynCom registration for classic COM:\n{}", + js + ); + assert!(js.contains("Windows.Win32.UI.Shell.ITaskbarList3")); + + // Base-aware slots + assert!(js.contains("method(3)"), "HrInit slot 3"); + assert!(js.contains("method(9)"), "SetProgressValue slot 9"); + assert!(js.contains("method(10)"), "SetProgressState slot 10"); + + // Should NOT contain WinRT `.method(6)` for a user method (that would be + // the IInspectable-rooted slot for the first user method). + // HrInit at slot 6 would be the failing case — we accept `method(6)` only + // if that's ActivateTab (slot 6). ActivateTab IS at 6, so it's a valid + // occurrence. Just check the file doesn't say something like `HrInit ... method(6)`. + // This is covered by the exact per-method assertion above. +} + +/// Requirement 4 (acronym casing): `ITaskbarList3::SetTabActive(HWND hwndTab, +/// HWND hwndMDI, DWORD dwReserved)` must project `hwndMDI` as `mdi` (the +/// whole `MDI` acronym lowercased), not the naive first-letter-only `mDI`. +#[test] +fn taskbarlist3_settabactive_projects_hwndmdi_as_mdi_not_mdi_mixed_case() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + assert!( + js.contains("setTabActive(tab, mdi, reserved)"), + ".js must lowercase the whole `MDI` acronym in `hwndMDI` -> `mdi`, not `mDI`:\n{}", + js + ); + assert!( + !js.contains("mDI"), + ".js must not contain the naive-lowering artifact `mDI`:\n{}", + js + ); + let dts = out.dts.as_str(); + assert!( + dts.contains("mdi:"), + ".d.ts must also project the parameter as `mdi`:\n{}", + dts + ); +} + +/// Lifecycle ergonomics + doc rendering on a generated interface wrapper. +/// Activation lives on the separately generated coclass; the interface must +/// expose `release()`, a protected constructor/IID descriptor for generated +/// coclass inheritance and `as()`, and — since win32metadata attaches a +/// `DocumentationAttribute` (a `learn.microsoft.com` URL) to most methods — +/// an `@see` JSDoc comment referencing that URL. +#[test] +fn taskbarlist3_generated_output_has_lifecycle_members_and_doc_links() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + let dts = out.dts.as_str(); + + assert!( + js.contains("release()") && js.contains("this._obj.release();"), + ".js must expose release() delegating to the managed native value:\n{}", + js + ); + assert!( + dts.contains("release(): void;"), + ".d.ts must declare release(): void;:\n{}", + dts + ); + assert!( + dts.contains("protected constructor(obj: unknown);") + && dts.contains("static readonly IID:"), + ".d.ts must expose only the generated-coclass/interface-view construction surface:\n{}", + dts + ); + assert!( + js.contains("@see {@link https://learn.microsoft.com/"), + ".js must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", + js + ); + assert!( + dts.contains("@see {@link https://learn.microsoft.com/"), + ".d.ts must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", + dts + ); +} + +// ------------------------------------------------------------------------- +// CORNER tests +// ------------------------------------------------------------------------- + +/// 9. Regression: WinRT-style (IInspectable-based) interfaces still compute +/// base offset 6 (i.e. the existing WinRT path is unaffected). +#[test] +fn winrt_interfaces_still_use_offset_6() { + // Parse a well-known WinRT interface (Windows.Foundation.IUriRuntimeClass or similar) + // via the existing WinRT path — its first method should still have vtable_index = 6. + let Some(windows_winmd) = discovered_windows_winmd() else { + eprintln!( + "Skipping winrt_interfaces_still_use_offset_6: no Windows SDK Windows.winmd discoverable" + ); + return; + }; + // Take Windows.Foundation.Uri's default interface — pick one that has methods. + let class = meta::parse_class(&windows_winmd, "Windows.Foundation", "Uri") + .expect("Windows.Foundation.Uri must be present"); + let default_iface = class + .default_interface + .as_ref() + .expect("Uri must have a default interface"); + + // Its first method's vtable_index must still be 6 (unchanged from existing + // WinRT behavior); classic-COM support must not regress this. + let first_slot = default_iface + .methods + .first() + .map(|m| m.vtable_index) + .expect("Uri default interface must have methods"); + assert_eq!( + first_slot, 6, + "WinRT interfaces retain the IInspectable base offset of 6" + ); +} + +/// 10. Interface-not-found is a clean Option::None, not a panic. +#[test] +fn interface_not_found_is_clean_none() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let missing = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "IDoesNotExist_XYZ", + ); + assert!(missing.is_none()); +} + +/// 11. QI-only interface (no coclass) → wrapper emitted WITHOUT `create()`, +/// only a static from-raw / QI entry point. +#[test] +fn qi_only_interface_has_no_create() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + // IPersist is IUnknown-rooted (has 1 own method: GetClassID) and has NO + // "Persist" coclass anywhere in the metadata — verified via probe. + let com_iface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IPersist") + .expect("IPersist must exist in Win32 metadata"); + assert!( + com_iface.coclass_clsid.is_none(), + "IPersist has no associated coclass CLSID" + ); + let get_class_id = com_iface + .interface + .methods + .iter() + .find(|method| method.name == "GetClassID") + .unwrap(); + assert!(matches!(get_class_id.params[0].typ, TypeMeta::Guid)); + + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface"); + let js = out.js.as_str(); + let dts = out.dts.as_str(); + assert!(js.contains(".addOut(DynCom.guidType())")); + + // No `create()` in either surface + assert!( + !dts.contains("static create()") && !dts.contains("static create(): "), + "QI-only interface must not expose static create() in .d.ts:\n{}", + dts + ); + assert!( + !js.contains("coCreateInstance"), + "QI-only interface must not call coCreateInstance in .js:\n{}", + js + ); + + // Must still have a fromNative / QI-only entry + assert!( + js.contains("_fromNative") || js.contains("fromRaw"), + "QI-only interface must expose a from-raw entry:\n{}", + js + ); + + // Slot 3 for GetClassID (only method, IUnknown-rooted) + assert!( + js.contains("method(3)"), + "IPersist.GetClassID must invoke slot 3:\n{}", + js + ); +} + +/// 12. Determinism: regenerating ITaskbarList3 twice produces byte-identical output. +#[test] +fn generation_is_deterministic() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let a = { + let com = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + com::generate_com_interface_files(&com, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface") + }; + let b = { + let com = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + com::generate_com_interface_files(&com, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface") + }; + assert_eq!(a.js, b.js); + assert_eq!(a.dts, b.dts); + assert_eq!(a.extra_files, b.extra_files); +} + +// ------------------------------------------------------------------------- +// SNAPSHOT test +// ------------------------------------------------------------------------- + +/// Snapshot test: lock generated TaskbarList coclass and interface files. +/// +/// To update snapshots after an intentional change: +/// cargo run -p dynwinrt-codegen -- generate \ +/// --winmd C:\s\win32metadata\Windows.Win32.winmd \ +/// --namespace Windows.Win32.UI.Shell \ +/// --class-name TaskbarList \ +/// --output tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3 +#[test] +fn snapshot_itaskbarlist3() { + if !win32_available() { + eprintln!("Skipping snapshot test: Win32 winmd not available"); + return; + } + let coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .expect("TaskbarList must exist"); + let out = com::generate_com_coclass_files(&coclass, &win32_winmd()) + .expect("codegen must succeed for TaskbarList"); + + let snapshot_dir: PathBuf = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/itaskbarlist3"); + assert!( + snapshot_dir.exists(), + "Snapshot directory not found: {}", + snapshot_dir.display() + ); + + let mut generated: Vec<(String, String)> = Vec::new(); + generated.push(("TaskbarList.js".into(), out.js.clone())); + generated.push(("TaskbarList.d.ts".into(), out.dts.clone())); + for (name, content) in &out.extra_files { + generated.push((name.clone(), content.clone())); + } + + let mut mismatches = Vec::new(); + for (name, actual) in &generated { + let path = snapshot_dir.join(name); + if !path.exists() { + mismatches.push(format!(" missing snapshot: {}", name)); + continue; + } + let expected = fs::read_to_string(&path).unwrap(); + if actual.trim_end() != expected.trim_end() { + mismatches.push(format!(" differs: {}", name)); + } + } + + // Any extra snapshot file not produced by the generator is also a mismatch. + if let Ok(entries) = fs::read_dir(&snapshot_dir) { + let names: std::collections::HashSet = + generated.iter().map(|(n, _)| n.clone()).collect(); + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if !names.contains(&name) { + mismatches.push(format!(" extra snapshot not generated: {}", name)); + } + } + } + + if !mismatches.is_empty() { + panic!( + "ITaskbarList3 snapshot mismatch!\n{}\n\n\ + To update, re-run the generator or copy the actual output into the snapshot dir.", + mismatches.join("\n") + ); + } +} + +#[test] +fn snapshot_ishelllinkw_native_pod() { + if !win32_available() { + eprintln!("Skipping snapshot test: Win32 winmd not available"); + return; + } + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") + .expect("IShellLinkW must exist"); + let out = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect("codegen must succeed for IShellLinkW"); + let snapshot_dir: PathBuf = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/ishelllinkw"); + + for (name, actual) in [("IShellLinkW.js", out.js), ("IShellLinkW.d.ts", out.dts)] { + let path = snapshot_dir.join(name); + let expected = fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display())); + assert_eq!( + actual.trim_end(), + expected.trim_end(), + "{name} native POD snapshot changed" + ); + } +} + +// ------------------------------------------------------------------------- +// --import-name honored by classic-COM path +// ------------------------------------------------------------------------- + +/// Regression test for a bug where the classic-COM generator hardcoded the +/// runtime import as `'@microsoft/dynwinrt'`, ignoring the `--import-name` +/// CLI flag (which the WinRT path already honored via +/// `codegen::project::set_import_name`). Fixing this makes it possible to +/// regenerate the Node E2E wrappers from `Windows.Win32.winmd` without +/// hand-patching the import line. +/// +/// The test uses the same thread-local as `set_import_name`, so it +/// save/restores the default around the assertion to avoid contaminating +/// other tests that assume the `@microsoft/dynwinrt` default (notably the +/// snapshot tests). `#[serial]` is intentionally NOT used — because +/// `RUNTIME_IMPORT_NAME` is a `thread_local!`, cargo's parallel test runner +/// gives each thread its own copy; restoring on the same thread is enough. +#[test] +fn import_name_flag_is_honored_by_com_path() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let previous = get_import_name(); + set_import_name("../dist/com-unsafe.js"); + + let result = std::panic::catch_unwind(|| { + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .expect("ITaskbarList3 must exist"); + com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface") + }); + + // Always restore before propagating any assertion failure. + set_import_name(&previous); + + let out = result.unwrap_or_else(|e| std::panic::resume_unwind(e)); + + // Custom import must appear on the runtime import line... + assert!( + out.js.contains("require('../dist/com-unsafe.js')"), + "classic-COM .js must honor --import-name (expected `require('../dist/com-unsafe.js')`):\n{}", + out.js + ); + // ...and the hardcoded default must NOT be present in the generated body. + assert!( + !out.js.contains("'@microsoft/dynwinrt'"), + "classic-COM .js must NOT hardcode '@microsoft/dynwinrt' when --import-name is set:\n{}", + out.js + ); + + // Sanity: after restoring the default, subsequent generation reverts. + let default_out = { + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .expect("ITaskbarList3 must exist"); + com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interface") + }; + assert!( + default_out + .js + .contains("require('@microsoft/dynwinrt/com/unsafe')"), + "after restoring, default import must use '@microsoft/dynwinrt/com/unsafe':\n{}", + default_out.js + ); +} + +/// Same test for the interop bridge generation path. +#[test] +fn import_name_flag_is_honored_by_interop_wrapper() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + if discovered_windows_winmd().is_none() { + eprintln!( + "Skipping: no Windows SDK Windows.winmd discoverable (needed for interop resolution)" + ); + return; + } + + let previous = get_import_name(); + set_import_name("../dist/com-unsafe.js"); + + let result = std::panic::catch_unwind(|| { + let com_iface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "IDataTransferManagerInterop", + ) + .expect("IDataTransferManagerInterop must exist"); + com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for classic-COM interop interface") + }); + + set_import_name(&previous); + let out = result.unwrap_or_else(|e| std::panic::resume_unwind(e)); + + // The interop .js itself must honor the flag. + assert!( + out.js.contains("require('../dist/com-unsafe.js')"), + "interop .js must honor --import-name:\n{}", + out.js + ); + assert!( + !out.js.contains("'@microsoft/dynwinrt'"), + "interop .js must NOT hardcode '@microsoft/dynwinrt':\n{}", + out.js + ); + + assert!( + out.dts.contains("from '../dist/com.js'"), + "interop .d.ts must honor --import-name:\n{}", + out.dts + ); + assert!( + !out.extra_files + .iter() + .any(|(name, _)| name.starts_with("DataTransferManager.")), + "COM codegen must not emit a projected WinRT companion" + ); +} + +#[test] +fn shellitem_getdisplayname_is_not_classified_as_caller_owned_string_buffer() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let com_iface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellItem") + .expect("IShellItem must exist"); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for IShellItem"); + + assert!( + out.js.contains(".addOut(DynCom.coTaskMemPointerType())") + && out.js.contains( + "'GetDisplayName', new DynComMethodSig().addIn(DynCom.i32Type()).addOut(DynCom.coTaskMemPointerType())" + ), + "PWSTR* callee-allocated output must be registered as an owned CoTaskMem output, not the unclassified pointer type:\n{}", + out.js + ); + assert!( + !out.js.contains("getDisplayName(sigdnName = 260)") + && !out.js.contains("_decodeWideString"), + "IShellItem.GetDisplayName must not allocate/decode a caller-owned buffer:\n{}", + out.js + ); +} + +#[test] +fn u16_input_param_uses_existing_u16_value_ctor_not_u16value() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + // IShellLinkW.SetHotkey takes a [in] u16 (WORD). The classic-COM value + // ctor is DynCom.u16(...) — there is no `u16Value`/`i16Value`. Regression + // guard: the arg-wrapper must emit the ctor that actually exists, or the + // generated call throws at runtime. + let com_iface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") + .expect("IShellLinkW must exist"); + let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) + .expect("codegen must succeed for IShellLinkW"); + + assert!( + out.js.contains("DynCom.u16(wHotkey)"), + "u16 input param must wrap via the existing DynCom.u16(...):\n{}", + out.js + ); + assert!( + !out.js.contains("u16Value(") && !out.js.contains("i16Value("), + "codegen must not emit non-existent u16Value/i16Value ctor:\n{}", + out.js + ); +} + +#[test] +fn sid_buffers_keep_data_pointer_address_semantics() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let mut interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Storage.FileSystem", + "IDiskQuotaControl", + ) + .expect("IDiskQuotaControl must exist"); + interface + .interface + .methods + .retain(|method| method.name == "AddUserSid"); + interface + .raw_methods + .as_mut() + .unwrap() + .retain(|method| method.projected_name == "AddUserSid"); + let output = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect("isolated IDiskQuotaControl.AddUserSid generation should succeed"); + + assert!( + output + .dts + .contains("addUserSid(pUserSid: PSID | Buffer | Uint8Array"), + "PSID input must accept backing storage rather than handle bytes:\n{}", + output.dts + ); + assert!( + output.js.contains("DynCom.pointer(pUserSid)") + && !output.js.contains("handleValue(pUserSid)"), + "PSID Buffer must pass its address, not decoded contents:\n{}", + output.js + ); +} + +#[test] +fn typed_counted_buffers_generate_from_real_win32_contracts() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( + + let stream = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.System.Com", + "ISequentialStream", ) - .unwrap(); - - // Generate wrapper as a text bundle we can inspect for the mapping decisions - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - - let dts = out.dts.as_str(); - let js = out.js.as_str(); - - // HWND inputs accept Electron's pointer-width Buffer through the centralized - // runtime conversion, while the HWND value alias remains numeric. - assert!( - dts.contains("export type HWND = bigint | number;"), - "HWND value aliases should remain numeric in .d.ts, got:\n{}", - dts - ); - assert!( - dts.contains("hwnd: HWND | Buffer | Uint8Array") - && js.contains("DynCom.pointer(DynCom.handleValue(hwnd))") - && !js.contains("function _handleArg("), - "HWND inputs must use centralized DynCom.handleValue in .js, got:\n{}", - js - ); - - // ULONGLONG (U64) → bigint - // setProgressValue's completed/total params are U64 + .expect("ISequentialStream must exist"); + let output = com::generate_com_interface_files(&stream, &win32_winmd()) + .expect("documented ISequentialStream buffer overrides must project"); assert!( - dts.contains("bigint"), - "U64 params should surface as bigint" + output + .js + .contains(".addCallerOutputBuffer(DynCom.u8Type(), 1, 2, true, false)") + && output + .js + .contains(".addInputBuffer(DynCom.u8Type(), 1, 2, true)"), + "stream signatures must preserve byte capacity and actual-length relationships:\n{}", + output.js ); - - // TBPFLAG enum → surfaced by name (either an enum decl or a union) assert!( - dts.contains("TBPFLAG") || dts.contains("TbpFlag"), - ".d.ts must reference the TBPFLAG enum:\n{}", - dts + output.js.contains("read(pv)") + && output.js.contains("write(pv)") + && !output.js.contains("read(pv, cb") + && !output.js.contains("write(pv, cb"), + "derived byte counts must be hidden from the JS surface:\n{}", + output.js ); - - // HRESULT-returning methods project to `void` (throw on failure); no HRESULT surface assert!( - !dts.contains(": HRESULT") - && !dts.contains("-> HRESULT") - && !dts.contains("Promise"), - "HRESULT must not leak into the .d.ts surface:\n{}", - dts + output + .dts + .contains("read(pv: Buffer | ArrayBufferView): [number, Buffer]") + && output + .dts + .contains("write(pv: Buffer | ArrayBufferView): [number, number]"), + "stream buffers must use natural typed-buffer declarations:\n{}", + output.dts ); - // JS body: the SetProgressState signature must include u32 (TBPFLAG's underlying) for the enum arg - // Look for slot 10 invocation: - assert!( - js.contains("method(10)"), - ".js must call vtable slot 10 for SetProgressState" - ); + let opc = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Storage.Packaging.Opc", + "IOpcSignatureCustomObject", + ) + .expect("IOpcSignatureCustomObject must exist"); + let output = com::generate_com_interface_files(&opc, &win32_winmd()) + .expect("documented CoTaskMem byte output must project"); assert!( - js.contains("method(9)"), - ".js must call vtable slot 9 for SetProgressValue" + output + .js + .contains(".addCoTaskMemOutputBuffer(DynCom.u8Type(), 1, true)") + && output.js.contains("return DynCom.takeBuffer(_out)") + && output.dts.contains("getXml(): Buffer"), + "callee-allocated bytes must carry their exact allocator into generated code:\n{}", + output.js ); } #[test] -fn shelllink_scalar_out_pointers_preserve_pointee_types() { +fn recorder_two_call_buffer_uses_bounded_exact_projection() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let interface = - com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") - .unwrap(); - let get_show_cmd = interface - .interface - .methods - .iter() - .find(|method| method.name == "GetShowCmd") - .unwrap(); - assert!(matches!( - &get_show_cmd.params[0].typ, - TypeMeta::Enum { underlying, .. } if matches!(**underlying, TypeMeta::I32) - )); - let get_hotkey = interface - .interface - .methods + let mut recorder = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Storage.Imapi", + "IDiscRecorder", + ) + .expect("IDiscRecorder must exist"); + let raw = recorder + .raw_methods + .as_ref() + .unwrap() .iter() - .find(|method| method.name == "GetHotkey") - .unwrap(); - assert!(matches!(get_hotkey.params[0].typ, TypeMeta::U16)); - let get_icon_location = interface + .position(|method| method.metadata_name == "GetRecorderGUID") + .expect("GetRecorderGUID raw metadata"); + let projected = recorder .interface .methods .iter() - .find(|method| method.name == "GetIconLocation") - .unwrap(); - assert!(matches!(get_icon_location.params[2].typ, TypeMeta::I32)); - let get_hotkey_vtable = get_hotkey.vtable_index; - let get_show_cmd_vtable = get_show_cmd.vtable_index; - - // `GetPath` is intentionally unsupported (see `without_method`); it is - // covered by its own fail-closed regression test below. - let interface_without_get_path = without_method(interface, "GetPath"); - let output = - com::generate_com_interface_files(&interface_without_get_path, &win32_winmd()).unwrap(); - assert!(output.js.contains(&format!( - ".addMethodAt({get_hotkey_vtable}, 'GetHotkey', new DynComMethodSig().addOut(DynCom.u16Type()))" - ))); - assert!(output.js.contains(&format!( - ".addMethodAt({get_show_cmd_vtable}, 'GetShowCmd', new DynComMethodSig().addOut(DynCom.i32Type()))" - ))); + .position(|method| method.name == "GetRecorderGUID") + .expect("GetRecorderGUID projected metadata"); + recorder.raw_methods = Some(vec![recorder.raw_methods.as_ref().unwrap()[raw].clone()]); + recorder.interface.methods = vec![recorder.interface.methods[projected].clone()]; + recorder.own_methods_start = 0; + + let output = com::generate_com_interface_files(&recorder, &win32_winmd()) + .expect("the isolated exact documented two-call method must project"); assert!( output - .dts - .contains("getIconLocation(cch?: number): [string, number];") + .js + .contains(".addCallerOutputBuffer(DynCom.u8Type(), 1, 2, true, true)") + && output.js.contains("getRecorderGUID()") + && output + .js + .contains("for (let _attempt = 0; _attempt <= 2; _attempt++)") + && output.js.contains("DynCom.bufferCount") + && output.js.contains("DynCom.nullBuffer()") + && output.js.contains("DynCom.bufferAllocationLength(_actual)") + && output + .js + .contains("COM buffer size changed during bounded two-call retry"), + "two-call sizing must be exact and bounded:\n{}", + output.js ); + assert!(output.dts.contains("getRecorderGUID(): Buffer")); } -/// 6. Partial generation: generating a single class-name yields ONLY that -/// interface plus its immediate deps (enum, coclass metadata), NOT the -/// entire Windows.Win32.UI.Shell namespace. #[test] -fn partial_generation_only_emits_target_interface() { +fn imf_attributes_get_blob_uses_exact_fixed_capacity_bytes() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( + + let mut attributes = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.Media.MediaFoundation", + "IMFAttributes", ) - .unwrap(); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - - // Expected files: ITaskbarList3.js, ITaskbarList3.d.ts, TBPFLAG.js, TBPFLAG.d.ts - let file_names: Vec<&str> = out.extra_files.iter().map(|(n, _)| n.as_str()).collect(); + .expect("IMFAttributes must exist"); + assert_eq!( + attributes.interface.iid, + "2cd2d921-c447-44a7-a13c-4adabfc247e3" + ); + assert_eq!(attributes.base_chain, ["IUnknown"]); + assert_eq!(attributes.base_offset, 3); + assert_eq!(attributes.own_methods_start, 3); - // Should NOT include unrelated Shell types like IShellItem or IApplicationActivationManager + let raw_index = attributes + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetBlob") + .expect("GetBlob raw metadata"); + let raw = &attributes.raw_methods.as_ref().unwrap()[raw_index]; + assert_eq!(raw.vtable_index, 15); + assert_eq!(raw.params.len(), 4); + let contract = raw + .exact_contract + .as_ref() + .expect("GetBlob exact contract evidence"); + assert_eq!( + contract.kind, + com_metadata::RawExactMethodContractKind::FixedCapacityBytes + ); + assert_eq!( + ( + contract.buffer_param_index, + contract.capacity_param_index, + contract.actual_length_param_index, + ), + (1, 2, Some(3)) + ); + assert!(contract.citation.contains("imfattributes-getblob")); + assert_eq!(raw.params[0].typ.pointer_depth, 1); + assert!(raw.params[0].const_attribute); + assert_eq!(raw.params[0].direction, RawParamDirection::In); + assert_eq!(raw.params[1].typ.pointer_depth, 1); + assert_eq!(raw.params[1].direction, RawParamDirection::Out); + assert!(!raw.params[1].optional); + let relation = raw.params[1] + .native_array + .as_ref() + .expect("GetBlob byte relation"); + assert_eq!(relation.count_param_index, Some(2)); + assert_eq!(relation.actual_length_param_index, Some(3)); + assert_eq!(relation.unit, com_metadata::RawCountUnit::Bytes); + assert!(relation.projected_capacity); + assert!(!relation.two_call); + assert_eq!(raw.params[2].direction, RawParamDirection::In); + assert!(matches!(raw.params[2].typ.native_type, RawNativeType::U32)); + assert_eq!(raw.params[3].direction, RawParamDirection::Out); + assert!(raw.params[3].optional); + assert_eq!(raw.params[3].typ.pointer_depth, 1); + + let projected_index = attributes + .interface + .methods + .iter() + .position(|method| method.name == "GetBlob") + .expect("GetBlob compatibility metadata"); + attributes.raw_methods = Some(vec![raw.clone()]); + attributes.interface.methods = vec![attributes.interface.methods[projected_index].clone()]; + attributes.own_methods_start = 0; + + let output = com::generate_com_interface_files(&attributes, &win32_winmd()) + .expect("isolated exact GetBlob must project"); assert!( - !file_names.iter().any(|n| n.starts_with("IShellItem")), - "Partial generation must not include IShellItem: {:?}", - file_names + output + .js + .contains(".addCallerOutputBuffer(DynCom.u8Type(), 2, 3, true, false)") + && output.js.contains("getBlob(guidKey, capacity)") + && output + .js + .contains("Number.isSafeInteger(capacity) || capacity < 0") + && output + .js + .contains("DynCom.bufferAllocationLength(BigInt(capacity))") + && output + .js + .contains("DynCom.callerOutputArray(DynCom.u8Type(), BigInt(_capacity))") + && output.js.contains("return DynCom.takeBuffer(_out);"), + "fixed-capacity GetBlob must allocate exclusive runtime storage and hide native counts:\n{}", + output.js ); assert!( - !file_names - .iter() - .any(|n| n.starts_with("IApplicationActivationManager")), - "Partial generation must not include unrelated types: {:?}", - file_names + output + .dts + .contains("getBlob(guidKey: string, capacity: number): Buffer;"), + "{}", + output.dts ); - // Should include TBPFLAG (a direct dep) - let has_tbpflag = file_names.iter().any(|n| n.starts_with("TBPFLAG")); + let mut invalid_actual = attributes.clone(); + invalid_actual.raw_methods.as_mut().unwrap()[0].params[3].direction = RawParamDirection::InOut; + let error = com::generate_com_interface_files(&invalid_actual, &win32_winmd()) + .expect_err("a distinct actual length must not accept InOut metadata"); assert!( - has_tbpflag, - "TBPFLAG (direct enum dep) must be included: {:?}", - file_names + (error.contains("actual-length") && error.contains("must be Out")) + || error.contains("no longer matches exact contract evidence"), + "{error}" + ); + + use windows::Win32::Media::MediaFoundation::IMFAttributes; + use windows::core::Interface; + assert_eq!( + format!("{:?}", IMFAttributes::IID).to_ascii_lowercase(), + attributes.interface.iid ); } -/// 7. Generated `.d.ts` has PascalCase type + camelCase methods and -/// no raw IID/vtable-index/CoCreateInstance leaked into the TYPED surface. #[test] -fn dts_surface_is_natural_and_clean() { +fn get_private_data_families_fail_closed_for_interface_ownership() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .unwrap(); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - let dts = out.dts.as_str(); - - // PascalCase class name - assert!( - dts.contains("class ITaskbarList3"), - ".d.ts must export class ITaskbarList3, got:\n{}", - dts - ); - // camelCase methods - for cc in &["hrInit", "setProgressValue", "setProgressState", "addTab"] { - assert!( - dts.contains(cc), - ".d.ts must declare camelCase method `{}`, got:\n{}", - cc, - dts + let families = [ + ( + "Windows.Win32.Graphics.Dxgi", + "IDXGIObject", + "aec22fb8-76f3-4639-9be0-28eb43a67a2e", + 5, + ), + ( + "Windows.Win32.Graphics.Direct3D10", + "ID3D10DeviceChild", + "9b7e4c00-342c-4106-a19f-4f2704f689f0", + 4, + ), + ( + "Windows.Win32.Graphics.Direct3D10", + "ID3D10Device", + "9b7e4c0f-342c-4106-a19f-4f2704f689f0", + 66, + ), + ( + "Windows.Win32.Graphics.Direct3D11", + "ID3D11DeviceChild", + "1841e5c8-16b0-489b-bcc8-44cfb0d5deae", + 4, + ), + ( + "Windows.Win32.Graphics.Direct3D11", + "ID3D11Device", + "db6f6ddb-ac77-4e88-8253-819df9bbf140", + 34, + ), + ( + "Windows.Win32.Graphics.Direct3D12", + "ID3D12Object", + "c4fec28f-7966-4e95-9f94-f431cb56c3b8", + 3, + ), + ( + "Windows.Win32.AI.MachineLearning.DirectML", + "IDMLObject", + "c8263aac-9e0c-4a2d-9b8e-007521a3317c", + 3, + ), + ]; + for (namespace, name, iid, slot) in families { + let mut interface = + com_metadata::parse_com_interface(&win32_winmd(), namespace, name).unwrap(); + assert_eq!(interface.interface.iid, iid); + assert_eq!(interface.base_chain, ["IUnknown"]); + let raw_index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetPrivateData") + .unwrap(); + let projected_index = interface + .interface + .methods + .iter() + .position(|method| method.name == "GetPrivateData") + .unwrap(); + let raw = interface.raw_methods.as_ref().unwrap()[raw_index].clone(); + assert_eq!(raw.vtable_index, slot); + assert_eq!( + raw.exact_contract.as_ref().unwrap().kind, + com_metadata::RawExactMethodContractKind::UnsafePrivateData ); - } - // No PascalCase leaked method names - for pc in &[ - "HrInit(", - "SetProgressValue(", - "SetProgressState(", - "AddTab(", - ] { + interface.raw_methods = Some(vec![raw]); + interface.interface.methods = vec![interface.interface.methods[projected_index].clone()]; + interface.own_methods_start = 0; + let error = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect_err("generic GetPrivateData Buffer projection must remain unsupported"); assert!( - !dts.contains(pc), - ".d.ts must not expose PascalCase method `{}`, got:\n{}", - pc, - dts + error.contains("AddRef") + && error.contains("interface pointer") + && (error.contains("ownership") || error.contains("destructive")), + "{namespace}.{name}: {error}" ); } +} - // No raw IID leak in .d.ts - assert!( - !dts.contains("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"), - "raw IID must not leak into .d.ts:\n{}", - dts - ); - // No raw CLSID leak - assert!( - !dts.contains("56fdf344-fd6d-11d0-958a-006097c9a090"), - "raw CLSID must not leak into .d.ts:\n{}", - dts - ); - // No CoCreateInstance leak - assert!( - !dts.contains("CoCreateInstance") && !dts.contains("coCreateInstance"), - "CoCreateInstance must not leak into .d.ts:\n{}", - dts - ); - // No vtable index leak in .d.ts - for slot in &["method(3)", "method(9)", "method(10)", "vtable"] { +#[test] +fn exact_fixed_capacity_byte_contract_mutations_fail_closed() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + fn isolated() -> com_metadata::ComInterfaceMeta { + let mut interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Media.MediaFoundation", + "IMFAttributes", + ) + .unwrap(); + let raw_index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "GetBlob") + .unwrap(); + let projected_index = interface + .interface + .methods + .iter() + .position(|method| method.name == "GetBlob") + .unwrap(); + interface.raw_methods = Some(vec![ + interface.raw_methods.as_ref().unwrap()[raw_index].clone(), + ]); + interface.interface.methods = vec![interface.interface.methods[projected_index].clone()]; + interface.own_methods_start = 0; + interface + } + + let mutations: Vec> = vec![ + Box::new(|interface| { + interface.interface.iid = "11111111-2222-3333-4444-555555555555".into() + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].metadata_name = "GetBlob2".into() + }), + Box::new(|interface| interface.raw_methods.as_mut().unwrap()[0].vtable_index += 1), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[0] + .typ + .pointer_depth = 0 + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[0].const_attribute = false + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[1].direction = RawParamDirection::In + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[1] + .typ + .pointer_depth = 2 + }), + Box::new(|interface| interface.raw_methods.as_mut().unwrap()[0].params[1].optional = true), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[2].direction = RawParamDirection::Out + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[2] + .typ + .native_type = RawNativeType::U16 + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[3].direction = + RawParamDirection::InOut + }), + Box::new(|interface| interface.raw_methods.as_mut().unwrap()[0].params[3].optional = false), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0].params[3] + .typ + .pointer_depth = 2 + }), + Box::new(|interface| { + interface.raw_methods.as_mut().unwrap()[0] + .return_type + .native_type = RawNativeType::Void + }), + ]; + for mutate in mutations { + let mut interface = isolated(); + mutate(&mut interface); + let error = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect_err("mutated exact byte contract must fail"); assert!( - !dts.contains(slot), - "vtable detail `{}` must not appear in .d.ts:\n{}", - slot, - dts + error.contains("GetBlob") || error.contains("exact contract"), + "{error}" ); } } -/// 8. Generated interface `.js` contains only IID/vtable behavior; activation -/// is emitted by the separate coclass wrapper. #[test] -fn js_body_uses_cocreateinstance_and_correct_slots() { +fn unsupported_counted_buffer_contracts_fail_closed() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( + + let enum_string = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.System.Com", + "IEnumString", ) - .unwrap(); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - let js = out.js.as_str(); - - // Only the IID appears in the interface wrapper. - assert!(!js.contains("56fdf344-fd6d-11d0-958a-006097c9a090")); + .expect("IEnumString must exist"); + com::generate_com_interface_files(&enum_string, &win32_winmd()) + .expect("exact IEnumString ownership must project"); + let mut missing_array = enum_string.clone(); + missing_array + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Next") + .unwrap() + .params[1] + .native_array = None; + let error = com::generate_com_interface_files(&missing_array, &win32_winmd()) + .expect_err("IEnumString without count evidence must fail"); assert!( - js.contains("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"), - ".js must embed the IID:\n{}", - js + error.contains("Next") + && (error.contains("pointer") + || error.contains("array") + || error.contains("EnumeratorNext")), + "missing initialized-range evidence must fail closed: {error}" ); - - assert!(!js.contains("coCreateInstance")); - - // Classic COM registration is kept out of the WinRT type namespace. + let mut unknown_allocator = enum_string; + unknown_allocator + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Next") + .unwrap() + .params[1] + .string_pointer_array + .as_mut() + .unwrap() + .ownership = com_metadata::RawElementOwnership::Unknown; + let error = com::generate_com_interface_files(&unknown_allocator, &win32_winmd()) + .expect_err("IEnumString without CoTaskMem ownership must fail"); assert!( - js.contains("DynCom.registerIUnknownInterface"), - ".js must use DynCom registration for classic COM:\n{}", - js + error.contains("Next") + && (error.contains("ownership") + || error.contains("allocator") + || error.contains("cleanup") + || error.contains("caller-sized")), + "unknown element allocator must fail closed: {error}" ); - assert!(js.contains("Windows.Win32.UI.Shell.ITaskbarList3")); - - // Base-aware slots - assert!(js.contains("method(3)"), "HrInit slot 3"); - assert!(js.contains("method(9)"), "SetProgressValue slot 9"); - assert!(js.contains("method(10)"), "SetProgressState slot 10"); - - // Should NOT contain WinRT `.method(6)` for a user method (that would be - // the IInspectable-rooted slot for the first user method). - // HrInit at slot 6 would be the failing case — we accept `method(6)` only - // if that's ActivateTab (slot 6). ActivateTab IS at 6, so it's a valid - // occurrence. Just check the file doesn't say something like `HrInit ... method(6)`. - // This is covered by the exact per-method assertion above. -} -/// Requirement 4 (acronym casing): `ITaskbarList3::SetTabActive(HWND hwndTab, -/// HWND hwndMDI, DWORD dwReserved)` must project `hwndMDI` as `mdi` (the -/// whole `MDI` acronym lowercased), not the naive first-letter-only `mDI`. -#[test] -fn taskbarlist3_settabactive_projects_hwndmdi_as_mdi_not_mdi_mixed_case() { - if !win32_available() { - eprintln!("Skipping: Win32 winmd not available"); - return; - } - let com_iface = com_metadata::parse_com_interface( + let mut stream = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.System.Com", + "ISequentialStream", ) .unwrap(); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - let js = out.js.as_str(); + let read = stream + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Read") + .unwrap(); + read.params[0].native_array = None; + let error = com::generate_com_interface_files(&stream, &win32_winmd()) + .expect_err("a writable void pointer without array evidence must fail"); assert!( - js.contains("setTabActive(tab, mdi, reserved)"), - ".js must lowercase the whole `MDI` acronym in `hwndMDI` -> `mdi`, not `mDI`:\n{}", - js + error.contains("Read") && error.contains("pv"), + "absent evidence must fail at the buffer parameter: {error}" ); + + let mut stream = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "ISequentialStream", + ) + .unwrap(); + stream + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Read") + .unwrap() + .params[0] + .native_array + .as_mut() + .unwrap() + .count_param_index = Some(99); + let error = com::generate_com_interface_files(&stream, &win32_winmd()) + .expect_err("an out-of-range count relation must fail"); assert!( - !js.contains("mDI"), - ".js must not contain the naive-lowering artifact `mDI`:\n{}", - js + error.contains("Read") + && error.contains("pv") + && (error.contains("outside the method") + || error.contains("caller-sized native buffers")), + "mismatched count relationships must fail closed: {error}" ); - let dts = out.dts.as_str(); + + let mut opc = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Storage.Packaging.Opc", + "IOpcSignatureCustomObject", + ) + .unwrap(); + opc.raw_methods.as_mut().unwrap()[0].params[0].free_with = None; + let error = com::generate_com_interface_files(&opc, &win32_winmd()) + .expect_err("callee allocation without its allocator must fail"); assert!( - dts.contains("mdi:"), - ".d.ts must also project the parameter as `mdi`:\n{}", - dts + error.contains("GetXml") + && error.contains("xmlMarkup") + && (error.contains("ownership") || error.contains("caller-sized native buffers")), + "unknown allocator must fail closed: {error}" ); } -/// Lifecycle ergonomics + doc rendering on a generated interface wrapper. -/// Activation lives on the separately generated coclass; the interface must -/// expose `release()`, a protected constructor/IID descriptor for generated -/// coclass inheritance and `as()`, and — since win32metadata attaches a -/// `DocumentationAttribute` (a `learn.microsoft.com` URL) to most methods — -/// an `@see` JSDoc comment referencing that URL. #[test] -fn taskbarlist3_generated_output_has_lifecycle_members_and_doc_links() { +fn standard_enumerator_next_projects_partial_arrays_and_exact_interface_ownership() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let com_iface = com_metadata::parse_com_interface( + + let guid_enum = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IEnumGUID") + .expect("IEnumGUID must exist"); + let next = guid_enum + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Next") + .unwrap(); + let plan = next + .enumerator_next + .as_ref() + .expect("exact IEnumGUID::Next override"); + assert_eq!( + ( + plan.capacity_param_index, + plan.values_param_index, + plan.fetched_param_index, + plan.fetched_optional_for_single, + ), + (0, 1, 2, true) + ); + let output = com::generate_com_interface_files(&guid_enum, &win32_winmd()) + .expect("IEnumGUID must project completely"); + assert!( + output.js.contains( + ".addEnumeratorNextBuffer(DynCom.guidType(), 0, 2).addOptionalOut(DynCom.u32Type()).preserveEnumeratorNextHresult()" + ) && output + .js + .contains("DynCom.enumeratorOutputArray(DynCom.guidType(), BigInt(count))") + && output.js.contains("DynCom.takeGuidArray(_out[1])") + && output.dts.contains("next(count: number): string[]") + && output.js.contains(".addMethodAt(6, 'Clone'"), + "IEnumGUID must expose its complete interface with a natural partial-array Next:\n{}", + output.js + ); + + let connection_enum = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", + "Windows.Win32.System.Com", + "IEnumConnectionPoints", ) - .unwrap(); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - let js = out.js.as_str(); - let dts = out.dts.as_str(); - + .expect("IEnumConnectionPoints must exist"); + let next = connection_enum + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Next") + .unwrap(); assert!( - js.contains("release()") && js.contains("this._obj.release();"), - ".js must expose release() delegating to the managed native value:\n{}", - js + !next + .enumerator_next + .as_ref() + .expect("exact IEnumConnectionPoints::Next override") + .fetched_optional_for_single ); + let output = com::generate_com_interface_files(&connection_enum, &win32_winmd()) + .expect("IEnumConnectionPoints must project completely"); assert!( - dts.contains("release(): void;"), - ".d.ts must declare release(): void;:\n{}", - dts + output.js.contains( + ".addEnumeratorNextBuffer(DynCom.interfaceType(WinGuid.parse('b196b286-bab4-101a-b69c-00aa00341d07')), 0, 2).addOut(DynCom.u32Type()).preserveEnumeratorNextHresult()" + ) && output.js.contains("DynCom.takeComArray(_out[1])") + && output + .js + .contains("value => IConnectionPoint._fromNative(value)") + && output + .dts + .contains("next(count: number): IConnectionPoint[]") + && output + .extra_files + .iter() + .any(|(name, _)| name == "IConnectionPoint.js") + && output + .extra_files + .iter() + .any(|(name, _)| name == "IConnectionPoint.d.ts"), + "owned interface elements must use managed wrappers and emit their complete dependency:\n{}", + output.js ); + + let variant_enum = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Ole", + "IEnumVARIANT", + ) + .expect("IEnumVARIANT must exist"); + let output = com::generate_com_interface_files(&variant_enum, &win32_winmd()) + .expect("IEnumVARIANT must project completely"); assert!( - dts.contains("protected constructor(obj: unknown);") - && dts.contains("static readonly IID:"), - ".d.ts must expose only the generated-coclass/interface-view construction surface:\n{}", - dts + output + .js + .contains(".addEnumeratorNextBuffer(DynCom.variantType(), 0, 2)") + && output.js.contains("DynCom.takeVariantArray(_out[1])") + && output.dts.contains("next(count: number): DynComVariant[]"), + "{}", + output.js ); + + let string_enum = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "IEnumString", + ) + .expect("IEnumString must exist"); + let output = com::generate_com_interface_files(&string_enum, &win32_winmd()) + .expect("IEnumString must project completely"); assert!( - js.contains("@see {@link https://learn.microsoft.com/"), - ".js must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", - js + output + .js + .contains(".addEnumeratorNextBuffer(DynCom.coTaskMemWideStringType(), 0, 2)") + && output + .js + .contains("DynCom.takeCoTaskMemWideStringArray(_out[1])") + && output.dts.contains("next(count: number): string[]"), + "{}", + output.js ); + + let inherited_enum = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.TextServices", + "IEnumITfCompositionView", + ) + .expect("IEnumITfCompositionView must exist"); + let next = inherited_enum + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Next") + .unwrap(); + assert_eq!(next.vtable_index, 4); + assert!(next.enumerator_next.is_some()); + let output = com::generate_com_interface_files(&inherited_enum, &win32_winmd()) + .expect("exact non-slot-3 interface enumerator must project"); assert!( - dts.contains("@see {@link https://learn.microsoft.com/"), - ".d.ts must render win32metadata's DocumentationAttribute URL as an @see JSDoc comment:\n{}", - dts + output.js.contains(".preserveEnumeratorNextHresultAt(4)") + && output + .dts + .contains("next(count: number): ITfCompositionView[]"), + "{}", + output.js ); -} -// ------------------------------------------------------------------------- -// CORNER tests -// ------------------------------------------------------------------------- + use windows::Win32::System::Com::{ + IConnectionPoint, IEnumConnectionPoints, IEnumGUID, IEnumString, + }; + use windows::Win32::System::Ole::IEnumVARIANT; + use windows::core::Interface; + assert_eq!( + format!("{:?}", IEnumGUID::IID).to_ascii_lowercase(), + "0002e000-0000-0000-c000-000000000046" + ); + assert_eq!( + format!("{:?}", IEnumConnectionPoints::IID).to_ascii_lowercase(), + "b196b285-bab4-101a-b69c-00aa00341d07" + ); + assert_eq!( + format!("{:?}", IConnectionPoint::IID).to_ascii_lowercase(), + "b196b286-bab4-101a-b69c-00aa00341d07" + ); + assert_eq!( + format!("{:?}", IEnumVARIANT::IID).to_ascii_lowercase(), + "00020404-0000-0000-c000-000000000046" + ); + assert_eq!( + format!("{:?}", IEnumString::IID).to_ascii_lowercase(), + "00000101-0000-0000-c000-000000000046" + ); + assert_eq!(std::mem::size_of::(), 16); + assert_eq!(std::mem::align_of::(), 4); + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::<*mut std::ffi::c_void>() + ); + assert_eq!( + std::mem::align_of::(), + std::mem::align_of::<*mut std::ffi::c_void>() + ); + assert_eq!( + std::mem::size_of::(), + if cfg!(target_pointer_width = "64") { + 24 + } else { + 16 + } + ); + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::<*mut std::ffi::c_void>() + ); +} -/// 9. Regression: WinRT-style (IInspectable-based) interfaces still compute -/// base offset 6 (i.e. the existing WinRT path is unaffected). #[test] -fn winrt_interfaces_still_use_offset_6() { - // Parse a well-known WinRT interface (Windows.Foundation.IUriRuntimeClass or similar) - // via the existing WinRT path — its first method should still have vtable_index = 6. - let Some(windows_winmd) = discovered_windows_winmd() else { - eprintln!( - "Skipping winrt_interfaces_still_use_offset_6: no Windows SDK Windows.winmd discoverable" - ); +fn enumerator_next_exact_evidence_fails_closed_when_mutated() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); return; - }; - // Take Windows.Foundation.Uri's default interface — pick one that has methods. - let class = meta::parse_class(&windows_winmd, "Windows.Foundation", "Uri") - .expect("Windows.Foundation.Uri must be present"); - let default_iface = class - .default_interface - .as_ref() - .expect("Uri must have a default interface"); + } - // Its first method's vtable_index must still be 6 (unchanged from existing - // WinRT behavior); classic-COM support must not regress this. - let first_slot = default_iface - .methods - .first() - .map(|m| m.vtable_index) - .expect("Uri default interface must have methods"); - assert_eq!( - first_slot, 6, - "WinRT interfaces retain the IInspectable base offset of 6" + let mut mismatched = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IEnumGUID") + .unwrap(); + let next = mismatched + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Next") + .unwrap(); + next.params[1] + .native_array + .as_mut() + .unwrap() + .count_param_index = Some(2); + let error = com::generate_com_interface_files(&mismatched, &win32_winmd()).unwrap_err(); + assert!( + error.contains("Next") + && (error.contains("count") + || error.contains("caller-sized native buffers") + || error.contains("Unknown native type") + || error.contains("unknown native type")), + "{error}" + ); + + let mut nonstandard = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IEnumGUID") + .unwrap(); + nonstandard + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Next") + .unwrap() + .vtable_index = 4; + let error = com::generate_com_interface_files(&nonstandard, &win32_winmd()).unwrap_err(); + assert!( + error.contains("slot-3 ABI shape") + || error.contains("duplicate vtable slot") + || error.contains("vtable") + || error.contains("caller-sized native buffers"), + "{error}" + ); + + let mut variant_enum = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Ole", + "IEnumVARIANT", + ) + .expect("IEnumVARIANT must exist"); + variant_enum + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "Next") + .unwrap() + .params[1] + .typ + .pointer_depth = 2; + let error = com::generate_com_interface_files(&variant_enum, &win32_winmd()) + .expect_err("mutated VARIANT enumerator must fail closed"); + assert!( + error.contains("Next") + && (error.contains("initialized-range cleanup") + || error.contains("Automation") + || error.contains("caller-sized native buffers") + || error.contains("unsupported") + || error.contains("exact enumerator evidence")), + "{error}" ); } -/// 10. Interface-not-found is a clean Option::None, not a panic. #[test] -fn interface_not_found_is_clean_none() { +fn real_owning_counted_arrays_project_natural_inputs_and_outputs() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let missing = com_metadata::parse_com_interface( + + let type_info = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "ITypeInfo") + .expect("ITypeInfo must exist"); + let get_names = type_info + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetNames") + .unwrap(); + let names = get_names.params[1].native_array.as_ref().unwrap(); + assert_eq!(names.count_param_index, Some(2)); + assert_eq!(names.actual_length_param_index, Some(3)); + assert!(names.evidence.iter().any(|evidence| matches!( + evidence, + com_metadata::RawEvidence::Override { citation, .. } + if citation.contains("itypeinfo-getnames") + ))); + let get_names_output = com::generate_com_interface_files( + &isolate_com_method(&type_info, "GetNames"), &win32_winmd(), - "Windows.Win32.UI.Shell", - "IDoesNotExist_XYZ", + ) + .unwrap(); + assert!( + get_names_output + .js + .contains(".addCallerOutputBuffer(DynCom.bstrType(), 2, 3, false, false)") + ); + + let mut invalid = isolate_com_method(&type_info, "GetNames"); + invalid.raw_methods.as_mut().unwrap()[0].params[3].direction = RawParamDirection::In; + let error = com::generate_com_interface_files(&invalid, &win32_winmd()) + .expect_err("GetNames must require an authoritative output actual count"); + assert!( + error.contains("actual length") + || error.contains("output") + || error.contains("caller-sized native buffers"), + "{error}" + ); + + let cases = [ + ( + "Windows.Win32.System.RemoteDesktop", + "ITSGAuthorizeResourceSink", + "OnChannelAuthorized", + "DynCom.bstrArray(", + "string[]", + ), + ( + "Windows.Win32.System.Wmi", + "IWbemObjectSink", + "Indicate", + "DynCom.interfaceArray(", + "IWbemClassObject[]", + ), + ( + "Windows.Win32.System.Com.StructuredStorage", + "IPropertyBag2", + "Write", + "DynCom.variantArray(", + "DynComVariant[]", + ), + ( + "Windows.Win32.System.Com", + "ITypeInfo", + "GetNames", + "DynCom.takeBstrArray(", + "string[]", + ), + ]; + for (namespace, interface, method, js, dts) in cases { + let output = project_isolated_com_method(namespace, interface, method); + assert!( + output.js.contains(js), + "{}.{}:\n{}", + interface, + method, + output.js + ); + assert!( + output.dts.contains(dts), + "{}.{}:\n{}", + interface, + method, + output.dts + ); + } + let sink = + project_isolated_com_method("Windows.Win32.System.Wmi", "IWbemObjectSink", "Indicate"); + let wrapper = sink + .extra_files + .iter() + .find(|(name, _)| name == "IWbemClassObject.js") + .expect("nominal element wrapper dependency"); + assert!( + wrapper.1.contains("class IWbemClassObject"), + "{}", + wrapper.1 + ); + assert!( + !wrapper.1.contains(".addMethodAt("), + "an incomplete dependency must remain an opaque nominal wrapper:\n{}", + wrapper.1 ); - assert!(missing.is_none()); } -/// 11. QI-only interface (no coclass) → wrapper emitted WITHOUT `create()`, -/// only a static from-raw / QI entry point. #[test] -fn qi_only_interface_has_no_create() { +fn real_borrowed_hwnd_outputs_are_exact_numeric_getters() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - // IPersist is IUnknown-rooted (has 1 own method: GetClassID) and has NO - // "Persist" coclass anywhere in the metadata — verified via probe. - let com_iface = - com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IPersist") - .expect("IPersist must exist in Win32 metadata"); + + let cases = [ + ( + "Windows.Win32.System.Ole", + "IOleWindow", + "GetWindow", + "getWindow(): HWND;", + ), + ( + "Windows.Win32.System.Mmc", + "IConsole", + "GetMainWindow", + "getMainWindow(): HWND;", + ), + ( + "Windows.Win32.Devices.ImageAcquisition", + "IWiaAppErrorHandler", + "GetWindow", + "getWindow(): HWND;", + ), + ( + "Windows.Win32.UI.Shell", + "ICredentialProviderCredentialEvents", + "OnCreatingWindow", + "onCreatingWindow(): HWND;", + ), + ( + "Windows.Win32.Media.PictureAcquisition", + "IPhotoProgressDialog", + "GetWindow", + "getWindow(): HWND;", + ), + ( + "Windows.Win32.Media.DirectShow", + "IOverlay", + "GetWindowHandle", + "getWindowHandle(): HWND;", + ), + ( + "Windows.Win32.Media.DirectShow.Tv", + "IMSVidCtl", + "get_Window", + "get_Window(): HWND;", + ), + ( + "Windows.Win32.Media.DirectShow.Tv", + "IMSVidRect", + "get_HWnd", + "get_HWnd(): HWND;", + ), + ( + "Windows.Win32.Media.MediaFoundation", + "IMFPMediaPlayer", + "GetVideoWindow", + "getVideoWindow(): HWND;", + ), + ( + "Windows.Win32.Media.MediaFoundation", + "IMFVideoDisplayControl", + "GetVideoWindow", + "getVideoWindow(): HWND;", + ), + ( + "Windows.Win32.System.WinRT", + "ICoreWindowInterop", + "get_WindowHandle", + "get_WindowHandle(): HWND;", + ), + ( + "Windows.Win32.System.WinRT", + "IShareWindowCommandEventArgsInterop", + "GetWindow", + "getWindow(): HWND;", + ), + ( + "Windows.Win32.System.WinRT.Xaml", + "IDesktopWindowXamlSourceNative", + "get_WindowHandle", + "get_WindowHandle(): HWND;", + ), + ( + "Windows.Win32.System.UpdateAgent", + "IUpdateInstaller", + "get_ParentHwnd", + "get_ParentHwnd(): HWND;", + ), + ( + "Windows.Win32.UI.Accessibility", + "IUIAutomationElement", + "get_CachedNativeWindowHandle", + "get_CachedNativeWindowHandle(): HWND;", + ), + ( + "Windows.Win32.UI.Accessibility", + "IUIAutomationElement", + "get_CurrentNativeWindowHandle", + "get_CurrentNativeWindowHandle(): HWND;", + ), + ( + "Windows.Win32.UI.Shell", + "ILaunchSourceViewSizePreference", + "GetSourceViewToPosition", + "getSourceViewToPosition(): HWND;", + ), + ( + "Windows.Win32.UI.Shell", + "IFileIsInUse", + "GetSwitchToHWND", + "getSwitchToHWND(): HWND;", + ), + ( + "Windows.Win32.UI.Shell", + "IPreviewHandler", + "QueryFocus", + "queryFocus(): HWND;", + ), + ( + "Windows.Win32.UI.TabletPC", + "ITextInputPanel", + "get_AttachedEditWindow", + "get_AttachedEditWindow(): HWND;", + ), + ( + "Windows.Win32.UI.TextServices", + "ITfContextOwner", + "GetWnd", + "getWnd(): HWND;", + ), + ( + "Windows.Win32.UI.TextServices", + "ITfContextView", + "GetWnd", + "getWnd(): HWND;", + ), + ]; + assert_eq!(cases.len(), 22); + for (namespace, interface, method, declaration) in cases { + let output = project_isolated_com_method(namespace, interface, method); + assert!( + output + .js + .contains(".addOut(DynCom.borrowedHandleOutputType())"), + "{interface}.{method}:\n{}", + output.js + ); + assert!( + output.js.contains("DynCom.asPointerBigint("), + "{interface}.{method}:\n{}", + output.js + ); + assert!( + output.dts.contains(declaration), + "{interface}.{method}:\n{}", + output.dts + ); + assert!(!output.js.contains("adoptComPointer")); + assert!(!output.js.contains("DestroyWindow")); + assert!(!output.dts.contains("Buffer")); + } + + let ole = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Ole", "IOleWindow") + .unwrap(); + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].declaring_iid = + "00000000-0000-0000-c000-000000000046".into(); + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND IID drift must fail closed"); + assert!(error.contains("borrowed HWND evidence identity"), "{error}"); + + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].vtable_index += 1; + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND slot drift must fail closed"); + assert!(error.contains("borrowed HWND evidence identity"), "{error}"); + + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params[0].name = "changed".into(); + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND parameter drift must fail closed"); assert!( - com_iface.coclass_clsid.is_none(), - "IPersist has no associated coclass CLSID" + error.contains("exact documented borrowed HWND evidence"), + "{error}" ); - let get_class_id = com_iface - .interface - .methods - .iter() - .find(|method| method.name == "GetClassID") - .unwrap(); - assert!(matches!(get_class_id.params[0].typ, TypeMeta::Guid)); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface"); - let js = out.js.as_str(); - let dts = out.dts.as_str(); - assert!(js.contains(".addOut(DynCom.guidType())")); + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params[0] + .typ + .pointer_depth = 2; + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND pointer-depth drift must fail closed"); + assert!( + error.contains("exact documented borrowed HWND evidence"), + "{error}" + ); - // No `create()` in either surface + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params[0].direction = RawParamDirection::InOut; + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND direction drift must fail closed"); assert!( - !dts.contains("static create()") && !dts.contains("static create(): "), - "QI-only interface must not expose static create() in .d.ts:\n{}", - dts + error.contains("exact documented borrowed HWND evidence"), + "{error}" ); + + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params[0].free_with = + Some(com_metadata::RawFreeWith { + function: "DestroyWindow".into(), + evidence: com_metadata::RawEvidence::Override { + reason: "mutation", + citation: "mutation", + }, + }); + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND cleanup drift must fail closed"); assert!( - !js.contains("coCreateInstance"), - "QI-only interface must not call coCreateInstance in .js:\n{}", - js + error.contains("exact documented borrowed HWND evidence"), + "{error}" ); - // Must still have a fromNative / QI-only entry + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params.clear(); + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND parameter-count drift must fail closed"); + assert!(error.contains("borrowed HWND evidence"), "{error}"); + + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0].params[0].optional = true; + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND optionality drift must fail closed"); assert!( - js.contains("_fromNative") || js.contains("fromRaw"), - "QI-only interface must expose a from-raw entry:\n{}", - js + error.contains("exact documented borrowed HWND evidence"), + "{error}" ); - // Slot 3 for GetClassID (only method, IUnknown-rooted) + let mut drifted = isolate_com_method(&ole, "GetWindow"); + drifted.raw_methods.as_mut().unwrap()[0] + .return_type + .native_type = com_metadata::RawNativeType::I32; + let error = com::generate_com_interface_files(&drifted, &win32_winmd()) + .expect_err("borrowed HWND return-convention drift must fail closed"); assert!( - js.contains("method(3)"), - "IPersist.GetClassID must invoke slot 3:\n{}", - js + error.contains("exact documented borrowed HWND evidence"), + "{error}" ); } -/// 12. Determinism: regenerating ITaskbarList3 twice produces byte-identical output. #[test] -fn generation_is_deterministic() { +fn real_iolewindow_family_generates_with_borrowed_inherited_hwnd() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let a = { - let com = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .unwrap(); - com::generate_com_interface_files(&com, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface") - }; - let b = { - let com = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .unwrap(); - com::generate_com_interface_files(&com, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface") - }; - assert_eq!(a.js, b.js); - assert_eq!(a.dts, b.dts); - assert_eq!(a.extra_files, b.extra_files); -} -// ------------------------------------------------------------------------- -// SNAPSHOT test -// ------------------------------------------------------------------------- + let interfaces = [ + ("Windows.Win32.System.Ole", "IOleWindow"), + ("Windows.Win32.System.Ole", "IOleInPlaceActiveObject"), + ("Windows.Win32.System.Ole", "IOleInPlaceFrame"), + ("Windows.Win32.System.Ole", "IOleInPlaceObject"), + ("Windows.Win32.System.Ole", "IOleInPlaceObjectWindowless"), + ("Windows.Win32.System.Ole", "IOleInPlaceUIWindow"), + ("Windows.Win32.UI.Shell", "IDeskBand"), + ("Windows.Win32.UI.Shell", "IDeskBand2"), + ("Windows.Win32.UI.Shell", "IDeskBar"), + ("Windows.Win32.UI.Shell", "IDeskBarClient"), + ("Windows.Win32.UI.Shell", "IDockingWindow"), + ("Windows.Win32.UI.Shell", "IDockingWindowFrame"), + ("Windows.Win32.UI.Shell", "IDockingWindowSite"), + ("Windows.Win32.UI.Shell", "IMenuPopup"), + ]; + for (namespace, interface) in interfaces { + let meta = com_metadata::parse_com_interface(&win32_winmd(), namespace, interface).unwrap(); + let output = com::generate_com_interface_files(&meta, &win32_winmd()) + .unwrap_or_else(|error| panic!("{interface}: {error}")); + assert!( + output.dts.contains("getWindow(): HWND;"), + "{interface}:\n{}", + output.dts + ); + assert!( + output + .js + .contains(".addOut(DynCom.borrowedHandleOutputType())"), + "{interface}:\n{}", + output.js + ); + } +} -/// Snapshot test: lock generated TaskbarList coclass and interface files. -/// -/// To update snapshots after an intentional change: -/// cargo run -p dynwinrt-codegen -- generate \ -/// --winmd C:\s\win32metadata\Windows.Win32.winmd \ -/// --namespace Windows.Win32.UI.Shell \ -/// --class-name TaskbarList \ -/// --output tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3 #[test] -fn snapshot_itaskbarlist3() { +fn canonical_iunknown_owning_arrays_use_managed_values_directly() { if !win32_available() { - eprintln!("Skipping snapshot test: Win32 winmd not available"); + eprintln!("Skipping: Win32 winmd not available"); return; } - let coclass = - com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") - .unwrap() - .expect("TaskbarList must exist"); - let out = com::generate_com_coclass_files(&coclass, &win32_winmd()) - .expect("codegen must succeed for TaskbarList"); - - let snapshot_dir: PathBuf = - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/itaskbarlist3"); - assert!( - snapshot_dir.exists(), - "Snapshot directory not found: {}", - snapshot_dir.display() - ); - let mut generated: Vec<(String, String)> = Vec::new(); - generated.push(("TaskbarList.js".into(), out.js.clone())); - generated.push(("TaskbarList.d.ts".into(), out.dts.clone())); - for (name, content) in &out.extra_files { - generated.push((name.clone(), content.clone())); + let cases = [ + ("Windows.Win32.System.Com", "IEnumUnknown"), + ("Windows.Win32.Storage.VirtualDiskService", "IEnumVdsObject"), + ("Windows.Win32.System.Com.Events", "IEnumEventObject"), + ]; + for (namespace, interface) in cases { + let meta = com_metadata::parse_com_interface(&win32_winmd(), namespace, interface).unwrap(); + let output = com::generate_com_interface_files(&meta, &win32_winmd()).unwrap(); + assert!( + output.js.contains("Array.from(DynCom.takeComArray("), + "{interface}:\n{}", + output.js + ); + assert!( + output.dts.contains("DynWinRtValue[]"), + "{interface}:\n{}", + output.dts + ); + assert!(!output.js.contains("require('./IUnknown.js')")); + assert!(!output.dts.contains("IUnknown[]")); + assert!( + output + .extra_files + .iter() + .all(|(name, _)| name != "IUnknown.js" && name != "IUnknown.d.ts") + ); + let names = output + .extra_files + .iter() + .map(|(name, _)| name) + .collect::>(); + assert_eq!(names.len(), output.extra_files.len()); } +} - let mut mismatches = Vec::new(); - for (name, actual) in &generated { - let path = snapshot_dir.join(name); - if !path.exists() { - mismatches.push(format!(" missing snapshot: {}", name)); - continue; - } - let expected = fs::read_to_string(&path).unwrap(); - if actual.trim_end() != expected.trim_end() { - mismatches.push(format!(" differs: {}", name)); - } - } +#[test] +fn windows_iid_oracle_matches_ole_window_and_iunknown() { + use windows::core::Interface; - // Any extra snapshot file not produced by the generator is also a mismatch. - if let Ok(entries) = fs::read_dir(&snapshot_dir) { - let names: std::collections::HashSet = - generated.iter().map(|(n, _)| n.clone()).collect(); - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if !names.contains(&name) { - mismatches.push(format!(" extra snapshot not generated: {}", name)); - } - } - } + assert_eq!( + windows::Win32::System::Ole::IOleWindow::IID, + windows::core::GUID::from_u128(0x00000114_0000_0000_c000_000000000046) + ); + assert_eq!( + windows::core::IUnknown::IID, + windows::core::GUID::from_u128(0x00000000_0000_0000_c000_000000000046) + ); +} - if !mismatches.is_empty() { - panic!( - "ITaskbarList3 snapshot mismatch!\n{}\n\n\ - To update, re-run the generator or copy the actual output into the snapshot dir.", - mismatches.join("\n") +#[test] +fn dynamic_iid_requires_exact_guid_and_output_pointer_depths() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "IDataTransferManagerInterop", + ) + .unwrap(); + for (param_from_end, depth) in [(2usize, 2usize), (1usize, 3usize)] { + let mut invalid = interface.clone(); + let method = invalid + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "GetForWindow") + .unwrap(); + let index = method.params.len() - param_from_end; + method.params[index].typ.pointer_depth = depth; + let error = com::generate_com_interface_files(&invalid, &win32_winmd()).unwrap_err(); + assert!( + error.contains("GetForWindow") && error.contains("dynamic-IID"), + "{error}" ); } } -// ------------------------------------------------------------------------- -// --import-name honored by classic-COM path -// ------------------------------------------------------------------------- - -/// Regression test for a bug where the classic-COM generator hardcoded the -/// runtime import as `'@microsoft/dynwinrt'`, ignoring the `--import-name` -/// CLI flag (which the WinRT path already honored via -/// `codegen::project::set_import_name`). Fixing this makes it possible to -/// regenerate the Node E2E wrappers from `Windows.Win32.winmd` without -/// hand-patching the import line. -/// -/// The test uses the same thread-local as `set_import_name`, so it -/// save/restores the default around the assertion to avoid contaminating -/// other tests that assume the `@microsoft/dynwinrt` default (notably the -/// snapshot tests). `#[serial]` is intentionally NOT used — because -/// `RUNTIME_IMPORT_NAME` is a `thread_local!`, cargo's parallel test runner -/// gives each thread its own copy; restoring on the same thread is enough. #[test] -fn import_name_flag_is_honored_by_com_path() { +fn generalized_dynamic_iid_unlocks_non_positional_real_interfaces() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - let previous = get_import_name(); - set_import_name("../dist/com.js"); - - let result = std::panic::catch_unwind(|| { - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .expect("ITaskbarList3 must exist"); - com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface") - }); - - // Always restore before propagating any assertion failure. - set_import_name(&previous); - - let out = result.unwrap_or_else(|e| std::panic::resume_unwind(e)); + let surface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Graphics.DirectComposition", + "IDCompositionSurface", + ) + .expect("IDCompositionSurface must exist"); + let output = com::generate_com_interface_files(&surface, &win32_winmd()) + .expect("IDCompositionSurface must project completely"); + assert!( + output.dts.contains( + "beginDraw(updateRect: RECT | null, iid: string): [DynWinRtValue, POINT];" + ) && output.js.contains( + ".addIn(DynCom.nativeStructPointerType(_nativeLayout_RECT, true)).addIn(DynCom.pointerType()).addOut(DynCom.ownedComPointerType()).addOut(DynCom.nativeStructType(_nativeLayout_POINT))" + ) && output.js.contains( + "invokeAll(this._obj, [updateRect === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_RECT, updateRect), DynCom.iidPointer(_iid)])" + ) && output.js.contains( + "return [DynCom.adoptComPointer(_r[0], _iid), DynCom.nativeStructBytes(_nativeLayout_POINT, _r[1])];" + ), + "BeginDraw must preserve the non-terminal dynamic output and following POINT result:\n{}", + output.js + ); - // Custom import must appear on the runtime import line... + let texture = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Graphics.DirectComposition", + "IDCompositionTexture", + ) + .expect("IDCompositionTexture must exist"); + let output = com::generate_com_interface_files(&texture, &win32_winmd()) + .expect("IDCompositionTexture must project completely"); assert!( - out.js.contains("require('../dist/com.js')"), - "classic-COM .js must honor --import-name (expected `require('../dist/com.js')`):\n{}", - out.js + output + .dts + .contains("getAvailableFence(iid: string): [bigint, DynWinRtValue];") + && output.js.contains( + ".addOut(DynCom.u64Type()).addIn(DynCom.pointerType()).addOut(DynCom.ownedComPointerType())" + ) + && output + .js + .contains("invokeAll(this._obj, [DynCom.iidPointer(_iid)])") + && output.js.contains( + "return [DynCom.toU64Bigint(_r[0]), DynCom.adoptComPointer(_r[1], _iid)];" + ), + "GetAvailableFence must preserve output order before dynamic adoption:\n{}", + output.js ); - // ...and the hardcoded default must NOT be present in the generated body. + + let class_factory = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Ole", + "IClassFactory2", + ) + .expect("IClassFactory2 must exist"); + let output = com::generate_com_interface_files(&class_factory, &win32_winmd()) + .expect("IClassFactory2 must project completely"); assert!( - !out.js.contains("'@microsoft/dynwinrt'"), - "classic-COM .js must NOT hardcode '@microsoft/dynwinrt' when --import-name is set:\n{}", - out.js + output.dts.contains( + "createInstanceLic(pUnkOuter: DynWinRtValue | null, pUnkReserved: DynWinRtValue | null, riid: string, bstrKey: string): DynWinRtValue;" + ) && output.js.contains( + "createInstanceLic(pUnkOuter, pUnkReserved, riid, bstrKey)" + ) && output.js.contains( + "DynCom.iidPointer(_iid), DynCom.bstr(bstrKey)" + ) && output.js.contains("DynCom.adoptComPointer(_out, _iid)"), + "CreateInstanceLic must keep the visible BSTR after its non-adjacent IID:\n{}", + output.js ); - // Sanity: after restoring the default, subsequent generation reverts. - let default_out = { - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .expect("ITaskbarList3 must exist"); - com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interface") - }; - assert!( - default_out - .js - .contains("require('@microsoft/dynwinrt/com')"), - "after restoring, default import must use '@microsoft/dynwinrt/com':\n{}", - default_out.js + use windows::Win32::Graphics::DirectComposition::{IDCompositionSurface, IDCompositionTexture}; + use windows::Win32::System::Ole::IClassFactory2; + use windows::core::Interface; + assert_eq!( + surface.interface.iid, + format!("{:?}", IDCompositionSurface::IID).to_ascii_lowercase() + ); + assert_eq!( + texture.interface.iid, + format!("{:?}", IDCompositionTexture::IID).to_ascii_lowercase() + ); + assert_eq!( + class_factory.interface.iid, + format!("{:?}", IClassFactory2::IID).to_ascii_lowercase() ); } -/// Same test for the interop bridge generation path. #[test] -fn import_name_flag_is_honored_by_interop_wrapper() { +fn real_dynamic_iid_optional_and_multi_interface_shapes_fail_closed() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - if discovered_windows_winmd().is_none() { - eprintln!( - "Skipping: no Windows SDK Windows.winmd discoverable (needed for interop resolution)" - ); - return; - } - - let previous = get_import_name(); - set_import_name("../dist/com.js"); - let result = std::panic::catch_unwind(|| { - let com_iface = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "IDataTransferManagerInterop", - ) - .expect("IDataTransferManagerInterop must exist"); - com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for classic-COM interop interface") - }); - - set_import_name(&previous); - let out = result.unwrap_or_else(|e| std::panic::resume_unwind(e)); + let dxc = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Graphics.Direct3D.Dxc", + "IDxcResult", + ) + .expect("IDxcResult must exist"); + let get_output = dxc + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetOutput") + .unwrap(); + assert!(get_output.params[2].optional); + let error = com::generate_com_interface_files(&dxc, &win32_winmd()) + .expect_err("optional IDxcResult dynamic output must fail closed"); + assert!( + error.contains("GetOutput") && error.contains("dynamic-IID"), + "{error}" + ); - // The interop .js itself must honor the flag. + let viewport = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Graphics.DirectManipulation", + "IDirectManipulationViewport2", + ) + .expect("IDirectManipulationViewport2 must exist"); + let get_tag = viewport + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "GetTag") + .unwrap(); + assert!(get_tag.params[1].optional); + let error = com::generate_com_interface_files(&viewport, &win32_winmd()) + .expect_err("optional GetTag dynamic output must fail closed"); assert!( - out.js.contains("require('../dist/com.js')"), - "interop .js must honor --import-name:\n{}", - out.js + error.contains("GetTag") && error.contains("dynamic-IID"), + "{error}" ); + + let primary = isolate_com_method(&viewport, "GetPrimaryContent"); + let output = com::generate_com_interface_files(&primary, &win32_winmd()) + .expect("required GetPrimaryContent shape must project in isolation"); assert!( - !out.js.contains("'@microsoft/dynwinrt'"), - "interop .js must NOT hardcode '@microsoft/dynwinrt':\n{}", - out.js + output + .dts + .contains("getPrimaryContent(riid: string): DynWinRtValue;") + && output.js.contains("DynCom.adoptComPointer(_out, _iid)"), + "{}", + output.js ); + let lookup = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Media.MediaFoundation", + "IMFTopologyServiceLookup", + ) + .expect("IMFTopologyServiceLookup must exist"); + let error = com::generate_com_interface_files(&lookup, &win32_winmd()) + .expect_err("multi-interface lookup array must fail closed"); assert!( - out.dts.contains("from '../dist/com.js'"), - "interop .d.ts must honor --import-name:\n{}", - out.dts + error.contains("LookupService") + && error.contains("dynamic-IID") + && error.contains("in, out"), + "{error}" ); + + let netcfg = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.NetworkManagement.NetManagement", + "INetCfg", + ) + .expect("INetCfg must exist"); + let error = com::generate_com_interface_files(&netcfg, &win32_winmd()) + .expect_err("optional QueryNetCfgClass output must no longer be adopted"); assert!( - !out.extra_files - .iter() - .any(|(name, _)| name.starts_with("DataTransferManager.")), - "COM codegen must not emit a projected WinRT companion" + error.contains("QueryNetCfgClass") && error.contains("dynamic-IID"), + "{error}" + ); + + use windows::Win32::Graphics::Direct3D::Dxc::IDxcResult; + use windows::Win32::Graphics::DirectManipulation::IDirectManipulationViewport2; + use windows::core::Interface; + assert_eq!( + dxc.interface.iid, + format!("{:?}", IDxcResult::IID).to_ascii_lowercase() + ); + assert_eq!( + viewport.interface.iid, + format!("{:?}", IDirectManipulationViewport2::IID).to_ascii_lowercase() ); } #[test] -fn shellitem_getdisplayname_is_not_classified_as_caller_owned_string_buffer() { +fn owned_handle_outputs_fail_without_a_projected_cleanup_owner() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - - let com_iface = - com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellItem") - .expect("IShellItem must exist"); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for IShellItem"); - - assert!( - out.js.contains(".addOut(DynCom.coTaskMemPointerType())") - && out.js.contains( - "'GetDisplayName', new DynComMethodSig().addIn(DynCom.i32Type()).addOut(DynCom.coTaskMemPointerType())" - ), - "PWSTR* callee-allocated output must be registered as an owned CoTaskMem output, not the unclassified pointer type:\n{}", - out.js - ); + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "IExtractIconW", + ) + .expect("IExtractIconW must exist"); + let error = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect_err("owned HICON outputs must not project as borrowed bigint values"); assert!( - !out.js.contains("getDisplayName(sigdnName = 260)") - && !out.js.contains("_decodeWideString"), - "IShellItem.GetDisplayName must not allocate/decode a caller-owned buffer:\n{}", - out.js + error.contains("owned handle output") || error.contains("cleanup"), + "{error}" ); } #[test] -fn u16_input_param_uses_existing_u16_value_ctor_not_u16value() { +fn production_codegen_requires_validated_raw_com_facts() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } + let mut interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .expect("ITaskbarList3 must exist"); + let pbutton = interface + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "ThumbBarAddButtons") + .and_then(|method| { + method + .params + .iter_mut() + .find(|param| param.name == "pButton") + }) + .expect("ThumbBarAddButtons.pButton raw facts must exist"); + pbutton.typ.constness = com_metadata::RawConstness::Unspecified; - // IShellLinkW.SetHotkey takes a [in] u16 (WORD). The classic-COM value - // ctor is DynCom.u16(...) — there is no `u16Value`/`i16Value`. Regression - // guard: the arg-wrapper must emit the ctor that actually exists, or the - // generated call throws at runtime. - let com_iface = - com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") - .expect("IShellLinkW must exist"); - let com_iface = without_method(com_iface, "GetPath"); - let out = com::generate_com_interface_files(&com_iface, &win32_winmd()) - .expect("codegen must succeed for IShellLinkW"); - - assert!( - out.js.contains("DynCom.u16(wHotkey)"), - "u16 input param must wrap via the existing DynCom.u16(...):\n{}", - out.js - ); + let error = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect_err("production projection must reject incomplete raw pointer facts"); assert!( - !out.js.contains("u16Value(") && !out.js.contains("i16Value("), - "codegen must not emit non-existent u16Value/i16Value ctor:\n{}", - out.js + error.contains("ThumbBarAddButtons") + && error.contains("pButton") + && error.contains("unknown pointer meaning"), + "semantic validation must fail before the legacy adapter: {error}" ); } #[test] -fn sid_buffers_keep_data_pointer_address_semantics() { +fn production_projection_ignores_legacy_abi_fields() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - - let interface = com_metadata::parse_com_interface( + let mut interface = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.Storage.FileSystem", - "IDiskQuotaControl", + "Windows.Win32.UI.Shell", + "ITaskbarList3", ) - .expect("IDiskQuotaControl must exist"); - let output = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect("IDiskQuotaControl generation should succeed"); + .expect("ITaskbarList3 must exist"); + let baseline = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect("baseline generation must succeed"); + let method = interface + .interface + .methods + .iter_mut() + .find(|method| method.name == "SetProgressValue") + .expect("SetProgressValue must exist"); + method.params[1].typ = TypeMeta::Bool; + method.params[1].direction = com_metadata::ParamDirection::Out; + method.vtable_index = 999; + method.return_type = None; + method.preserve_hresult = true; + method.owned_outputs = vec![com_metadata::OwnedOutput { + param_index: 1, + free_with: "NotARealCleanup".into(), + }]; + interface + .referenced_enums + .iter_mut() + .find(|definition| definition.name == "TBPFLAG") + .unwrap() + .members[0] + .value = com_metadata::ComEnumValue::Signed(999); + + let projected = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect("validated raw contracts, not compatibility ABI fields, drive projection"); + assert_eq!(projected.js, baseline.js); + assert_eq!(projected.dts, baseline.dts); + assert_eq!(projected.extra_files, baseline.extra_files); +} + +#[test] +fn semantic_interface_rejects_reserved_and_duplicate_slots() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let mut inspectable = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.WinRT", + "ISystemMediaTransportControlsInterop", + ) + .unwrap(); + inspectable.raw_methods.as_mut().unwrap()[0].vtable_index = 3; + let error = com::generate_com_interface_files(&inspectable, &win32_winmd()).unwrap_err(); assert!( - output - .dts - .contains("addUserSid(pUserSid: PSID | Buffer | Uint8Array"), - "PSID input must accept backing storage rather than handle bytes:\n{}", - output.dts - ); - assert!( - output.js.contains("DynCom.pointer(pUserSid)") - && !output.js.contains("handleValue(pUserSid)"), - "PSID Buffer must pass its address, not decoded contents:\n{}", - output.js + error.contains("reserved vtable slot") && error.contains("first user slot is 6"), + "{error}" ); + + let mut taskbar = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let methods = taskbar.raw_methods.as_mut().unwrap(); + methods[1].vtable_index = methods[0].vtable_index; + let error = com::generate_com_interface_files(&taskbar, &win32_winmd()).unwrap_err(); + assert!(error.contains("duplicate vtable slot"), "{error}"); } #[test] -fn native_array_buffers_fail_closed() { +fn coclass_activation_requires_a_valid_nonzero_clsid() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } + let mut coclass = + com_metadata::parse_com_coclass(&win32_winmd(), "Windows.Win32.UI.Shell", "TaskbarList") + .unwrap() + .unwrap(); - let interface = com_metadata::parse_com_interface( + coclass.primary_interface.interface.iid = + coclass.primary_interface.interface.iid.to_ascii_uppercase(); + com::generate_com_coclass_files(&coclass, &win32_winmd()) + .expect("valid IID casing must not affect primary-interface selection"); + + coclass.clsid = "not-a-guid".into(); + let error = com::generate_com_coclass_files(&coclass, &win32_winmd()).unwrap_err(); + assert!(error.contains("invalid GUID"), "{error}"); + + coclass.clsid = "00000000-0000-0000-0000-000000000000".into(); + let error = com::generate_com_coclass_files(&coclass, &win32_winmd()).unwrap_err(); + assert!(error.contains("zero CLSID"), "{error}"); +} + +#[test] +fn unresolved_named_pointer_aliases_fail_closed_before_name_classification() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let mut interface = com_metadata::parse_com_interface( &win32_winmd(), - "Windows.Win32.Storage.Imapi", - "IDiscRecorder", + "Windows.Win32.UI.Shell", + "ITaskbarList3", ) - .expect("IDiscRecorder must exist"); - let error = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect_err("NativeArrayInfo byte buffers must not become scalar in/out storage"); + .unwrap(); + let hwnd = interface + .raw_methods + .as_mut() + .unwrap() + .iter_mut() + .find(|method| method.metadata_name == "AddTab") + .unwrap() + .params + .first_mut() + .unwrap(); + if let com_metadata::RawNativeType::Named { kind, .. } = &mut hwnd.typ.native_type { + *kind = com_metadata::RawNamedKind::Unknown; + } else { + panic!("AddTab HWND must be a named type"); + } - assert!( - error.contains("GetRecorderGUID") - && error.contains("pbyUniqueID") - && error.contains("caller-sized native buffers are not supported"), - "generation must fail with a targeted buffer diagnostic: {error}" - ); + let error = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap_err(); + assert!(error.contains("unknown native type"), "{error}"); } #[test] @@ -1204,14 +3758,23 @@ fn required_parameters_after_string_buffer_count_remain_required() { return; } - let interface = com_metadata::parse_com_interface( + let mut interface = com_metadata::parse_com_interface( &win32_winmd(), "Windows.Win32.UI.Shell", "IExtractImage", ) .expect("IExtractImage must exist"); + interface + .interface + .methods + .retain(|method| method.name == "GetLocation"); + interface + .raw_methods + .as_mut() + .unwrap() + .retain(|method| method.projected_name == "GetLocation"); let output = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect("IExtractImage generation should succeed"); + .expect("isolated IExtractImage.GetLocation generation should succeed"); assert!( output @@ -1229,7 +3792,7 @@ fn required_parameters_after_string_buffer_count_remain_required() { ); assert!( output.dts.contains( - "getLocation(cch: number, pdwPriority: number, prgSize: bigint | Buffer, recClrDepth: number, pdwFlags: number)" + "getLocation(cch: number, pdwPriority: number, prgSize: SIZE, recClrDepth: number, pdwFlags: number)" ), "declarations must keep the parameters required:\n{}", output.dts @@ -1318,46 +3881,113 @@ fn unsigned_enum_values_preserve_their_value() { } #[test] -fn shelllink_getpath_fails_closed_on_unsupported_find_data_struct() { +fn shelllink_getpath_projects_validated_find_data_pod() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - // `IShellLinkW::GetPath` takes a caller-writable `WIN32_FIND_DATAW* pfd` - // (an [in, out] multi-field struct with no NativeArrayInfo count and no - // recognized single-field pointer-alias/scalar shape). There is no safe - // layout/size projection for it, so generation must fail closed with an - // actionable diagnostic instead of silently treating it as an opaque - // caller-owned buffer (the removed `pfd`/`finddata` name heuristic). let interface = com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") .expect("IShellLinkW must exist"); - let error = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect_err("GetPath's WIN32_FIND_DATAW* must fail closed, not fall back to a heuristic"); + let output = com::generate_com_interface_files(&interface, &win32_winmd()) + .expect("WIN32_FIND_DATAW has a complete validated POD layout"); + assert!( + output + .dts + .contains("getPath(cch: number, pfd: WIN32_FIND_DATAW | null, fFlags: number): [string, WIN32_FIND_DATAW | null];") + && output.dts.contains("createWIN32_FIND_DATAW") + && output.js.contains("DynCom.nativeStructPointerType(") + && output.js.contains("DynCom.nullNativeStructPointer()") + && output.js.contains("DynCom.nativeStructBytes(") + && output.js.contains("\"size\":592") + && output.js.contains("\"count\":260") + && output.js.contains("Windows.Win32.Foundation.FILETIME"), + "GetPath must render only the validated nested/fixed-array POD plan:\n{}", + output.dts + ); +} + +#[test] +fn real_win32_pods_cover_value_pointer_out_and_inout_shapes() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + + let drop_target = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Ole", + "IDropTarget", + ) + .expect("IDropTarget must exist"); + let drop_output = com::generate_com_interface_files(&drop_target, &win32_winmd()) + .expect("POINTL by-value methods must project"); + assert!( + drop_output + .dts + .contains("export type POINTL = DynComNativeStruct &") + ); + assert!( + drop_output + .dts + .contains("dragOver(grfKeyState: MODIFIERKEYS_FLAGS, pt: POINTL") + ); + assert!( + drop_output + .js + .contains("\"name\":\"Windows.Win32.Foundation.POINTL\",\"x86\":{\"size\":8") + ); + + let bind_ctx = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.System.Com", "IBindCtx") + .expect("IBindCtx must exist"); + let error = com::generate_com_interface_files(&bind_ctx, &win32_winmd()) + .expect_err("BIND_OPTS must fail until cbStruct initialization is modeled"); + assert!(error.contains("cbStruct"), "{error}"); + + let running_object_table = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Com", + "IRunningObjectTable", + ) + .expect("IRunningObjectTable must exist"); + let rot_output = com::generate_com_interface_files(&running_object_table, &win32_winmd()) + .expect("FILETIME input and output methods must project"); + assert!( + rot_output + .dts + .contains("noteChangeTime(register: number, pfiletime: FILETIME): void;") + ); + assert!( + rot_output + .dts + .contains("getTimeOfLastChange(pmkObjectName: DynWinRtValue): FILETIME;") + ); assert!( - error.contains("GetPath") && error.contains("pfd") && error.contains("WIN32_FIND_DATAW"), - "diagnostic must name the interface, method, and offending parameter:\n{error}" + rot_output + .js + .contains("DynCom.nativeStructPointerType(_nativeLayout_FILETIME)") + ); + assert!( + rot_output + .js + .contains(".addOut(DynCom.nativeStructType(_nativeLayout_FILETIME))") ); } #[test] -fn shelllink_other_methods_still_generate_when_getpath_is_excluded() { +fn shelllink_other_methods_remain_unchanged_with_pod_support() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } - // Everything else on IShellLinkW (including its OTHER string-buffer - // methods, e.g. GetIconLocation) is unaffected by GetPath's fail-closed - // struct-layout limitation; a consumer can still generate the interface - // by excluding the one unsupported method. let interface = com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.UI.Shell", "IShellLinkW") .expect("IShellLinkW must exist"); - let interface = without_method(interface, "GetPath"); let output = com::generate_com_interface_files(&interface, &win32_winmd()) - .expect("IShellLinkW generation should succeed once GetPath is excluded"); + .expect("IShellLinkW generation should succeed"); assert!( output @@ -1520,6 +4150,11 @@ fn semantic_hresult_preserves_metadata_and_documented_contracts() { .interface .methods .retain(|method| method.name == "IsDirty"); + interface + .raw_methods + .as_mut() + .unwrap() + .retain(|method| method.projected_name == "IsDirty"); let output = com::generate_com_interface_files(&interface, &win32_winmd()) .expect("semantic HRESULT generation must succeed"); assert!(output.js.contains(".preserveHresult()")); @@ -1530,6 +4165,11 @@ fn semantic_hresult_preserves_metadata_and_documented_contracts() { .interface .methods .retain(|method| method.name == "GetCurFile"); + get_cur_file_interface + .raw_methods + .as_mut() + .unwrap() + .retain(|method| method.projected_name == "GetCurFile"); let output = com::generate_com_interface_files(&get_cur_file_interface, &win32_winmd()) .expect("GetCurFile semantic HRESULT generation must succeed"); assert!(output.js.contains(".preserveHresult()")); @@ -1594,8 +4234,12 @@ fn metadata_delegate_parameter_fails_closed_as_a_delegate() { let error = com::generate_com_interface_files(&interface, &win32_winmd()) .expect_err("delegate parameters require a managed callback projection"); - assert!(error.contains("PD2D1_EFFECT_FACTORY")); - assert!(error.contains("managed callback projection")); + assert!( + (error.contains("PD2D1_EFFECT_FACTORY") && error.contains("managed callback projection")) + || (error.contains("D2D1_PROPERTY_BINDING") + && error.contains("nested string/interface ownership")), + "{error}" + ); } #[test] @@ -1699,15 +4343,7 @@ fn com_only_generation_emits_an_importable_package_shape() { "--namespace", "Windows.Win32.UI.Shell", "--class-name", - // `IShellLinkW` is deliberately NOT used here: its `GetPath` - // parameter `pfd` (`WIN32_FIND_DATAW*`) has no safe layout/size - // projection and now correctly fails closed (see the - // `shelllink_getpath_fails_closed_on_unsupported_find_data_struct` - // regression test), which would fail this whole interface's - // generation. `IShellItem` exercises the same incremental - // multi-interface + referenced-enum path (it references both - // `SIGDN` and `SFGAO_FLAGS`) without hitting that limitation. - "IShellItem", + "IShellLinkW", "--output", output_dir.to_str().unwrap(), ]) @@ -1721,15 +4357,14 @@ fn com_only_generation_emits_an_importable_package_shape() { let incremental_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); assert!( incremental_index.contains("ITaskbarList3") - && incremental_index.contains("IShellItem") - && incremental_index.contains("TBPFLAG") - && incremental_index.contains("SIGDN"), + && incremental_index.contains("IShellLinkW") + && incremental_index.contains("TBPFLAG"), "incremental generation must preserve earlier exports:\n{incremental_index}" ); let incremental_package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!( incremental_package.contains("\"./ITaskbarList3\"") - && incremental_package.contains("\"./IShellItem\""), + && incremental_package.contains("\"./IShellLinkW\""), "incremental generation must preserve earlier package subpaths:\n{incremental_package}" ); @@ -1847,9 +4482,9 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { /// Requirement 8: multi-interface COM generation must be atomic enough that /// a later interface's projection failure doesn't leave an earlier, /// successfully-projected interface's files (or the `com/` barrel) newly -/// written on disk. `ITaskbarList3` projects cleanly; `IShellLinkW` fails -/// closed (its `GetPath` parameter `pfd` is an unsupported -/// `WIN32_FIND_DATAW*`). Requesting both in one `--class-name` batch must +/// written on disk. `ITaskbarList3` projects cleanly; `IShellFolder` fails +/// closed because `ParseDisplayName` has an untyped owned pointer output. +/// Requesting both in one `--class-name` batch must /// fail the whole command AND leave no `com/` output directory at all (since /// this is a from-scratch generation into a directory that doesn't exist /// yet). @@ -1875,7 +4510,7 @@ fn multi_interface_com_generation_does_not_leave_partial_output_on_projection_fa "--namespace", "Windows.Win32.UI.Shell", "--class-name", - "ITaskbarList3,IShellLinkW", + "ITaskbarList3,IShellFolder", "--output", output_dir.to_str().unwrap(), ]) @@ -1888,7 +4523,7 @@ fn multi_interface_com_generation_does_not_leave_partial_output_on_projection_fa ); let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("IShellLinkW") && stderr.contains("pfd"), + stderr.contains("IShellFolder") && stderr.contains("ParseDisplayName"), "failure must name the offending interface/parameter:\n{stderr}" ); From 94dbd97db966efa5b846bca8df2ff08c8fd72a53 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 6 Aug 2026 15:37:06 +0800 Subject: [PATCH 3/4] Align CI Win32 metadata with COM registry Run registry and E2E validation against Microsoft.Windows.SDK.Win32Metadata 71.0.14-preview, the baseline used by the exact SAFEARRAY evidence and coverage census. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6307886d-3c24-4596-8924-ba44b0e850a5 --- .github/workflows/build.yml | 4 ++-- .pipelines/ci.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 57f78466..86cfe7e6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,7 +25,7 @@ jobs: run: | $root = Join-Path $env:RUNNER_TEMP 'win32metadata' nuget install Microsoft.Windows.SDK.Win32Metadata ` - -Version 69.0.7-preview ` + -Version 71.0.14-preview ` -OutputDirectory $root ` -DirectDownload ` -NonInteractive @@ -62,7 +62,7 @@ jobs: run: | $root = Join-Path $env:RUNNER_TEMP 'win32metadata' nuget install Microsoft.Windows.SDK.Win32Metadata ` - -Version 69.0.7-preview ` + -Version 71.0.14-preview ` -OutputDirectory $root ` -DirectDownload ` -NonInteractive diff --git a/.pipelines/ci.yml b/.pipelines/ci.yml index f9d154b6..54e5271d 100644 --- a/.pipelines/ci.yml +++ b/.pipelines/ci.yml @@ -106,7 +106,7 @@ extends: script: | $root = Join-Path "$(Agent.TempDirectory)" "win32metadata" nuget install Microsoft.Windows.SDK.Win32Metadata ` - -Version 69.0.7-preview ` + -Version 71.0.14-preview ` -OutputDirectory $root ` -DirectDownload ` -NonInteractive From b5ce48f19e8480bebf5f5082923313750043dd49 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 6 Aug 2026 15:38:12 +0800 Subject: [PATCH 4/4] fix version --- bindings/js/package-lock.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bindings/js/package-lock.json b/bindings/js/package-lock.json index 1812f878..c35d712a 100644 --- a/bindings/js/package-lock.json +++ b/bindings/js/package-lock.json @@ -49,6 +49,7 @@ "integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -1984,6 +1985,7 @@ "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@octokit/auth-token": "^6.0.0", "@octokit/graphql": "^9.0.3", @@ -2643,6 +2645,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" },