diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 86cfe7e6..e456b3d8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,6 +40,33 @@ jobs: run: cargo test -p dynwinrt - name: Test dynwinrt-codegen run: cargo test -p dynwinrt-codegen + - name: Enforce Classic COM coverage baseline + shell: pwsh + run: | + $json = cargo run -p dynwinrt-codegen --quiet -- com-census ` + --winmd $env:DYNWINRT_WIN32_WINMD ` + --json + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $result = $json | ConvertFrom-Json + if ($result.eligible_interfaces -ne 7929) { + throw "Classic COM census denominator changed: $($result.eligible_interfaces)" + } + if ($result.complete_interfaces -lt 5560) { + throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" + } + if ($result.coverage_percent -lt 70.0) { + throw "Classic COM coverage fell below 70%: $($result.coverage_percent)" + } + Write-Host "Classic COM coverage: $($result.complete_interfaces)/$($result.eligible_interfaces) ($($result.coverage_percent)%)" + - name: Test Classic COM failure cleanup contracts + run: | + cargo test -p dynwinrt failing_hresult_releases_written_interface_output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cargo test -p dynwinrt automation_validation_failure_cleans_other_owned_outputs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cargo test -p dynwinrt bstr_in_out_failure_cleans_unchanged_replaced_and_null_slots + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cargo test -p dynwinrt excep_info_deferred_fill_runs_once_and_cleans_on_every_failure_path - name: Check x86 Classic COM runtime run: cargo check -p jswinrt_rs --target i686-pc-windows-msvc @@ -161,3 +188,5 @@ jobs: bindings/js/dist/winrt.d.ts bindings/js/dist/com.js bindings/js/dist/com.d.ts + bindings/js/dist/com-unsafe.js + bindings/js/dist/com-unsafe.d.ts diff --git a/Cargo.lock b/Cargo.lock index 6977ad1b..3c494e51 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,8 @@ dependencies = [ "clap", "regex", "roxmltree", + "serde", + "serde_json", "windows", "windows-metadata", ] diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 467b672e..49c6d062 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -38,6 +38,8 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { 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.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynWinRTValue')) + t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'WinGUID')) t.is(typeof comRuntime.initializeCom, 'function') t.truthy(DynCom) t.truthy(DynComUnsafe) @@ -52,6 +54,8 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { "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(Object.prototype.hasOwnProperty.call(com, 'DynWinRTValue'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'WinGUID'), false);" + "assert.equal(typeof winrt.DynWinRtType, 'function');" + "assert.equal(typeof com.DynComVariant, 'function');" + "assert.equal(typeof com.initializeCom, 'function');" + @@ -75,6 +79,8 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { "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(Object.prototype.hasOwnProperty.call(com, 'DynWinRTValue'), false);" + + "assert.equal(Object.prototype.hasOwnProperty.call(com, 'WinGUID'), false);" + "assert.equal(typeof winrt.DynWinRtType, 'function');" + "assert.equal(typeof com.DynComVariant, 'function');" + "assert.equal(typeof com.initializeCom, 'function');" + @@ -130,6 +136,29 @@ test('DynCom rejects pointers after their TypedArray backing store is detached', t.regex(error.message, /backing ArrayBuffer is detached/) }) +test('Generated COM pointer helpers reject arbitrary numeric addresses', (t) => { + t.truthy(DynCom.safeDataPointer(Buffer.alloc(8))) + t.truthy(DynCom.safeDataPointer(new Uint8Array(8))) + t.throws( + () => + (DynCom.safeDataPointer as unknown as (value: bigint) => unknown)(0x1234n), + { message: /arbitrary numeric addresses/ }, + ) + + t.truthy(DynCom.safeWideStringPointer('wide')) + t.truthy(DynCom.safeAnsiStringPointer('ansi')) + t.throws( + () => + (DynCom.safeWideStringPointer as unknown as (value: bigint) => unknown)(0x1234n), + { message: /arbitrary numeric addresses/ }, + ) + t.throws( + () => + (DynCom.safeAnsiStringPointer as unknown as (value: number) => unknown)(0x1234), + { message: /arbitrary numeric addresses/ }, + ) +}) + test('DynCom rejects detached counted buffers and accepts typed backing widths', (t) => { const detached = new Uint8Array(16) structuredClone(detached.buffer, { transfer: [detached.buffer] }) diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index b5e6785c..50645a12 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -26,12 +26,11 @@ const comExports = new Set([ 'DynComSafeArray', 'DynComVariant', 'DynWinRtValue', - 'DynWinRTValue', 'WinGuid', - 'WinGUID', 'initializeCom', ]) -const comTypeExports = [...comExports, 'DynComSafeArrayBound'] +const comTypeAliases = ['DynWinRTValue', 'WinGUID'] +const comTypeExports = [...comExports, ...comTypeAliases, 'DynComSafeArrayBound'] const comUnsafeExports = new Set([ ...comExports, 'DynCom', @@ -43,7 +42,7 @@ const comUnsafeExports = new Set([ 'DynComUnsafe', 'DynComUnsafeInterface', ]) -const comUnsafeTypeExports = [...comUnsafeExports, 'DynComSafeArrayBound'] +const comUnsafeTypeExports = [...comUnsafeExports, ...comTypeAliases, 'DynComSafeArrayBound'] writeFacade( 'winrt', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 0f984682..3c2a4244 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -4,7 +4,7 @@ use napi::bindgen_prelude::{BigInt, Buffer, FromNapiValue, ToNapiValue, Unknown}; use napi::JsValue; use napi_derive::napi; -use windows::core::{Interface as _, GUID}; +use windows::core::{IUnknown, Interface as _, GUID}; use super::{DynWinRTValue, WinGUID, TABLE}; @@ -283,21 +283,34 @@ impl Drop for NativePointerOwner { fn co_create_instance(clsid: String, iid: &WinGUID) -> napi::Result { let parsed = windows::core::GUID::try_from(clsid.as_str()) .map_err(|_| napi::Error::from_reason(format!("Invalid CLSID: '{clsid}'")))?; - dynwinrt::com::co_create_instance(parsed, iid.0) + let mut value = dynwinrt::com::co_create_instance(parsed, iid.0) .map(DynWinRTValue::new) - .map_err(|error| napi::Error::from_reason(error.message())) + .map_err(|error| napi::Error::from_reason(error.message()))?; + value.bind_current_com_apartment()?; + Ok(value) } fn try_cast(value: &DynWinRTValue, iid: &WinGUID) -> napi::Result> { const E_NOINTERFACE: windows::core::HRESULT = windows::core::HRESULT(0x80004002u32 as i32); + value.ensure_existing_com_apartment()?; match value.0.cast(&iid.0) { - Ok(value) => Ok(Some(DynWinRTValue::new(value))), + Ok(value) => { + let mut value = DynWinRTValue::new(value); + value.bind_current_com_apartment()?; + Ok(Some(value)) + } Err(dynwinrt::Error::WindowsError(error)) if error.code() == E_NOINTERFACE => Ok(None), Err(error) => Err(napi::Error::from_reason(error.message())), } } +fn apartment_bound_com_object(value: IUnknown) -> napi::Result { + let mut value = DynWinRTValue::new(dynwinrt::WinRTValue::Object(value)); + value.bind_current_com_apartment()?; + Ok(value) +} + fn create_test_hwnd() -> napi::Result { use std::sync::atomic::{AtomicUsize, Ordering}; use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, WINDOW_EX_STYLE, WS_POPUP}; @@ -661,6 +674,33 @@ fn pointer(value: Unknown) -> napi::Result { )) } +fn safe_data_pointer(value: Unknown, nullable: bool) -> 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 matches!( + value_type, + sys::ValueType::napi_null | sys::ValueType::napi_undefined + ) { + return if nullable { + pointer(value) + } else { + Err(napi::Error::from_reason( + "safeDataPointer(): null requires an explicitly nullable parameter", + )) + }; + } + if uint8_array_info(env, raw)?.is_some() { + return pointer(value); + } + Err(napi::Error::from_reason( + "safeDataPointer(): expected Buffer or Uint8Array; arbitrary numeric addresses require @microsoft/dynwinrt/com/unsafe", + )) +} + fn wide_string_pointer(value: Unknown) -> napi::Result { use napi::sys; @@ -723,6 +763,45 @@ fn ansi_string_pointer(value: Unknown) -> napi::Result { pointer(value) } +fn safe_wide_string_pointer(value: Unknown, nullable: bool) -> napi::Result { + safe_string_pointer(value, nullable, true) +} + +fn safe_ansi_string_pointer(value: Unknown, nullable: bool) -> napi::Result { + safe_string_pointer(value, nullable, false) +} + +fn safe_string_pointer(value: Unknown, nullable: bool, wide: bool) -> 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 matches!( + value_type, + sys::ValueType::napi_null | sys::ValueType::napi_undefined + ) { + return if nullable { + pointer(value) + } else { + Err(napi::Error::from_reason( + "safe string pointer: null requires an explicitly nullable parameter", + )) + }; + } + if value_type == sys::ValueType::napi_string || uint8_array_info(env, raw)?.is_some() { + return if wide { + wide_string_pointer(value) + } else { + ansi_string_pointer(value) + }; + } + Err(napi::Error::from_reason( + "safe string pointer: expected string, Buffer, or Uint8Array; arbitrary numeric addresses require @microsoft/dynwinrt/com/unsafe", + )) +} + fn handle_value(value: Unknown) -> napi::Result { use napi::sys; @@ -789,8 +868,16 @@ fn adopt_com_pointer( Some(iid) => adopted .cast(&iid.0) .map(DynWinRTValue::new) - .map_err(|error| napi::Error::from_reason(error.message())), - None => Ok(DynWinRTValue::new(adopted)), + .map_err(|error| napi::Error::from_reason(error.message())) + .and_then(|mut value| { + value.bind_current_com_apartment()?; + Ok(value) + }), + None => { + let mut value = DynWinRTValue::new(adopted); + value.bind_current_com_apartment()?; + Ok(value) + } } } @@ -829,6 +916,10 @@ fn adopt_owned_com_pointer_bits( .cast(&iid.0) .map(DynWinRTValue::new) .map_err(|error| napi::Error::from_reason(error.message())) + .and_then(|mut value| { + value.bind_current_com_apartment()?; + Ok(value) + }) } fn unsafe_borrow_com_pointer(value: Unknown, iid: &WinGUID) -> napi::Result { @@ -849,6 +940,10 @@ fn borrow_com_pointer_bits( .cast(&iid.0) .map(DynWinRTValue::new) .map_err(|error| napi::Error::from_reason(error.message())) + .and_then(|mut value| { + value.bind_current_com_apartment()?; + Ok(value) + }) } fn adopt_co_task_mem_pointer(value: &mut DynWinRTValue) -> napi::Result { @@ -1359,6 +1454,11 @@ impl DynComMethodSig { Self(self.0.clone().add_in(typ.0.clone())) } + #[napi] + pub fn add_nullable_in(&self, typ: &DynComType) -> Self { + Self(self.0.clone().add_nullable_in(typ.0.clone())) + } + #[napi] pub fn add_out(&self, typ: &DynComType) -> Self { Self(self.0.clone().add_out(typ.0.clone())) @@ -1379,6 +1479,11 @@ impl DynComMethodSig { Self(self.0.clone().add_in_out(typ.0.clone())) } + #[napi] + pub fn add_nullable_in_out(&self, typ: &DynComType) -> Self { + Self(self.0.clone().add_nullable_in_out(typ.0.clone())) + } + #[napi] pub fn add_out_fill(&self, typ: &DynComType) -> Self { Self(self.0.clone().add_out_fill(typ.0.clone())) @@ -1640,6 +1745,7 @@ impl DynComDispatchInvokeResult { impl DynComMethodHandle { #[napi] pub fn get_string(&self, obj: &DynWinRTValue) -> napi::Result { + obj.ensure_com_apartment()?; let raw = obj .0 .as_object() @@ -1656,6 +1762,7 @@ impl DynComMethodHandle { obj: &DynWinRTValue, args: Vec<&DynWinRTValue>, ) -> napi::Result { + obj.ensure_com_apartment()?; if self.0.result_count() > 1 { return Err(napi::Error::from_reason( "invoke() cannot discard multiple COM results; use invokeAll()", @@ -1688,6 +1795,7 @@ impl DynComMethodHandle { obj: &DynWinRTValue, args: Vec<&DynWinRTValue>, ) -> napi::Result> { + obj.ensure_com_apartment()?; let raw = obj .0 .as_object() @@ -1716,6 +1824,7 @@ impl DynComMethodHandle { obj: &DynWinRTValue, args: Vec<&DynWinRTValue>, ) -> napi::Result { + obj.ensure_com_apartment()?; let raw = obj .0 .as_object() @@ -2130,7 +2239,7 @@ impl DynComVariant { 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)))) + value.map(apartment_bound_com_object).transpose() } _ => Err(napi::Error::from_reason( "VARIANT does not contain VT_UNKNOWN or VT_DISPATCH", @@ -2771,7 +2880,7 @@ impl DynComSafeArray { .map(|value| match value { dynwinrt::com::SafeArrayElementValue::Unknown(value) | dynwinrt::com::SafeArrayElementValue::Dispatch(value) => { - Ok(value.map(|value| DynWinRTValue::new(dynwinrt::WinRTValue::Object(value)))) + value.map(apartment_bound_com_object).transpose() } _ => Err(napi::Error::from_reason( "SAFEARRAY element type is not VT_UNKNOWN or VT_DISPATCH", @@ -3714,6 +3823,11 @@ impl DynCom { self::try_cast(value, iid) } + #[napi] + pub fn bind_com_object(value: &mut DynWinRTValue) -> napi::Result<()> { + value.bind_current_com_apartment() + } + #[napi] pub fn pointer( #[napi(ts_arg_type = "bigint | number | Buffer | Uint8Array | null | undefined")] @@ -3722,6 +3836,30 @@ impl DynCom { self::pointer(value) } + #[napi] + pub fn safe_data_pointer( + #[napi(ts_arg_type = "Buffer | Uint8Array | null | undefined")] value: Unknown, + nullable: Option, + ) -> napi::Result { + self::safe_data_pointer(value, nullable.unwrap_or(false)) + } + + #[napi] + pub fn safe_wide_string_pointer( + #[napi(ts_arg_type = "string | Buffer | Uint8Array | null | undefined")] value: Unknown, + nullable: Option, + ) -> napi::Result { + self::safe_wide_string_pointer(value, nullable.unwrap_or(false)) + } + + #[napi] + pub fn safe_ansi_string_pointer( + #[napi(ts_arg_type = "string | Buffer | Uint8Array | null | undefined")] value: Unknown, + nullable: Option, + ) -> napi::Result { + self::safe_ansi_string_pointer(value, nullable.unwrap_or(false)) + } + #[napi] pub fn null_buffer() -> DynWinRTValue { DynWinRTValue::from_com_value( @@ -4826,7 +4964,7 @@ mod tests { .as_slice(), &[1, 2, 3, 4, 5, 6, 7, 8] ); - value.release(); + value.release().unwrap(); 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"), @@ -5003,6 +5141,37 @@ mod tests { .is_ok()); } + #[test] + fn classic_com_objects_reject_cross_thread_use() { + let _ = dynwinrt::com::initialize_apartment(dynwinrt::com::ApartmentType::MultiThreaded); + let iid = WinGUID(windows::core::IUnknown::IID); + let value = co_create_instance("00021401-0000-0000-c000-000000000046".into(), &iid) + .expect("ShellLink activation"); + value + .ensure_com_apartment() + .expect("creating apartment must be accepted"); + + let cross_thread_iid = iid; + let (value, error, cast_error) = std::thread::spawn(move || { + let error = value + .ensure_com_apartment() + .expect_err("cross-thread COM use must fail"); + let cast_error = match value.cast(&cross_thread_iid) { + Ok(_) => panic!("QueryInterface must validate the source apartment first"), + Err(error) => error, + }; + (value, error, cast_error) + }) + .join() + .unwrap(); + + assert!(error.reason.contains("different apartment thread")); + assert!(cast_error.reason.contains("different apartment thread")); + value + .ensure_com_apartment() + .expect("ownership returned to the creating apartment"); + } + #[test] fn borrowed_handle_outputs_convert_null_and_pointer_bits_without_adoption() { let null = DynWinRTValue::from_com_result( diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 53e27e5f..7998b093 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -587,13 +587,69 @@ pub struct DynWinRTValue( Option, Option, Option, + Option, ); unsafe impl Send for DynWinRTValue {} unsafe impl Sync for DynWinRTValue {} +#[derive(Clone)] +struct ComApartmentBinding { + owner_thread: std::thread::ThreadId, +} + impl DynWinRTValue { fn new(value: dynwinrt::WinRTValue) -> Self { - Self(value, None, com::PointerProvenance::None, None, None, None) + Self( + value, + None, + com::PointerProvenance::None, + None, + None, + None, + None, + ) + } + + pub(crate) fn bind_current_com_apartment(&mut self) -> napi::Result<()> { + if self.0.as_object().is_none() { + return Err(napi::Error::from_reason( + "Classic COM apartment binding requires a managed COM object", + )); + } + let current = std::thread::current().id(); + match &self.6 { + Some(binding) if binding.owner_thread != current => Err(napi::Error::from_reason( + "Classic COM object is already bound to a different apartment thread", + )), + Some(_) => Ok(()), + None => { + self.6 = Some(ComApartmentBinding { + owner_thread: current, + }); + Ok(()) + } + } + } + + pub(crate) fn ensure_com_apartment(&self) -> napi::Result<()> { + let current = std::thread::current().id(); + match &self.6 { + Some(binding) if binding.owner_thread == current => Ok(()), + Some(_) => Err(napi::Error::from_reason( + "Classic COM object used from a different apartment thread", + )), + None => Err(napi::Error::from_reason( + "Classic COM object must be apartment-bound before native invocation", + )), + } + } + + pub(crate) fn ensure_existing_com_apartment(&self) -> napi::Result<()> { + if self.6.is_some() { + self.ensure_com_apartment() + } else { + Ok(()) + } } fn with_pointer_owner(value: dynwinrt::WinRTValue, owner: com::NativePointerOwner) -> Self { @@ -604,6 +660,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -615,6 +672,7 @@ impl DynWinRTValue { None, None, None, + None, ) } @@ -629,6 +687,7 @@ impl DynWinRTValue { None, Some(buffer), None, + None, ) } @@ -648,7 +707,10 @@ impl DynWinRTValue { } else { com::PointerProvenance::None }; - Self(value, None, provenance, None, None, None) + let apartment = matches!(value, dynwinrt::WinRTValue::Object(_)).then(|| ComApartmentBinding { + owner_thread: std::thread::current().id(), + }); + Self(value, None, provenance, None, None, None, apartment) } fn from_com_value( @@ -664,6 +726,7 @@ impl DynWinRTValue { None, None, Some(com::AutomationValue::new(dynwinrt::com::Value::Bstr(value))), + None, ), dynwinrt::com::Value::NativeStruct(value) => Self( dynwinrt::WinRTValue::Null, @@ -672,6 +735,7 @@ impl DynWinRTValue { Some(value), None, None, + None, ), dynwinrt::com::Value::NativeUnion(value) => Self( dynwinrt::WinRTValue::Null, @@ -682,6 +746,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new( dynwinrt::com::Value::NativeUnion(value), )), + None, ), dynwinrt::com::Value::Variant(value) => Self( dynwinrt::WinRTValue::Null, @@ -692,6 +757,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new(dynwinrt::com::Value::Variant( value, ))), + None, ), dynwinrt::com::Value::SafeArray(value) => Self( dynwinrt::WinRTValue::Null, @@ -702,6 +768,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new(dynwinrt::com::Value::SafeArray( value, ))), + None, ), dynwinrt::com::Value::PropVariant(value) => Self( dynwinrt::WinRTValue::Null, @@ -712,6 +779,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new( dynwinrt::com::Value::PropVariant(value), )), + None, ), dynwinrt::com::Value::DispatchParams(value) => Self( dynwinrt::WinRTValue::Null, @@ -722,6 +790,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new( dynwinrt::com::Value::DispatchParams(value), )), + None, ), dynwinrt::com::Value::ExcepInfo(value) => Self( dynwinrt::WinRTValue::Null, @@ -732,6 +801,7 @@ impl DynWinRTValue { Some(com::AutomationValue::new(dynwinrt::com::Value::ExcepInfo( value, ))), + None, ), dynwinrt::com::Value::Buffer(value) => Self( dynwinrt::WinRTValue::Null, @@ -740,6 +810,7 @@ impl DynWinRTValue { None, Some(value), None, + None, ), } } @@ -786,6 +857,15 @@ impl DynWinRTValue { impl Drop for DynWinRTValue { fn drop(&mut self) { + if self + .6 + .as_ref() + .is_some_and(|binding| binding.owner_thread != std::thread::current().id()) + { + let value = mem::replace(&mut self.0, dynwinrt::WinRTValue::Null); + mem::forget(value); + return; + } // 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 @@ -809,7 +889,10 @@ impl Drop for DynWinRTValue { #[napi] impl DynWinRTValue { #[napi] - pub fn release(&mut self) { + pub fn release(&mut self) -> napi::Result<()> { + if self.6.is_some() { + self.ensure_com_apartment()?; + } self.release_native_pointer_output(); self.0 = dynwinrt::WinRTValue::Null; self.1 = None; @@ -817,6 +900,8 @@ impl DynWinRTValue { self.3 = None; self.4 = None; self.5 = None; + self.6 = None; + Ok(()) } #[napi] @@ -1120,11 +1205,14 @@ impl DynWinRTValue { #[napi] pub fn cast(&self, iid: &WinGUID) -> napi::Result { + self.ensure_existing_com_apartment()?; let result = self .0 .cast(&iid.0) .map_err(|e| napi::Error::from_reason(format!("QueryInterface failed: {}", e.message())))?; - Ok(DynWinRTValue::new(result)) + let mut result = DynWinRTValue::new(result); + result.6 = self.6.clone(); + Ok(result) } #[napi] diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index ac51fb89..e79d55c4 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -546,6 +546,22 @@ pub enum Value { Buffer(ComBufferValue), } +fn is_null_input_value(value: &Value) -> bool { + match value { + Value::WinRt(WinRTValue::RawPtr(pointer)) => pointer.is_null(), + Value::WinRt(value) => value.is_null_object(), + Value::Bstr(value) => value.as_deref().is_none(), + Value::NativeStruct(_) + | Value::NativeUnion(_) + | Value::Variant(_) + | Value::SafeArray(_) + | Value::PropVariant(_) + | Value::DispatchParams(_) + | Value::ExcepInfo(_) + | Value::Buffer(_) => false, + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StringEncoding { Utf16, @@ -1441,6 +1457,10 @@ impl Type { } } + fn input_is_intrinsically_nullable(&self) -> bool { + self.abi.is_nullable_native_struct_pointer() || self.abi.is_nullable_bstr() + } + fn supports_direct_return(&self) -> bool { matches!(self.abi, ParameterType::Pointer) || matches!( @@ -1619,6 +1639,7 @@ struct ComBufferContract { struct ComParameterSpec { direction: ComParameterDirection, typ: Type, + nullable: bool, buffer: Option, } @@ -1626,6 +1647,7 @@ struct ComParameterSpec { struct ComArgumentPlan { typ: ParameterType, direction: ComParameterDirection, + nullable: bool, storage: ComArgumentStorage, input_index: Option, output_index: Option, @@ -1937,6 +1959,7 @@ impl ComCallPlan { arguments.push(ComArgumentPlan { typ: typ.abi, direction, + nullable: parameter.nullable, storage, input_index: parameter_input_index, output_index: parameter_output_index, @@ -2100,6 +2123,19 @@ impl ComCallPlan { args.len() ))); } + for (parameter_index, argument) in self.arguments.iter().enumerate() { + let Some(input_index) = argument.input_index else { + continue; + }; + if !argument.nullable + && !argument.typ.is_bstr() + && is_null_input_value(&args[input_index]) + { + return Err(invalid_argument(format!( + "required COM parameter {parameter_index} cannot be null" + ))); + } + } let mut prepared_buffers = (0..self.arguments.len()).map(|_| None).collect::>(); for (parameter_index, argument) in self.arguments.iter().enumerate() { @@ -3275,9 +3311,21 @@ impl MethodSignature { } pub fn add_in(mut self, typ: Type) -> Self { + let nullable = typ.input_is_intrinsically_nullable(); + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::In, + typ, + nullable, + buffer: None, + }); + self + } + + pub fn add_nullable_in(mut self, typ: Type) -> Self { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::In, typ, + nullable: true, buffer: None, }); self @@ -3287,6 +3335,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::Out, typ, + nullable: false, buffer: None, }); self @@ -3296,15 +3345,28 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::OptionalOut, typ, + nullable: false, buffer: None, }); self } pub fn add_in_out(mut self, typ: Type) -> Self { + let nullable = typ.input_is_intrinsically_nullable(); + self.parameters.push(ComParameterSpec { + direction: ComParameterDirection::InOut, + typ, + nullable, + buffer: None, + }); + self + } + + pub fn add_nullable_in_out(mut self, typ: Type) -> Self { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::InOut, typ, + nullable: true, buffer: None, }); self @@ -3314,6 +3376,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::OutFill, typ, + nullable: false, buffer: None, }); self @@ -3330,6 +3393,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::InputBuffer, typ: Type::pointer(), + nullable: false, buffer: Some(ComBufferContract { element, relation: ComBufferRelation::Input { @@ -3350,6 +3414,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::InputBuffer, typ: Type::pointer(), + nullable: false, buffer: Some(ComBufferContract { element: BufferElementPlan::string_pointer(encoding), relation: ComBufferRelation::Input { @@ -3374,6 +3439,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::CallerOutputBuffer, typ: Type::pointer(), + nullable: false, buffer: Some(ComBufferContract { element, relation: ComBufferRelation::CallerCapacity { @@ -3397,6 +3463,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::CallerOutputBuffer, typ: Type::pointer(), + nullable: false, buffer: Some(ComBufferContract { element, relation: ComBufferRelation::EnumeratorNext { @@ -3422,6 +3489,7 @@ impl MethodSignature { self.parameters.push(ComParameterSpec { direction: ComParameterDirection::CalleeAllocatedBuffer, typ, + nullable: false, buffer: Some(ComBufferContract { element, relation: ComBufferRelation::CalleeAllocated { @@ -3562,6 +3630,7 @@ impl MethodSignature { fn build(self, vtable_index: usize) -> result::Result { validate_automation_contracts(&self.parameters, &self.return_plan)?; + validate_in_out_ownership(&self.parameters)?; validate_buffer_contracts(&self.parameters)?; let enumerator_buffers = self .parameters @@ -3628,6 +3697,20 @@ impl MethodSignature { } } +fn validate_in_out_ownership(parameters: &[ComParameterSpec]) -> result::Result<()> { + for parameter in parameters { + if parameter.direction == ComParameterDirection::InOut + && !parameter.typ.abi.is_bstr() + && parameter.typ.output_cleanup() != OutputCleanup::None + { + return Err(invalid_argument( + "owned COM InOut parameters require an explicit replacement and cleanup contract; only dedicated BSTR replacement is currently supported", + )); + } + } + Ok(()) +} + fn validate_automation_contracts( parameters: &[ComParameterSpec], return_plan: &ComReturnPlan, @@ -4481,6 +4564,7 @@ mod tests { } static VOID_CALLS: AtomicU32 = AtomicU32::new(0); + static POINTER_INPUT_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); @@ -4600,6 +4684,14 @@ mod tests { windows_core::HRESULT(0) } + unsafe extern "system" fn observe_pointer_input( + _this: *mut c_void, + _value: *mut c_void, + ) -> windows_core::HRESULT { + POINTER_INPUT_CALLS.fetch_add(1, Ordering::Relaxed); + windows_core::HRESULT(0) + } + unsafe extern "system" fn succeed_without_writing_native_pointer( _this: *mut c_void, _value: *mut *mut c_void, @@ -8525,6 +8617,63 @@ mod tests { assert_eq!(plan.results[1].failure_cleanup, OutputCleanup::ComRelease); } + #[test] + fn required_pointer_nullability_is_enforced_before_dispatch() { + POINTER_INPUT_CALLS.store(0, Ordering::Relaxed); + let required = MethodSignature::new(&MetadataTable::new()) + .add_in(Type::pointer()) + .build(0) + .unwrap(); + let nullable = MethodSignature::new(&MetadataTable::new()) + .add_nullable_in(Type::pointer()) + .build(0) + .unwrap(); + let vtable = [observe_pointer_input as *mut c_void]; + let mut object = FakeComObject { + vtable: vtable.as_ptr(), + }; + let null = [Value::WinRt(WinRTValue::RawPtr(std::ptr::null_mut()))]; + + let error = required + .plan + .invoke_values((&mut object as *mut FakeComObject).cast(), &null) + .expect_err("required pointer must reject null before dispatch"); + assert!(error.message().contains("cannot be null")); + assert_eq!(POINTER_INPUT_CALLS.load(Ordering::Relaxed), 0); + + nullable + .plan + .invoke_values((&mut object as *mut FakeComObject).cast(), &null) + .expect("explicitly nullable pointer must reach native dispatch"); + assert_eq!(POINTER_INPUT_CALLS.load(Ordering::Relaxed), 1); + } + + #[test] + fn unsupported_owning_in_out_contracts_fail_registration() { + let table = MetadataTable::new(); + for typ in [ + Type::owned_com_pointer(), + Type::co_task_mem_pointer(), + Type::bstr_pointer(), + Type::winrt(table.interface(GUID::from_u128(0x00000000_0000_0000_c000_000000000046))), + ] { + let error = MethodSignature::new(&table) + .add_in_out(typ) + .build(0) + .expect_err("owning InOut must not silently lose cleanup"); + assert!(error.message().contains("replacement and cleanup")); + } + + MethodSignature::new(&table) + .add_in_out(Type::bstr()) + .build(0) + .expect("dedicated BSTR replacement remains supported"); + MethodSignature::new(&table) + .add_in_out(Type::pointer()) + .build(0) + .expect("explicit unclassified borrowed pointer InOut remains available"); + } + #[test] fn multi_output_guid_uses_full_sized_storage() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 580e5c14..0c8642ff 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -301,7 +301,17 @@ impl ValueTypeData { &[arg(&obj_raw), arg(data_ref), arg(&(&mut out))], ) }; - hr.ok()?; + if hr.is_err() { + if !out.is_null() { + drop(unsafe { windows_core::IUnknown::from_raw(out) }); + } + hr.ok()?; + } + if out.is_null() { + return Err(windows_core::Error::from_hresult(windows_core::HRESULT( + 0x80004003u32 as i32, + ))); + } Ok(unsafe { windows_core::IUnknown::from_raw(out as _) }) } } diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 10a0da2c..f69af1ae 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -1431,7 +1431,12 @@ impl Method { obj, &mut out as *mut _ as *mut std::ffi::c_void, ); - hr.ok()?; + if hr.is_err() { + if !out.is_null() { + drop(unsafe { windows_core::IUnknown::from_raw(out) }); + } + hr.ok()?; + } if out.is_null() { Ok(WinRTValue::Null) } else { @@ -2004,6 +2009,45 @@ mod tests { calls: AtomicU32, } + #[repr(C)] + struct FailureGetterObject { + vtable: *const *mut std::ffi::c_void, + output: *mut std::ffi::c_void, + } + + #[repr(C)] + struct TrackedUnknown { + vtable: *const *mut std::ffi::c_void, + } + + static TRACKED_RELEASES: AtomicU32 = AtomicU32::new(0); + + unsafe extern "system" fn tracked_query_interface( + _this: *mut std::ffi::c_void, + _iid: *const windows_core::GUID, + _object: *mut *mut std::ffi::c_void, + ) -> windows_core::HRESULT { + windows_core::HRESULT(0x80004002u32 as i32) + } + + unsafe extern "system" fn tracked_add_ref(_this: *mut std::ffi::c_void) -> u32 { + 2 + } + + unsafe extern "system" fn tracked_release(_this: *mut std::ffi::c_void) -> u32 { + TRACKED_RELEASES.fetch_add(1, Ordering::SeqCst); + 0 + } + + unsafe extern "system" fn fail_after_writing_object( + this: *mut std::ffi::c_void, + output: *mut *mut std::ffi::c_void, + ) -> windows_core::HRESULT { + let object = unsafe { &*(this.cast::()) }; + unsafe { *output = object.output }; + windows_core::HRESULT(0x80004005u32 as i32) + } + unsafe extern "system" fn increment_struct_first_field( this: *mut std::ffi::c_void, value: *mut i32, @@ -2076,6 +2120,35 @@ mod tests { assert_eq!(object.calls.load(Ordering::Relaxed), 0); } + #[test] + fn object_fast_getter_releases_failure_written_output() { + TRACKED_RELEASES.store(0, Ordering::SeqCst); + let output_vtable = Box::new([ + tracked_query_interface as *mut std::ffi::c_void, + tracked_add_ref as *mut std::ffi::c_void, + tracked_release as *mut std::ffi::c_void, + ]); + let mut output = TrackedUnknown { + vtable: output_vtable.as_ptr(), + }; + let getter_vtable = Box::new([fail_after_writing_object as *mut std::ffi::c_void]); + let mut getter = FailureGetterObject { + vtable: getter_vtable.as_ptr(), + output: (&mut output as *mut TrackedUnknown).cast(), + }; + let table = MetadataTable::new(); + let method = AbiMethodSignature::new(&table) + .add_out_type(ParameterType::winrt(table.object())) + .build(0); + + let error = method + .call_getter_object((&mut getter as *mut FailureGetterObject).cast()) + .expect_err("failure HRESULT must not produce an object"); + + assert_eq!(error.code().0, 0x80004005u32 as i32); + assert_eq!(TRACKED_RELEASES.load(Ordering::SeqCst), 1); + } + #[test] fn rejects_wrong_native_pointer_value_before_native_call() { let table = MetadataTable::new(); diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index bcfc41f9..861a0a9d 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -370,10 +370,13 @@ HRESULT methods retain the normal throw-or-`void` behavior. **Problem:** A valid COM reference is not necessarily callable from every thread. STA objects require the owning apartment or a marshaled proxy. -Required support includes: +Generated Classic COM JavaScript wrappers now record the creating thread and +reject wrong-thread invocation or explicit release. A wrong-thread finalizer +leaks rather than calling `Release` in the wrong apartment. WinRT values remain +unbound and retain their existing behavior. + +Remaining apartment work includes: -- tracking the apartment where a value was acquired; -- preventing unsafe cross-thread calls; - agile-object detection; - Global Interface Table or COM marshaling integration; and - deterministic callback dispatch to the correct apartment. @@ -1178,10 +1181,14 @@ 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 +**5,560 / 7,929 = 70.122336%**. The result remains above the 70% target without admitting any creator-owned, destroyable, InOut, undocumented, optional, or `HWND**` shape. +CI reproduces this number with `dynwinrt-codegen com-census --json` and fails +if the denominator changes, complete generation drops below 5,560, or coverage +falls below 70%. + ## Public-code frequency snapshot There is no authoritative Microsoft ranking of COM interface usage. The table @@ -1317,7 +1324,7 @@ hardware, and whether it adds a distinct ABI shape. Eleven unique Classic COM interfaces are currently exercised. Core live tests are in [`crates/dynwinrt/src/com.rs`](../../crates/dynwinrt/src/com.rs). The eleven Node -runners plus the counted-buffer runner (twelve total) are in +runners, the counted-buffer runner, and two Automation runners (fourteen total) are in [`tests/e2e/runners/com`](../../tests/e2e/runners/com) and are generated and executed by [`tests/e2e/e2e_test.ps1`](../../tests/e2e/e2e_test.ps1). diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index ba530458..f27f45d1 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -89,6 +89,15 @@ npx dynwinrt-codegen generate ` 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. +To reproduce the complete-interface coverage census: + +```powershell +npx dynwinrt-codegen com-census --winmd $winmd --json +``` + +The command prints stable JSON containing eligible, complete, and incomplete +interface counts plus the exact percentage. + ### 4.2 Generate files ```powershell @@ -112,6 +121,11 @@ Generated output is placed in `generated/com/`. Internally, the `.js` files impo `@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`. +The generator records files per top-level COM root in +`generated/com/.dynwinrt-com-manifest.json`. Regenerating the same root removes +files it no longer owns, while files shared with or generated by other roots +remain intact. + ### 4.3 Customize the runtime path For development repositories or packaging scenarios, specify: @@ -237,6 +251,10 @@ Do not treat every pointer as a Buffer: - 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. +- Safe generated data and string pointers reject arbitrary numeric addresses. + Numeric addresses are available only through the explicit `/com/unsafe` + pointer APIs. Numeric handle values remain supported because the value is + the handle itself rather than a dereferenced address. ## 7. Lifetime and ownership diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 20e86376..8cc52f61 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -34,6 +34,7 @@ $comShellDir = Join-Path $comBindingsDir "shell" $comInteropDir = Join-Path $comBindingsDir "interop" $comWicDir = Join-Path $comBindingsDir "wic" $comStreamDir = Join-Path $comBindingsDir "stream" +$comAutomationDir = Join-Path $comBindingsDir "automation" $comSmtcDir = Join-Path $comBindingsDir "smtc" [string[]]$cargoProfileArgs = @( if ($CargoProfile -eq "release") { @@ -260,6 +261,13 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM stream generation failed"; exit 1 } + & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + --winmd $win32Winmd ` + --class-name "Windows.Win32.System.Com.IDispatch,Windows.Win32.System.Ole.IEnumVARIANT" ` + --output $comAutomationDir ` + --import-name $comRuntimeImport + if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM Automation generation failed"; exit 1 } + & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` --namespace Windows.Media ` --class-name SystemMediaTransportControls ` @@ -326,6 +334,8 @@ if ("com" -in $Lang) { "file-open-dialog.mjs", "wic-imaging-factory.mjs", "sequential-stream-buffer.mjs", + "automation-values.mjs", + "automation-dispatch.mjs", "dtm.mjs", "smtc.mjs" ) diff --git a/tests/e2e/runners/com/automation-dispatch.mjs b/tests/e2e/runners/com/automation-dispatch.mjs new file mode 100644 index 00000000..9e19503f --- /dev/null +++ b/tests/e2e/runners/com/automation-dispatch.mjs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from "node:assert/strict"; +import { + DynComDispatchParams, + initializeCom, +} from "../../../../bindings/js/dist/com.js"; +import { DynComUnsafe } from "../../../../bindings/js/dist/com-unsafe.js"; +import { + IDispatch, + IID_IDispatch, +} from "../../e2e_generated/com/automation/com/IDispatch.js"; +import { IEnumVARIANT } from "../../e2e_generated/com/automation/com/IEnumVARIANT.js"; +import { ISequentialStream } from "../../e2e_generated/com/stream/com/ISequentialStream.js"; + +const CLSID_SHELL_APPLICATION = "13709620-c279-11ce-a49e-444553540000"; +const DISPATCH_PROPERTYGET = 2; +const IID_NULL = Buffer.alloc(16); + +initializeCom(1); + +const raw = DynComUnsafe.coCreateInstance( + CLSID_SHELL_APPLICATION, + IID_IDispatch, +); +const shell = IDispatch._fromNative(raw); +raw.release(); + +function invokeMember(dispatch, dispid, flags, name) { + const params = new DynComDispatchParams([]); + try { + const result = dispatch.invoke(dispid, IID_NULL, 0, flags, params, { + result: true, + excepInfo: true, + argErr: true, + }).result; + assert.ok(result, `${name} did not return a VARIANT`); + return result; + } finally { + params.release(); + } +} + +function namedMember(dispatch, name, flags = DISPATCH_PROPERTYGET) { + const [dispid] = dispatch.getIDsOfNames(IID_NULL, [name], 0); + return invokeMember(dispatch, dispid, flags, name); +} + +try { + assert.throws( + () => ISequentialStream._fromNative(shell._obj), + /QueryInterface failed/, + ); + assert.ok(shell.getTypeInfoCount() >= 1); + + const application = namedMember(shell, "Application"); + try { + assert.equal(application.kind, "dispatch"); + const object = application.toInterface(); + assert.ok(object && !object.isNull()); + object.release(); + } finally { + application.release(); + } + + const windows = namedMember(shell, "Windows", 1); + let windowsDispatch; + try { + const object = windows.toInterface(); + assert.ok(object); + try { + windowsDispatch = IDispatch._fromNative(object); + } finally { + object.release(); + } + } finally { + windows.release(); + } + try { + const enumeratorValue = invokeMember(windowsDispatch, -4, 3, "_NewEnum"); + let enumerator; + try { + const object = enumeratorValue.toInterface(); + assert.ok(object); + try { + enumerator = IEnumVARIANT._fromNative(object); + } finally { + object.release(); + } + } finally { + enumeratorValue.release(); + } + try { + const values = enumerator.next(1); + for (const value of values) value.release(); + enumerator.reset(); + } finally { + enumerator.release(); + } + } finally { + windowsDispatch.release(); + } + + const params = new DynComDispatchParams([]); + try { + assert.throws( + () => shell.invoke(0x7fffffff, IID_NULL, 0, DISPATCH_PROPERTYGET, params), + (error) => typeof error.hresult === "number" && error.hresult < 0, + ); + } finally { + params.release(); + } +} finally { + shell.release(); +} + +console.log("automation-dispatch ok"); diff --git a/tests/e2e/runners/com/automation-values.mjs b/tests/e2e/runners/com/automation-values.mjs new file mode 100644 index 00000000..9d457c8b --- /dev/null +++ b/tests/e2e/runners/com/automation-values.mjs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from "node:assert/strict"; +import { + DynComPropVariant, + DynComSafeArray, + DynComVariant, + WinGuid, + initializeCom, +} from "../../../../bindings/js/dist/com.js"; + +initializeCom(1); + +const variant = DynComVariant.bstr("embedded\0automation"); +const array = DynComSafeArray.variant( + [DynComVariant.i32(7), variant], + [{ lowerBound: -1, length: 2 }], +); +const property = DynComPropVariant.guid( + WinGuid.parse("00000000-0000-0000-c000-000000000046"), +); + +try { + assert.equal(variant.kind, "bstr"); + assert.equal(variant.toStringValue(), "embedded\0automation"); + assert.equal(array.elementType, "variant"); + assert.deepEqual(array.bounds, [{ lowerBound: -1, length: 2 }]); + const values = array.toVariants(); + try { + assert.equal(values[0].toNumber(), 7); + assert.equal(values[1].toStringValue(), "embedded\0automation"); + } finally { + for (const value of values) value.release(); + } + assert.equal(property.kind, "guid"); +} finally { + property.release(); + array.release(); + variant.release(); +} + +console.log("automation-values ok"); diff --git a/tools/dynwinrt-codegen/Cargo.toml b/tools/dynwinrt-codegen/Cargo.toml index b41fc056..498ca1a9 100644 --- a/tools/dynwinrt-codegen/Cargo.toml +++ b/tools/dynwinrt-codegen/Cargo.toml @@ -12,6 +12,8 @@ windows-metadata = "0.59.0" clap = { version = "4", features = ["derive"] } roxmltree = "0.20" regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" [dev-dependencies] regex = "1" diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index 9915df5e..f215fe06 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -99,15 +99,17 @@ fn render_coclass_files( primary_interface.name )); js.push_str(&format!( - " constructor() {{\n super(DynCom.coCreateInstance(CLSID_{name}, IID_{}));\n }}\n", + " constructor() {{\n const obj = DynCom.coCreateInstance(CLSID_{name}, IID_{});\n try {{\n super(obj);\n }} finally {{\n obj.release();\n }}\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", + " static _fromNative(obj) {{\n const cast = obj.cast(IID_{});\n DynCom.bindComObject(cast);\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( + " as(InterfaceClass) {\n return InterfaceClass._fromNative(this._obj);\n }\n", + ); + js.push_str(" tryAs(InterfaceClass) {\n const obj = DynCom.tryCast(this._obj, InterfaceClass.IID);\n if (obj === null) return null;\n try {\n return InterfaceClass._fromNative(obj);\n } finally {\n obj.release();\n }\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"); @@ -264,11 +266,15 @@ fn render_js(meta: &ProjectedComInterface) -> String { 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"); + let wrap_owned = format!("_wrap{}Owned", meta.name); out.push_str(&format!( - " static _fromNative(obj) {{ return Object.assign(Object.create({}.prototype), {{ _obj: obj }}); }}\n", + " _obj;\n constructor(obj) {{\n const cast = obj.cast(IID_{});\n DynCom.bindComObject(cast);\n this._obj = cast;\n }}\n", meta.name )); + out.push_str(&format!( + " static _fromNative(obj) {{ return {wrap_owned}(obj.cast(IID_{})); }}\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 => {} @@ -280,7 +286,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 * `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)); + out.push_str(&format!(" static create() {{\n const factory = DynWinRtValue.activationFactory('{full}');\n const _obj = factory.cast(IID_{});\n return {wrap_owned}(_obj);\n }}\n", meta.name)); } } let mut emitted_groups = std::collections::HashSet::new(); @@ -351,6 +357,10 @@ fn render_js(meta: &ProjectedComInterface) -> String { } } out.push_str("}\n"); + out.push_str(&format!( + "function {wrap_owned}(obj) {{\n DynCom.bindComObject(obj);\n return Object.assign(Object.create({}.prototype), {{ _obj: obj }});\n}}\n", + meta.name + )); out } @@ -366,10 +376,24 @@ fn build_method_sig_js(method: &ProjectedComMethod) -> String { continue; } match param.direction { - ComParamDirection::In => parts.push(format!(".addIn({})", param_abi_type_js(param))), - ComParamDirection::InOut => { - parts.push(format!(".addInOut({})", param_abi_type_js(param))) - } + ComParamDirection::In => parts.push(format!( + ".{}({})", + if param.nullable { + "addNullableIn" + } else { + "addIn" + }, + param_abi_type_js(param) + )), + ComParamDirection::InOut => parts.push(format!( + ".{}({})", + if param.nullable { + "addNullableInOut" + } else { + "addInOut" + }, + param_abi_type_js(param) + )), ComParamDirection::OutStringBuffer => parts.push(".addIn(DynCom.pointerType())".into()), ComParamDirection::Out => { @@ -1616,14 +1640,14 @@ fn render_dts(meta: &ProjectedComInterface) -> String { for (name, kind) in collect_pointer_aliases(meta) { 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::DataPointer => out.push_str(&format!("/** Retained native data storage. The backing-store address is passed for the duration of the call; arbitrary numeric addresses require the explicit unsafe runtime. */\nexport type {name} = Buffer | Uint8Array;\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.", + StringEncoding::Wide => "Pass a JS `string` (encoded automatically), or a `Buffer`/`Uint8Array` holding UTF-16LE bytes including the NUL terminator. Arbitrary numeric addresses require the explicit unsafe runtime.", + StringEncoding::Ansi => "Pass an ASCII JS `string` (encoded automatically), or a `Buffer`/`Uint8Array` holding explicitly ANSI-encoded bytes including the NUL terminator. Non-ASCII text must use pre-encoded bytes; arbitrary numeric addresses require the explicit unsafe runtime.", }; out.push_str(&format!( - "/** Win32 NUL-terminated string pointer. {description} */\nexport type {name} = string | Buffer | Uint8Array | bigint;\n" + "/** Win32 NUL-terminated string pointer. {description} */\nexport type {name} = string | Buffer | Uint8Array;\n" )); } } 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 dce08a24..4ec90f69 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -46,6 +46,14 @@ fn renderer_api_accepts_only_projected_ir() { .dts .contains("export declare const IID_ITest: WinGuid;") ); + assert!(output.js.contains("const cast = obj.cast(IID_ITest);")); + assert!( + output + .js + .contains("static _fromNative(obj) { return _wrapITestOwned(obj.cast(IID_ITest)); }") + ); + assert!(output.js.contains("function _wrapITestOwned(obj)")); + assert!(output.js.contains("DynCom.bindComObject")); } #[test] @@ -247,7 +255,7 @@ fn renderer_allows_null_only_for_nullable_bstr_inputs() { assert!( output .js - .contains("new DynComMethodSig().addIn(DynCom.nullableBstrType())") + .contains("new DynComMethodSig().addNullableIn(DynCom.nullableBstrType())") ); assert!( output @@ -2111,10 +2119,8 @@ 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 = string | Buffer | Uint8Array | bigint;")); - assert!( - dts.contains("Pass a JS `string` (encoded automatically via DynCom.wideStringPointer)") - ); + assert!(dts.contains("export type PWSTR = string | Buffer | Uint8Array;")); + assert!(dts.contains("Pass a JS `string` (encoded automatically)")); assert!( dts.contains("setOverlayIcon(hwnd: HWND | Buffer | Uint8Array, description: PWSTR): void;") ); @@ -2127,7 +2133,7 @@ fn handle_value_arg_accepts_buffer_and_string_pointer_keeps_buffer() { "HWND arg must use DynCom.handleValue:\n{js}" ); assert!(!js.contains("function _handleArg(")); - assert!(js.contains("DynCom.wideStringPointer(description)")); + assert!(js.contains("DynCom.safeWideStringPointer(description)")); } #[test] @@ -2154,9 +2160,9 @@ fn data_pointer_alias_does_not_read_buffer_contents_as_a_handle() { let js = render_js(&iface, None); let dts = render_dts(&iface, None); - assert!(dts.contains("export type PSID = bigint | number;")); - assert!(dts.contains("addUserSid(userSid: PSID | Buffer | Uint8Array): void;")); - assert!(js.contains("DynCom.pointer(userSid)")); + assert!(dts.contains("export type PSID = Buffer | Uint8Array;")); + assert!(dts.contains("addUserSid(userSid: PSID): void;")); + assert!(js.contains("DynCom.safeDataPointer(userSid)")); assert!(!js.contains("handleValue(userSid)")); } @@ -2704,7 +2710,7 @@ fn caller_supplied_riid_output_is_adopted() { assert!( output .dts - .contains("bindToHandler(pbc: bigint | Buffer, riid: string): DynWinRtValue;") + .contains("bindToHandler(pbc: Buffer | Uint8Array, 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 2c23144f..eb46267b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -107,11 +107,6 @@ pub(super) fn input_type_dts(typ: &ComType) -> String { kind: PointerAliasKind::HandleValue, .. } if name == "HWND" => format!("{name} | Buffer | Uint8Array"), - ComType::PointerAlias { - name, - kind: PointerAliasKind::DataPointer, - .. - } => format!("{name} | Buffer | Uint8Array"), _ => type_dts(typ), } } @@ -139,7 +134,7 @@ pub(super) fn type_dts(typ: &ComType) -> String { ComType::HString => "string".into(), ComType::Enum { name, .. } => name.clone(), ComType::ScalarAlias { name, .. } => name.clone(), - ComType::RawPointer => "bigint | Buffer".into(), + ComType::RawPointer => "Buffer | Uint8Array".into(), ComType::PointerAlias { name, .. } => name.clone(), ComType::NativePod { layout } | ComType::NativePodPointer { layout } => layout.name.clone(), ComType::NativeUnionPointer { layout } => layout.name.clone(), @@ -225,7 +220,7 @@ 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 => format!("DynCom.pointer({variable})"), + ComType::RawPointer => format!("DynCom.safeDataPointer({variable})"), ComType::Bstr => format!("DynCom.bstr({variable})"), ComType::PointerAlias { name, @@ -237,12 +232,19 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { ComType::PointerAlias { kind: PointerAliasKind::StringPointer(StringEncoding::Wide), .. - } => format!("DynCom.wideStringPointer({variable})"), + } => format!("DynCom.safeWideStringPointer({variable})"), ComType::PointerAlias { kind: PointerAliasKind::StringPointer(StringEncoding::Ansi), .. - } => format!("DynCom.ansiStringPointer({variable})"), - ComType::PointerAlias { .. } => format!("DynCom.pointer({variable})"), + } => format!("DynCom.safeAnsiStringPointer({variable})"), + ComType::PointerAlias { + kind: PointerAliasKind::DataPointer, + .. + } => format!("DynCom.safeDataPointer({variable})"), + ComType::PointerAlias { + kind: PointerAliasKind::HandleValue, + .. + } => format!("DynCom.pointer(DynCom.handleValue({variable}))"), ComType::NativePod { layout } | ComType::NativePodPointer { layout } => format!( "DynCom.nativeStruct({}, {variable})", native_pod_layout_js(layout) @@ -414,7 +416,7 @@ fn unwrap_array_result_js( ) -> String { if let Some(interface) = interface { return format!( - "Array.from(DynCom.takeComArray({expression}), value => {}._fromNative(value))", + "Array.from(DynCom.takeComArray({expression}), value => {{ try {{ return {}._fromNative(value); }} finally {{ value.release(); }} }})", interface.name ); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 4884c333..ee9ddf22 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -2058,13 +2058,15 @@ fn map_count_relation( } fn map_constness(constness: RawConstness, const_attribute: bool) -> Constness { - if const_attribute { + if constness == RawConstness::Mixed { + Constness::Unspecified + } else if const_attribute { Constness::Const } else { match constness { RawConstness::Const => Constness::Const, RawConstness::Mutable => Constness::Mutable, - RawConstness::Unspecified => Constness::Unspecified, + RawConstness::Mixed | RawConstness::Unspecified => Constness::Unspecified, } } } @@ -2076,7 +2078,7 @@ fn buffer_constness(raw: &RawComParam) -> Constness { match raw.typ.constness { RawConstness::Const => return Constness::Const, RawConstness::Mutable => return Constness::Mutable, - RawConstness::Unspecified => {} + RawConstness::Mixed | RawConstness::Unspecified => {} } if raw.typ.pointer_depth > 0 { return Constness::Unspecified; @@ -2208,6 +2210,18 @@ fn is_explicit_pointer_alias(namespace: &str, name: &str) -> bool { mod tests { use super::*; + #[test] + fn const_attribute_does_not_erase_mixed_pointer_qualifiers() { + assert_eq!( + map_constness(RawConstness::Mixed, true), + Constness::Unspecified + ); + assert_eq!( + map_constness(RawConstness::Unspecified, true), + Constness::Const + ); + } + fn win32_winmd() -> Option { std::env::var("DYNWINRT_WIN32_WINMD") .ok() diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index ec4892ca..477283c7 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -11,6 +11,7 @@ use crate::types::TypeMeta; pub enum RawConstness { Const, Mutable, + Mixed, Unspecified, } @@ -399,6 +400,18 @@ pub fn parse_com_interface( parse_com_interface_from_index(&index, namespace, name) } +pub fn parse_all_com_interfaces(winmd_paths: &str) -> Option> { + let index = crate::meta::load_index(winmd_paths)?; + Some( + index + .all() + .filter_map(|definition| { + parse_com_interface_from_index(&index, definition.namespace(), definition.name()) + }) + .collect(), + ) +} + pub fn parse_com_coclass( winmd_paths: &str, namespace: &str, @@ -451,43 +464,29 @@ fn parse_com_interface_from_index( return None; } - let mut base_chain = Vec::new(); - let mut current = (namespace.to_string(), name.to_string()); - let mut root = None; - for _ in 0..32 { - let current_def = index.get(¤t.0, ¤t.1).next()?; - let base = match current_def.interface_impls().next()?.interface(&[]) { - windows_metadata::Type::Name(name) => (name.namespace, name.name), - _ => return None, - }; - match base.1.as_str() { - "IUnknown" => { - root = Some((true, 3)); - base_chain.push(( - "Windows.Win32.System.Com".to_string(), - "IUnknown".to_string(), - 0, - )); - break; - } - "IInspectable" => { - root = Some((false, 6)); - base_chain.push(( - "Windows.Foundation".to_string(), - "IInspectable".to_string(), - 0, - )); - break; - } - _ => { - let base_def = index.get(&base.0, &base.1).next()?; - let count = base_def.methods().count(); - base_chain.push((base.0.clone(), base.1.clone(), count)); - current = base; - } - } - } - let (is_iunknown_rooted, root_offset) = root?; + let (is_iunknown_rooted, root_offset, base_chain) = + resolve_com_base_chain(namespace, name, |current_namespace, current_name| { + let current_def = index.get(current_namespace, current_name).next()?; + current_def + .interface_impls() + .map(|implementation| match implementation.interface(&[]) { + windows_metadata::Type::Name(name) => { + let method_count = + if matches!(name.name.as_str(), "IUnknown" | "IInspectable") { + 0 + } else { + index + .get(&name.namespace, &name.name) + .next()? + .methods() + .count() + }; + Some((name.namespace, name.name, method_count)) + } + _ => None, + }) + .collect::>>() + })?; let own_methods_start = root_offset + base_chain .iter() @@ -509,6 +508,7 @@ fn parse_com_interface_from_index( methods.append(&mut base_methods); raw_methods.append(&mut base_raw_methods); } + if slot != own_methods_start { return None; } @@ -545,6 +545,48 @@ fn parse_com_interface_from_index( }) } +fn resolve_com_base_chain( + namespace: &str, + name: &str, + mut direct_bases: impl FnMut(&str, &str) -> Option>, +) -> Option<(bool, usize, Vec<(String, String, usize)>)> { + let mut base_chain = Vec::new(); + let mut current = (namespace.to_string(), name.to_string()); + let mut visited = std::collections::BTreeSet::new(); + for _ in 0..32 { + if !visited.insert(current.clone()) { + return None; + } + let bases = direct_bases(¤t.0, ¤t.1)?; + let [base] = bases.as_slice() else { + return None; + }; + match base.1.as_str() { + "IUnknown" => { + base_chain.push(( + "Windows.Win32.System.Com".to_string(), + "IUnknown".to_string(), + 0, + )); + return Some((true, 3, base_chain)); + } + "IInspectable" => { + base_chain.push(( + "Windows.Foundation".to_string(), + "IInspectable".to_string(), + 0, + )); + return Some((false, 6, base_chain)); + } + _ => { + base_chain.push(base.clone()); + current = (base.0.clone(), base.1.clone()); + } + } + } + None +} + fn parse_com_coclass_from_index( index: &reader::Index, namespace: &str, @@ -2393,11 +2435,17 @@ fn raw_runtime_class_default_iid( fn add_raw_pointer(mut inner: RawComType, depth: usize, constness: RawConstness) -> RawComType { if inner.pointer_depth > 0 - && inner.constness != RawConstness::Unspecified + && !matches!( + inner.constness, + RawConstness::Mixed | RawConstness::Unspecified + ) && inner.constness != constness { - inner.constness = RawConstness::Unspecified; - } else if inner.constness != RawConstness::Unspecified { + inner.constness = RawConstness::Mixed; + } else if !matches!( + inner.constness, + RawConstness::Mixed | RawConstness::Unspecified + ) { inner.constness = constness; } else if inner.pointer_depth == 0 { inner.constness = constness; @@ -3017,7 +3065,59 @@ mod tests { let mixed = add_raw_pointer(inner, 1, RawConstness::Mutable); assert_eq!(mixed.pointer_depth, 2); - assert_eq!(mixed.constness, RawConstness::Unspecified); + assert_eq!(mixed.constness, RawConstness::Mixed); + } + + #[test] + fn com_inheritance_requires_one_acyclic_bounded_base_chain() { + let resolve = |graph: std::collections::BTreeMap< + (&'static str, &'static str), + Vec<(&'static str, &'static str, usize)>, + >| { + resolve_com_base_chain("Tests", "ILeaf", |namespace, name| { + graph.get(&(namespace, name)).map(|bases| { + bases + .iter() + .map(|(namespace, name, count)| { + ((*namespace).into(), (*name).into(), *count) + }) + .collect() + }) + }) + }; + + let valid = std::collections::BTreeMap::from([ + (("Tests", "ILeaf"), vec![("Tests", "IBase", 2)]), + ( + ("Tests", "IBase"), + vec![("Windows.Win32.System.Com", "IUnknown", 0)], + ), + ]); + let (iunknown, slot, chain) = resolve(valid).unwrap(); + assert!(iunknown); + assert_eq!(slot, 3); + assert_eq!(chain[0].1, "IBase"); + + let multiple = std::collections::BTreeMap::from([( + ("Tests", "ILeaf"), + vec![("Tests", "IBase", 2), ("Tests", "ISecond", 1)], + )]); + assert!(resolve(multiple).is_none()); + + let cyclic = std::collections::BTreeMap::from([ + (("Tests", "ILeaf"), vec![("Tests", "IBase", 2)]), + (("Tests", "IBase"), vec![("Tests", "ILeaf", 1)]), + ]); + assert!(resolve(cyclic).is_none()); + + let mut deep = std::collections::BTreeMap::new(); + deep.insert(("Tests", "ILeaf"), vec![("Tests", "I0", 1)]); + for index in 0..32 { + let current: &'static str = Box::leak(format!("I{index}").into_boxed_str()); + let next: &'static str = Box::leak(format!("I{}", index + 1).into_boxed_str()); + deep.insert(("Tests", current), vec![("Tests", next, 1)]); + } + assert!(resolve(deep).is_none()); } #[test] diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index fce9a05a..a6b6db85 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -6,6 +6,7 @@ use std::fs; use std::path::{Path, PathBuf}; use clap::{Parser, Subcommand}; +use serde::{Deserialize, Serialize}; use dynwinrt_codegen::codegen::com; use dynwinrt_codegen::codegen::package; @@ -46,6 +47,17 @@ enum Commands { /// Print supported machine-readable capabilities, one per line. Capabilities, + /// Measure complete safe Classic COM interface generation. + ComCensus { + /// Path(s) to Windows.Win32.winmd metadata, separated by ';'. + #[arg(long, value_name = "PATH")] + winmd: String, + + /// Emit one machine-readable JSON object. + #[arg(long)] + json: bool, + }, + /// Generate bindings from .winmd files #[command( long_about = "Parse .winmd metadata and generate typed binding files.\n\n\ @@ -127,6 +139,28 @@ enum Commands { }, } +const COM_MANIFEST_FILE: &str = ".dynwinrt-com-manifest.json"; + +#[derive(Debug, Default, Deserialize, Serialize)] +struct ComGenerationManifest { + version: u32, + roots: BTreeMap>, +} + +struct ComManifestUpdate { + manifest: ComGenerationManifest, + stale_files: BTreeSet, +} + +#[derive(Debug, Serialize)] +struct ComCensusResult { + metadata: String, + eligible_interfaces: usize, + complete_interfaces: usize, + incomplete_interfaces: usize, + coverage_percent: f64, +} + fn main() { if let Err(e) = run() { eprintln!("error: {}", e); @@ -134,6 +168,47 @@ fn main() { } } +fn run_com_census(winmd: &str, json: bool) -> Result<(), String> { + let interfaces = com_metadata::parse_all_com_interfaces(winmd) + .ok_or_else(|| format!("Failed to load Classic COM metadata from {winmd}"))?; + let eligible = interfaces + .into_iter() + .filter(|interface| { + (interface.is_iunknown_rooted || interface.interface.name.ends_with("Interop")) + && !(interface.interface.namespace == "Windows.Win32.UI.Controls.RichEdit" + && interface.interface.name == "ITextHost2") + }) + .collect::>(); + let complete = eligible + .iter() + .filter(|interface| com::generate_com_interface_files(interface, winmd).is_ok()) + .count(); + let result = ComCensusResult { + metadata: winmd.to_string(), + eligible_interfaces: eligible.len(), + complete_interfaces: complete, + incomplete_interfaces: eligible.len() - complete, + coverage_percent: if eligible.is_empty() { + 0.0 + } else { + complete as f64 * 100.0 / eligible.len() as f64 + }, + }; + if json { + println!( + "{}", + serde_json::to_string(&result) + .map_err(|error| format!("Failed to serialize COM census: {error}"))? + ); + } else { + println!( + "Classic COM complete interfaces: {}/{} ({:.6}%)", + result.complete_interfaces, result.eligible_interfaces, result.coverage_percent + ); + } + Ok(()) +} + fn parse_class_requests( class_names: &str, default_namespace: Option<&str>, @@ -168,6 +243,9 @@ fn run() -> Result<(), String> { Commands::Capabilities => { print_capabilities(); } + Commands::ComCensus { winmd, json } => { + run_com_census(&winmd, json)?; + } Commands::Generate { winmd, winmd_list, @@ -411,7 +489,14 @@ fn run() -> Result<(), String> { com_iface.interface.name, e ) })?; - generated.push((com_iface.interface.name.clone(), out)); + generated.push(( + format!( + "{}.{}", + com_iface.interface.namespace, com_iface.interface.name + ), + com_iface.interface.name.clone(), + out, + )); } for coclass in &com_coclasses { let out = @@ -421,17 +506,26 @@ fn run() -> Result<(), String> { coclass.name, e ) })?; - generated.push((coclass.name.clone(), out)); + generated.push(( + format!("{}.{}", coclass.namespace, coclass.name), + coclass.name.clone(), + out, + )); } let mut planned_files = BTreeMap::new(); - for (name, out) in &generated { + let mut root_files = BTreeMap::new(); + for (root, 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 { + root_files + .entry(root.clone()) + .or_insert_with(BTreeSet::new) + .insert(file_name.clone()); if let Some(existing) = planned_files.get(&file_name) && existing != &content { @@ -452,12 +546,15 @@ fn run() -> Result<(), String> { e ) })?; + let manifest_update = + prepare_com_generation_manifest(&com_output_dir, &root_files)?; 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))?; } + apply_com_generation_manifest(&com_output_dir, manifest_update)?; } - for (name, out) in &generated { + for (_, name, out) in &generated { if dry_run { println!("[dry-run] Would generate {}", name); } else { @@ -1222,6 +1319,88 @@ fn write_js_barrel_and_manifest(output_dir: &Path, index_content: &str) -> Resul Ok(()) } +fn prepare_com_generation_manifest( + com_output_dir: &Path, + updated_roots: &BTreeMap>, +) -> Result { + let path = com_output_dir.join(COM_MANIFEST_FILE); + let mut manifest = if path.exists() { + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + serde_json::from_str::(&content).map_err(|error| { + format!( + "Invalid COM generation manifest {}: {error}", + path.display() + ) + })? + } else { + ComGenerationManifest { + version: 1, + roots: BTreeMap::new(), + } + }; + if manifest.version != 1 { + return Err(format!( + "Unsupported COM generation manifest version {} in {}", + manifest.version, + path.display() + )); + } + + let previous_files = updated_roots + .keys() + .filter_map(|root| manifest.roots.get(root)) + .flatten() + .cloned() + .collect::>(); + for (root, files) in updated_roots { + manifest.roots.insert(root.clone(), files.clone()); + } + let retained_files = manifest + .roots + .values() + .flatten() + .cloned() + .collect::>(); + let stale_files = previous_files + .difference(&retained_files) + .cloned() + .collect::>(); + for stale in &stale_files { + let relative = Path::new(stale); + if relative.components().count() != 1 + || !(stale.ends_with(".js") || stale.ends_with(".d.ts")) + { + return Err(format!( + "Refusing unsafe path `{stale}` in COM generation manifest {}", + path.display() + )); + } + } + Ok(ComManifestUpdate { + manifest, + stale_files, + }) +} + +fn apply_com_generation_manifest( + com_output_dir: &Path, + update: ComManifestUpdate, +) -> Result<(), String> { + let path = com_output_dir.join(COM_MANIFEST_FILE); + for stale in &update.stale_files { + let stale_path = com_output_dir.join(stale); + if stale_path.exists() { + fs::remove_file(&stale_path) + .map_err(|error| format!("Failed to remove {}: {error}", stale_path.display()))?; + } + } + let content = serde_json::to_string_pretty(&update.manifest) + .map_err(|error| format!("Failed to serialize COM generation manifest: {error}"))?; + fs::write(&path, format!("{content}\n")) + .map_err(|error| format!("Failed to write {}: {error}", path.display())) +} + fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { let mut modules: BTreeMap> = BTreeMap::new(); let mut contents: BTreeMap = BTreeMap::new(); diff --git a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js index 47627523..718d4c88 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js +++ b/tools/dynwinrt-codegen/tests/snapshots/idatatransfermanagerinterop/IDataTransferManagerInterop.js @@ -18,8 +18,12 @@ const _IDataTransferManagerInterop = new Proxy({}, { class IDataTransferManagerInterop { static IID = IID_IDataTransferManagerInterop; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(IDataTransferManagerInterop.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_IDataTransferManagerInterop); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapIDataTransferManagerInteropOwned(obj.cast(IID_IDataTransferManagerInterop)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -29,7 +33,7 @@ class IDataTransferManagerInterop { static create() { const factory = DynWinRtValue.activationFactory('Windows.ApplicationModel.DataTransfer.DataTransferManager'); const _obj = factory.cast(IID_IDataTransferManagerInterop); - return new IDataTransferManagerInterop(_obj); + return _wrapIDataTransferManagerInteropOwned(_obj); } getForWindow(appWindow) { const _raw = _IDataTransferManagerInterop.method(3).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(appWindow)), DynCom.iidPointer(IID_DataTransferManager_default)]); @@ -41,5 +45,9 @@ class IDataTransferManagerInterop { _IDataTransferManagerInterop.method(4).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(appWindow))]); } } +function _wrapIDataTransferManagerInteropOwned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(IDataTransferManagerInterop.prototype), { _obj: obj }); +} exports.IID_IDataTransferManagerInterop = IID_IDataTransferManagerInterop; exports.IDataTransferManagerInterop = IDataTransferManagerInterop; diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts index 7760e1da..5211ee2b 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts @@ -6,8 +6,8 @@ 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; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically), or a `Buffer`/`Uint8Array` holding UTF-16LE bytes including the NUL terminator. Arbitrary numeric addresses require the explicit unsafe runtime. */ +export type PWSTR = string | Buffer | Uint8Array; /** 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' }; @@ -27,7 +27,7 @@ export declare class IShellLinkW { /** @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; + setIDList(pidl: Buffer | Uint8Array): 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} */ diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js index 2649e29b..434c382d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js @@ -21,7 +21,7 @@ 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(3, 'GetPath', new DynComMethodSig().addIn(DynCom.pointerType()).addIn(DynCom.i32Type()).addNullableInOut(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())) @@ -47,8 +47,12 @@ const _IShellLinkW = new Proxy({}, { class IShellLinkW { static IID = IID_IShellLinkW; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(IShellLinkW.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_IShellLinkW); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapIShellLinkWOwned(obj.cast(IID_IShellLinkW)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -68,7 +72,7 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(5).invoke(this._obj, [DynCom.safeDataPointer(pidl)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription} */ getDescription(cch = 260) { @@ -80,7 +84,7 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(7).invoke(this._obj, [DynCom.safeWideStringPointer(name)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getworkingdirectory} */ getWorkingDirectory(cch = 260) { @@ -92,7 +96,7 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(9).invoke(this._obj, [DynCom.safeWideStringPointer(dir)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getarguments} */ getArguments(cch = 260) { @@ -104,7 +108,7 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(11).invoke(this._obj, [DynCom.safeWideStringPointer(args)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-gethotkey} */ getHotkey() { @@ -134,11 +138,11 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(17).invoke(this._obj, [DynCom.safeWideStringPointer(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)]); + _IShellLinkW.method(18).invoke(this._obj, [DynCom.safeWideStringPointer(pathRel), DynCom.u32(reserved)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-resolve} */ resolve(hwnd, fFlags) { @@ -146,9 +150,13 @@ class IShellLinkW { } /** @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)]); + _IShellLinkW.method(20).invoke(this._obj, [DynCom.safeWideStringPointer(file)]); } } +function _wrapIShellLinkWOwned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(IShellLinkW.prototype), { _obj: obj }); +} 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.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js index 79dab23d..590c8245 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList.js @@ -20,8 +20,12 @@ const _ITaskbarList = new Proxy({}, { class ITaskbarList { static IID = IID_ITaskbarList; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_ITaskbarList); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapITaskbarListOwned(obj.cast(IID_ITaskbarList)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -47,5 +51,9 @@ class ITaskbarList { _ITaskbarList.method(7).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd))]); } } +function _wrapITaskbarListOwned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(ITaskbarList.prototype), { _obj: obj }); +} exports.IID_ITaskbarList = IID_ITaskbarList; exports.ITaskbarList = ITaskbarList; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js index 0bf652d5..51e3b6bb 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList2.js @@ -21,8 +21,12 @@ const _ITaskbarList2 = new Proxy({}, { class ITaskbarList2 { static IID = IID_ITaskbarList2; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList2.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_ITaskbarList2); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapITaskbarList2Owned(obj.cast(IID_ITaskbarList2)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -52,5 +56,9 @@ class ITaskbarList2 { _ITaskbarList2.method(8).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.i32(fFullscreen ? 1 : 0)]); } } +function _wrapITaskbarList2Owned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(ITaskbarList2.prototype), { _obj: obj }); +} 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 27242455..54ee4e2f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.d.ts @@ -9,8 +9,8 @@ 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 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; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically), or a `Buffer`/`Uint8Array` holding UTF-16LE bytes including the NUL terminator. Arbitrary numeric addresses require the explicit unsafe runtime. */ +export type PWSTR = string | Buffer | Uint8Array; /** Validated native POD bytes (Windows.Win32.Foundation-specific size selected at runtime). */ export type RECT = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.Foundation.RECT' }; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js index c83841c8..63a32ac9 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList3.js @@ -31,7 +31,7 @@ const _ITaskbarList3 = new Proxy({}, { .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.nativeStructPointerType(_nativeLayout_RECT, true))); + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addNullableIn(DynCom.nativeStructPointerType(_nativeLayout_RECT, true))); const value = _ITaskbarList3Cache[prop]; return typeof value === 'function' ? value.bind(_ITaskbarList3Cache) : value; }, @@ -40,8 +40,12 @@ const _ITaskbarList3 = new Proxy({}, { class ITaskbarList3 { static IID = IID_ITaskbarList3; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList3.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_ITaskbarList3); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapITaskbarList3Owned(obj.cast(IID_ITaskbarList3)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -104,21 +108,25 @@ class ITaskbarList3 { } /** @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)]); + _ITaskbarList3.method(17).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(DynCom.handleValue(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.wideStringPointer(description)]); + _ITaskbarList3.method(18).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(DynCom.handleValue(hIcon)), DynCom.safeWideStringPointer(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.wideStringPointer(tip)]); + _ITaskbarList3.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.safeWideStringPointer(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)), prcClip === null ? DynCom.nullNativeStructPointer() : DynCom.nativeStruct(_nativeLayout_RECT, prcClip)]); } } +function _wrapITaskbarList3Owned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(ITaskbarList3.prototype), { _obj: obj }); +} exports.createRECT = createRECT; exports.createTHUMBBUTTON = createTHUMBBUTTON; exports.createTHUMBBUTTONArray = createTHUMBBUTTONArray; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts index 1f54c959..a26e2cab 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.d.ts @@ -10,8 +10,8 @@ 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 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; +/** Win32 NUL-terminated string pointer. Pass a JS `string` (encoded automatically), or a `Buffer`/`Uint8Array` holding UTF-16LE bytes including the NUL terminator. Arbitrary numeric addresses require the explicit unsafe runtime. */ +export type PWSTR = string | Buffer | Uint8Array; /** Validated native POD bytes (Windows.Win32.Foundation-specific size selected at runtime). */ export type RECT = DynComNativeStruct & { readonly __dynComNativeStructLayout: 'Windows.Win32.Foundation.RECT' }; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js index f053d074..97bfcbc4 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/ITaskbarList4.js @@ -32,7 +32,7 @@ const _ITaskbarList4 = new Proxy({}, { .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.nativeStructPointerType(_nativeLayout_RECT, true))) + .addMethodAt(20, 'SetThumbnailClip', new DynComMethodSig().addIn(DynCom.pointerType()).addNullableIn(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; @@ -42,8 +42,12 @@ const _ITaskbarList4 = new Proxy({}, { class ITaskbarList4 { static IID = IID_ITaskbarList4; _obj; - constructor(obj) { this._obj = obj; } - static _fromNative(obj) { return Object.assign(Object.create(ITaskbarList4.prototype), { _obj: obj }); } + constructor(obj) { + const cast = obj.cast(IID_ITaskbarList4); + DynCom.bindComObject(cast); + this._obj = cast; + } + static _fromNative(obj) { return _wrapITaskbarList4Owned(obj.cast(IID_ITaskbarList4)); } /** Release the underlying native COM reference. Safe to call more than once. */ release() { this._obj.release(); @@ -106,15 +110,15 @@ class ITaskbarList4 { } /** @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)]); + _ITaskbarList4.method(17).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(DynCom.handleValue(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)]); + _ITaskbarList4.method(18).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.pointer(DynCom.handleValue(hIcon)), DynCom.safeWideStringPointer(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)]); + _ITaskbarList4.method(19).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(hwnd)), DynCom.safeWideStringPointer(tip)]); } /** @see {@link https://learn.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setthumbnailclip} */ setThumbnailClip(hwnd, prcClip) { @@ -125,6 +129,10 @@ class ITaskbarList4 { _ITaskbarList4.method(21).invoke(this._obj, [DynCom.pointer(DynCom.handleValue(tab)), DynCom.i32(stpFlags)]); } } +function _wrapITaskbarList4Owned(obj) { + DynCom.bindComObject(obj); + return Object.assign(Object.create(ITaskbarList4.prototype), { _obj: obj }); +} exports.createRECT = createRECT; exports.createTHUMBBUTTON = createTHUMBBUTTON; exports.createTHUMBBUTTONArray = createTHUMBBUTTONArray; diff --git a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js index 0bccfa46..3ec3dcf7 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js +++ b/tools/dynwinrt-codegen/tests/snapshots/itaskbarlist3/TaskbarList.js @@ -6,18 +6,29 @@ const CLSID_TaskbarList = '56fdf344-fd6d-11d0-958a-006097c9a090'; class TaskbarList extends ITaskbarList4 { constructor() { - super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4)); + const obj = DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4); + try { + super(obj); + } finally { + obj.release(); + } } static _fromNative(obj) { const cast = obj.cast(IID_ITaskbarList4); + DynCom.bindComObject(cast); return Object.assign(Object.create(TaskbarList.prototype), { _obj: cast }); } as(InterfaceClass) { - return InterfaceClass._fromNative(this._obj.cast(InterfaceClass.IID)); + return InterfaceClass._fromNative(this._obj); } tryAs(InterfaceClass) { const obj = DynCom.tryCast(this._obj, InterfaceClass.IID); - return obj === null ? null : InterfaceClass._fromNative(obj); + if (obj === null) return null; + try { + return InterfaceClass._fromNative(obj); + } finally { + obj.release(); + } } supports(InterfaceClass) { const obj = DynCom.tryCast(this._obj, InterfaceClass.IID); diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 44cd0e87..1ac2a396 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -823,7 +823,7 @@ fn real_metadata_projects_complete_idispatch_with_automation_compounds() { 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 };" + "invoke(dispIdMember: number, riid: Buffer | Uint8Array, lcid: number, wFlags: DISPATCH_FLAGS, dispParams: DynComDispatchParams, options?: { result?: boolean; excepInfo?: boolean; argErr?: boolean }): { result?: DynComVariant };" )); let invoke_raw_index = dispatch @@ -1102,8 +1102,10 @@ fn taskbarlist_coclass_generates_newable_class_and_interface_views() { assert!(out.js.contains("exports.TaskbarList = TaskbarList;")); assert!( out.js - .contains("super(DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4))") + .contains("const obj = DynCom.coCreateInstance(CLSID_TaskbarList, IID_ITaskbarList4)") ); + assert!(out.js.contains("super(obj)")); + assert!(out.js.contains("obj.release()")); assert!(out.js.contains("as(InterfaceClass)")); assert!(out.js.contains("DynCom.tryCast")); assert!(out.dts.contains("constructor();")); @@ -1989,14 +1991,12 @@ fn sid_buffers_keep_data_pointer_address_semantics() { .expect("isolated IDiskQuotaControl.AddUserSid generation should succeed"); assert!( - output - .dts - .contains("addUserSid(pUserSid: PSID | Buffer | Uint8Array"), + output.dts.contains("addUserSid(pUserSid: PSID,"), "PSID input must accept backing storage rather than handle bytes:\n{}", output.dts ); assert!( - output.js.contains("DynCom.pointer(pUserSid)") + output.js.contains("DynCom.safeDataPointer(pUserSid)") && !output.js.contains("handleValue(pUserSid)"), "PSID Buffer must pass its address, not decoded contents:\n{}", output.js @@ -2625,7 +2625,8 @@ fn standard_enumerator_next_projects_partial_arrays_and_exact_interface_ownershi ) && output.js.contains("DynCom.takeComArray(_out[1])") && output .js - .contains("value => IConnectionPoint._fromNative(value)") + .contains("return IConnectionPoint._fromNative(value);") + && output.js.contains("finally { value.release(); }") && output .dts .contains("next(count: number): IConnectionPoint[]") @@ -3350,7 +3351,7 @@ fn generalized_dynamic_iid_unlocks_non_positional_real_interfaces() { 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))" + ".addNullableIn(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( @@ -4368,6 +4369,54 @@ fn com_only_generation_emits_an_importable_package_shape() { "incremental generation must preserve earlier package subpaths:\n{incremental_package}" ); + let manifest_path = output_dir.join("com").join(".dynwinrt-com-manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap(); + let root = manifest["roots"]["Windows.Win32.UI.Shell.ITaskbarList3"] + .as_array_mut() + .expect("ITaskbarList3 manifest root"); + root.push(serde_json::Value::String("Stale.js".into())); + fs::write( + &manifest_path, + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); + fs::write( + output_dir.join("com").join("Stale.js"), + "exports.Stale = 1;\n", + ) + .unwrap(); + let regenerate = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args([ + "generate", + "--winmd", + &win32_winmd(), + "--namespace", + "Windows.Win32.UI.Shell", + "--class-name", + "ITaskbarList3", + "--output", + output_dir.to_str().unwrap(), + ]) + .output() + .expect("regenerate manifest root"); + assert!( + regenerate.status.success(), + "manifest regeneration failed:\n{}", + String::from_utf8_lossy(®enerate.stderr) + ); + assert!( + !output_dir.join("com").join("Stale.js").exists(), + "regenerating one COM root must remove only its stale manifest-owned files" + ); + let regenerated_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); + assert!( + regenerated_index.contains("ITaskbarList3") + && regenerated_index.contains("IShellLinkW") + && !regenerated_index.contains("Stale"), + "manifest cleanup must preserve other incremental roots:\n{regenerated_index}" + ); + fs::remove_dir_all(&output_dir).expect("remove COM package test directory"); }