diff --git a/crates/dynwinrt/src/metadata_table/arena.rs b/crates/dynwinrt/src/metadata_table/arena.rs index d34619bf..ff54c15c 100644 --- a/crates/dynwinrt/src/metadata_table/arena.rs +++ b/crates/dynwinrt/src/metadata_table/arena.rs @@ -8,7 +8,6 @@ use windows_core::GUID; use super::MetadataTable; use super::type_kind::TypeKind; use crate::signature::MethodSignature; -use crate::value::WinRTValue; // =========================================================================== // Arena data types @@ -130,6 +129,7 @@ impl MetadataTable { /// Add a method to an interface's method table. Returns the vtable index. /// If a method with the same name already exists, skips and returns the existing vtable index. pub(super) fn push_method(&self, iid: &GUID, name: &str, sig: MethodSignature) -> u32 { + sig.assert_parameter_owners(self, name); let mut iface_methods = self.interface_methods.write().unwrap(); let table = iface_methods .get_mut(iid) @@ -141,7 +141,7 @@ impl MetadataTable { } let vtable_index = 6 + table.method_indices.len(); - let method = sig.build(vtable_index); + let method = sig.build_registered(vtable_index); let arena_index = self.methods.push(method); table.method_names.push(name.to_string()); table.method_indices.push(arena_index); @@ -209,26 +209,9 @@ impl MetadataTable { .map(|e| e.members.clone()) } - pub(crate) fn invoke_method( - &self, - index: u32, - obj: *mut std::ffi::c_void, - args: &[WinRTValue], - ) -> windows_core::Result> { - // Grab a stable pointer to the method, then invoke. `AppendOnlyBoxArena` - // guarantees the pointer remains valid for the arena's lifetime, which - // lets us release the read lock before making the COM call. Holding the - // read lock across dispatch would deadlock any re-entrant `push_method` - // triggered from within (e.g. an event handler that touches a lazy - // proxy while `runEventLoop` is pumping). See the doc comment on - // `methods` in mod.rs for the safety argument. - let method_ptr: *const crate::signature::Method = self.methods.stable_ptr(index); - unsafe { (*method_ptr).call_dynamic(obj, args) } - } - - /// Get a stable pointer to a Method by arena index. See the safety notes + /// Get a stable pointer to a registered descriptor by arena index. See the safety notes /// on `MetadataTable::methods` for why this is sound. - pub(crate) fn method_ptr(&self, index: u32) -> *const crate::signature::Method { + pub(crate) fn method_ptr(&self, index: u32) -> *const crate::signature::RegisteredMethod { self.methods.stable_ptr(index) } diff --git a/crates/dynwinrt/src/metadata_table/method_handle.rs b/crates/dynwinrt/src/metadata_table/method_handle.rs index 19cc5db1..e5f3bc51 100644 --- a/crates/dynwinrt/src/metadata_table/method_handle.rs +++ b/crates/dynwinrt/src/metadata_table/method_handle.rs @@ -7,11 +7,13 @@ use crate::value::WinRTValue; use super::MetadataTable; -/// A handle to a pre-built method in the MetadataTable's methods arena. +/// An owning, bound method handle sharing its immutable prepared ABI plan. #[derive(Clone)] pub struct MethodHandle { - pub(crate) table: Arc, + // Keep even zero-parameter methods' registry alive. + _table: Arc, pub(crate) index: u32, + method: Arc, } impl std::fmt::Debug for MethodHandle { @@ -24,7 +26,14 @@ impl std::fmt::Debug for MethodHandle { impl MethodHandle { pub(crate) fn new(table: Arc, index: u32) -> Self { - MethodHandle { table, index } + let descriptor = table.method_ptr(index); + // The append-only descriptor cannot move or be removed while table is alive. + let method = Arc::new(unsafe { (*descriptor).bind(&table) }); + MethodHandle { + _table: table, + index, + method, + } } /// Invoke this method on the given COM object with the provided arguments. @@ -33,33 +42,31 @@ impl MethodHandle { obj: *mut std::ffi::c_void, args: &[WinRTValue], ) -> crate::result::Result> { - self.table - .invoke_method(self.index, obj, args) + self.method + .call_dynamic(obj, args) .map_err(crate::result::Error::WindowsError) } // --- Fast getter paths: zero Vec/WinRTValue allocation --- - // - // Each path grabs a stable Method pointer under the read lock via - // `method_ptr`, drops the guard, and then makes the COM call. See the - // safety comment on `MetadataTable::methods` for why this is sound. pub fn call_getter_i32(&self, obj: *mut std::ffi::c_void) -> crate::result::Result { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_getter_i32(obj) }.map_err(crate::result::Error::WindowsError) + self.method + .call_getter_i32(obj) + .map_err(crate::result::Error::WindowsError) } pub fn call_getter_bool(&self, obj: *mut std::ffi::c_void) -> crate::result::Result { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_getter_bool(obj) }.map_err(crate::result::Error::WindowsError) + self.method + .call_getter_bool(obj) + .map_err(crate::result::Error::WindowsError) } pub fn call_getter_hstring( &self, obj: *mut std::ffi::c_void, ) -> crate::result::Result { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_getter_hstring(obj) } + self.method + .call_getter_hstring(obj) .map_err(crate::result::Error::WindowsError) } @@ -67,8 +74,9 @@ impl MethodHandle { &self, obj: *mut std::ffi::c_void, ) -> crate::result::Result { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_getter_object(obj) }.map_err(crate::result::Error::WindowsError) + self.method + .call_getter_object(obj) + .map_err(crate::result::Error::WindowsError) } pub fn call_setter_hstring( @@ -76,8 +84,8 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: &windows_core::HSTRING, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_hstring(obj, value) } + self.method + .call_setter_hstring(obj, value) .map_err(crate::result::Error::WindowsError) } @@ -86,8 +94,8 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: bool, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_bool(obj, value) } + self.method + .call_setter_bool(obj, value) .map_err(crate::result::Error::WindowsError) } @@ -96,8 +104,8 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: i32, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_i32(obj, value) } + self.method + .call_setter_i32(obj, value) .map_err(crate::result::Error::WindowsError) } @@ -106,8 +114,8 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: u32, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_u32(obj, value) } + self.method + .call_setter_u32(obj, value) .map_err(crate::result::Error::WindowsError) } @@ -116,8 +124,8 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: f32, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_f32(obj, value) } + self.method + .call_setter_f32(obj, value) .map_err(crate::result::Error::WindowsError) } @@ -126,8 +134,56 @@ impl MethodHandle { obj: *mut std::ffi::c_void, value: f64, ) -> crate::result::Result<()> { - let method_ptr = self.table.method_ptr(self.index); - unsafe { (*method_ptr).call_setter_f64(obj, value) } + self.method + .call_setter_f64(obj, value) .map_err(crate::result::Error::WindowsError) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MethodSignature, TypeHandle, native_call::PreparedCall}; + use windows::Foundation::IUriRuntimeClassFactory; + use windows_core::Interface; + + #[test] + fn bound_handles_share_and_release_prepared_calls() { + fn assert_send_sync() {} + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + + let table = MetadataTable::new(); + let weak_table = Arc::downgrade(&table); + let interface = table + .register_interface("IUriRuntimeClassFactory", IUriRuntimeClassFactory::IID) + .add_method( + "CreateUri", + MethodSignature::new(&table) + .add_in(table.hstring()) + .add_out(table.object()), + ); + let first = interface.method(6).unwrap(); + let clone = first.clone(); + let second = interface.method_by_name("CreateUri").unwrap(); + assert!(Arc::ptr_eq(&first.method, &clone.method)); + assert!(!Arc::ptr_eq(&first.method, &second.method)); + assert!(Arc::ptr_eq( + first.method.prepared_call(), + second.method.prepared_call() + )); + let weak_plan = Arc::downgrade(first.method.prepared_call()); + drop(interface); + drop(table); + drop(first); + drop(second); + assert!(weak_table.upgrade().is_some()); + assert!(weak_plan.upgrade().is_some()); + drop(clone); + assert!(weak_table.upgrade().is_none()); + assert!(weak_plan.upgrade().is_none()); + } +} diff --git a/crates/dynwinrt/src/metadata_table/mod.rs b/crates/dynwinrt/src/metadata_table/mod.rs index 0e20327c..c6ca8dee 100644 --- a/crates/dynwinrt/src/metadata_table/mod.rs +++ b/crates/dynwinrt/src/metadata_table/mod.rs @@ -21,7 +21,7 @@ use std::sync::{Arc, RwLock}; use windows_core::GUID; -use crate::signature::{Method, MethodSignature}; +use crate::signature::{MethodSignature, RegisteredMethod}; use append_only_arena::AppendOnlyBoxArena; use arena::*; @@ -46,21 +46,15 @@ pub struct MetadataTable { // --- Methods arena --- // - // Stored in an `AppendOnlyBoxArena` so entries have heap-stable - // addresses that can never be invalidated: callers may take a raw - // `*const Method` under the read guard, drop the guard, and then - // invoke the method. This is essential because a method call can be - // `DispatcherQueue.runEventLoop`, which pumps messages and may - // re-enter this arena for `push_method` (requiring `.write()`); if - // the outer call still held the read lock during dispatch, we would - // deadlock. + // Descriptors contain local TypeKinds, not owning TypeHandles. Prepared + // ABI plans have no table backreference. External MethodHandles bind these + // descriptors to strong table owners once, outside the registry. // - // Vec growth may move the `Box` slots inside the arena's - // backing buffer, but the boxed `Method` itself never moves. The - // arena type intentionally exposes only `push` / `stable_ptr` - // (no `pop`/`remove`/`clear`), so the "never removed" invariant - // is enforced by the type system rather than by convention. - methods: AppendOnlyBoxArena, + // Boxed descriptors never move or disappear until this table drops, so + // lookup can release the arena lock before binding through a stable pointer. + // Invocation uses the bound handle and holds no registry lock, including + // during native calls that re-enter registration. + methods: AppendOnlyBoxArena, // --- Indexes (no data duplication, only pointers) --- /// IID → method table for O(1) interface method lookup. @@ -75,12 +69,6 @@ impl std::fmt::Debug for MetadataTable { } } -// Safety: MetadataTable is protected by RwLock internally. -// The non-Send/Sync raw pointers come from libffi Cif objects inside Method, -// which are only accessed through &self methods behind the RwLock. -unsafe impl Send for MetadataTable {} -unsafe impl Sync for MetadataTable {} - impl MetadataTable { pub fn new() -> Arc { Arc::new(MetadataTable { diff --git a/crates/dynwinrt/src/metadata_table/type_handle.rs b/crates/dynwinrt/src/metadata_table/type_handle.rs index 5aa81f32..59f2f5c1 100644 --- a/crates/dynwinrt/src/metadata_table/type_handle.rs +++ b/crates/dynwinrt/src/metadata_table/type_handle.rs @@ -58,6 +58,15 @@ impl TypeHandle { /// Add a method to this interface. Only valid for Interface types. /// Returns self for chaining. + /// + /// Every parameter type must belong to this interface's MetadataTable, + /// including when the method name is already registered. The signature's + /// constructor table need not match if its actual parameter types do. + /// + /// # Panics + /// + /// Panics if this is not an interface or a parameter belongs to another + /// table. Foreign parameters are rejected before changing the method table. pub fn add_method(self, name: &str, sig: MethodSignature) -> Self { match self.kind { TypeKind::Interface(iid) => { diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index d21bbbae..96e69c30 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -986,7 +986,7 @@ impl AbiMethodSignature { out_count: self.out_count, return_kind: self.return_kind, }, - strategy, + strategy: Arc::new(PreparedCall(strategy)), } } } @@ -1057,10 +1057,19 @@ enum CallStrategy { Libffi(Cif), } +/// Owns only the completed ABI strategy, never metadata owners or call storage. +#[derive(Debug)] +pub(crate) struct PreparedCall(CallStrategy); + +// Prepared CIFs own their type graphs and are immutable after construction. +// ffi_call only reads them; argument and output storage is invocation-local. +unsafe impl Send for PreparedCall {} +unsafe impl Sync for PreparedCall {} + #[derive(Debug)] pub struct Method { info: MethodInfo, - strategy: CallStrategy, + strategy: Arc, } fn expected_object_iid(typ: &TypeHandle) -> Option { @@ -1525,6 +1534,20 @@ impl call::ArgumentList for ComInvocationArgs<'_> { } impl Method { + #[cfg(test)] + pub(crate) fn prepared_call(&self) -> &Arc { + &self.strategy + } + + pub(crate) fn into_parts(self) -> (MethodInfo, Arc) { + (self.info, self.strategy) + } + + /// Rebind metadata without changing the completed method's ABI shape. + pub(crate) fn from_parts(info: MethodInfo, strategy: Arc) -> Self { + Self { info, strategy } + } + pub(crate) fn parameter_type(&self, parameter_index: usize) -> &ParameterType { &self.info.parameters[parameter_index].typ } @@ -1818,7 +1841,7 @@ impl Method { .expect("native dispatch marker must run exactly once")() }; - match &self.strategy { + match &self.strategy.0 { CallStrategy::Direct0In0Out => { // 0 in + 0 out: fn(this) -> HRESULT mark_dispatched()?; @@ -2322,7 +2345,7 @@ impl Method { )); } let invocation_args = self.prepare_com_invocation_args(args)?; - let CallStrategy::Libffi(cif) = &self.strategy else { + let CallStrategy::Libffi(cif) = &self.strategy.0 else { return Err(invalid_argument( "native POD calls must use the prepared libffi plan", )); @@ -2367,7 +2390,7 @@ impl Method { F: FnOnce() -> windows_core::Result<()>, { let invocation_args = self.prepare_com_invocation_args(args)?; - let CallStrategy::Libffi(cif) = &self.strategy else { + let CallStrategy::Libffi(cif) = &self.strategy.0 else { return Err(invalid_argument( "captured HRESULT calls must use the prepared libffi plan", )); @@ -2537,7 +2560,7 @@ mod tests { .add_out_fill_type(ParameterType::winrt(array_type.clone())) .build(0); assert!(matches!( - (&method.strategy, with_scalar), + (&method.strategy.0, with_scalar), (CallStrategy::DirectFillArray, false) | (CallStrategy::Direct1InFillArray, true) )); args.push(WinRTValue::Array(crate::array::ArrayData::from_values( diff --git a/crates/dynwinrt/src/signature.rs b/crates/dynwinrt/src/signature.rs index dce8fcab..5087235d 100644 --- a/crates/dynwinrt/src/signature.rs +++ b/crates/dynwinrt/src/signature.rs @@ -12,8 +12,11 @@ use std::sync::Arc; use windows::core::{GUID, HSTRING}; use crate::{ - metadata_table::{MetadataTable, TypeHandle}, - native_call::{AbiMethodSignature, Method as NativeMethod, ParameterType}, + metadata_table::{MetadataTable, TypeHandle, TypeKind}, + native_call::{ + AbiMethodSignature, Method as NativeMethod, MethodInfo, MethodReturn, OutputCleanup, + ParamKind, Parameter, ParameterType, PreparedCall, + }, value::WinRTValue, }; @@ -52,6 +55,54 @@ impl MethodSignature { Method(self.0.build(index)) } + pub(crate) fn assert_parameter_owners(&self, table: &MetadataTable, name: &str) { + for (index, parameter) in self.0.parameters().iter().enumerate() { + let typ = parameter.typ.as_winrt().expect("WinRT signature parameter"); + assert!( + std::ptr::eq(table, typ.table().as_ref()), + "registered method '{name}' parameter {index} must use the same MetadataTable" + ); + } + } + + pub(crate) fn build_registered(self, index: usize) -> RegisteredMethod { + let (info, prepared) = self.0.build(index).into_parts(); + let parameters = info + .parameters + .into_iter() + .map(|parameter| { + let direction = match parameter.kind { + ParamKind::In => WinRtParameterDirection::In, + ParamKind::Out => WinRtParameterDirection::Out, + ParamKind::OutFillArray => WinRtParameterDirection::FillArray, + ParamKind::OptionalOut | ParamKind::InOut => { + unreachable!("WinRT signature direction") + } + }; + debug_assert!(parameter.canonical_format_input.is_none()); + RegisteredParameter { + typ: parameter + .typ + .as_winrt() + .expect("WinRT signature parameter") + .kind(), + direction, + output_cleanup: parameter.output_cleanup, + value_index: parameter.value_index, + input_index: parameter.input_index, + } + }) + .collect(); + debug_assert!(matches!(info.return_kind, MethodReturn::HResult)); + RegisteredMethod { + index: info.index, + parameters, + input_count: info.input_count, + out_count: info.out_count, + prepared, + } + } + pub(crate) fn implementation_parameters( &self, ) -> windows_core::Result> { @@ -84,10 +135,65 @@ impl MethodSignature { } } +#[derive(Debug)] +struct RegisteredParameter { + typ: TypeKind, + direction: WinRtParameterDirection, + output_cleanup: OutputCleanup, + value_index: usize, + input_index: Option, +} + +/// Table-local method metadata must not retain owning TypeHandles. +#[derive(Debug)] +pub(crate) struct RegisteredMethod { + index: usize, + parameters: Vec, + input_count: usize, + out_count: usize, + prepared: Arc, +} + +impl RegisteredMethod { + pub(crate) fn bind(&self, table: &Arc) -> Method { + let parameters = self + .parameters + .iter() + .map(|parameter| Parameter { + typ: ParameterType::winrt(table.make(parameter.typ)), + kind: match parameter.direction { + WinRtParameterDirection::In => ParamKind::In, + WinRtParameterDirection::Out => ParamKind::Out, + WinRtParameterDirection::FillArray => ParamKind::OutFillArray, + }, + output_cleanup: parameter.output_cleanup, + canonical_format_input: None, + value_index: parameter.value_index, + input_index: parameter.input_index, + }) + .collect(); + Method(NativeMethod::from_parts( + MethodInfo { + index: self.index, + parameters, + input_count: self.input_count, + out_count: self.out_count, + return_kind: MethodReturn::HResult, + }, + Arc::clone(&self.prepared), + )) + } +} + #[derive(Debug)] pub struct Method(NativeMethod); impl Method { + #[cfg(test)] + pub(crate) fn prepared_call(&self) -> &Arc { + self.0.prepared_call() + } + pub fn call_getter_i32(&self, obj: *mut std::ffi::c_void) -> windows_core::Result { self.0.call_getter_i32(obj) } diff --git a/crates/dynwinrt/tests/metadata_lifetime.rs b/crates/dynwinrt/tests/metadata_lifetime.rs new file mode 100644 index 00000000..ef3b1136 --- /dev/null +++ b/crates/dynwinrt/tests/metadata_lifetime.rs @@ -0,0 +1,729 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +#![cfg(windows)] + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, OnceLock, Weak}; + +use dynwinrt::{MetadataTable, MethodSignature, TypeHandle, WinRTValue}; +use windows::Devices::Geolocation::{BasicGeoposition, Geopoint, IGeopoint}; +use windows::Foundation::{IClosable, IStringable, IUriRuntimeClassFactory, MemoryBuffer, Uri}; +use windows::Win32::System::Com::CoIncrementMTAUsage; +use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize}; +use windows_core::{HSTRING, Interface}; + +struct Apartment; + +impl Apartment { + fn new() -> Self { + static MTA: OnceLock<()> = OnceLock::new(); + MTA.get_or_init(|| { + // Keep the MTA alive as long as windows-core's process-wide factory cache. + // Worker apartment initialization below remains balanced. + let _cookie = unsafe { CoIncrementMTAUsage() }.unwrap(); + }); + unsafe { RoInitialize(RO_INIT_MULTITHREADED) }.unwrap(); + Self + } +} + +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { RoUninitialize() }; + } +} + +fn stringable(table: &Arc) -> TypeHandle { + table + .register_interface("IStringable", IStringable::IID) + .add_method( + "ToString", + MethodSignature::new(table).add_out(table.hstring()), + ) +} + +fn assert_expired(weak: &Weak) { + assert!( + weak.upgrade().is_none(), + "registry retains {} strong owners", + weak.strong_count() + ); +} + +fn registration_case(case: usize) -> Weak { + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + if case == 6 { + drop( + MethodSignature::new(&table) + .add_in(table.i32_type()) + .add_out(table.hstring()), + ); + } else if case != 0 { + let mut interface = table.register_interface("Lifetime", IStringable::IID); + if case >= 2 { + let mut signature = MethodSignature::new(&table); + if matches!(case, 3 | 5) { + signature = signature.add_in(table.i32_type()); + } + if matches!(case, 4 | 5) { + signature = signature.add_out(table.hstring()); + } + interface = interface.add_method("Method", signature); + drop(interface.method(6).unwrap()); + } + } + drop(table); + weak +} + +#[test] +fn all_registered_and_unregistered_lifetime_cases_expire() { + let cases = [ + "empty", + "interface only", + "zero parameter", + "scalar input", + "HSTRING output", + "scalar input and HSTRING output", + "unregistered signature", + ]; + let mut retained = Vec::new(); + for (case, name) in cases.into_iter().enumerate() { + let observations: Vec<_> = (0..32).map(|_| registration_case(case)).collect(); + let live = observations + .iter() + .filter(|weak| weak.upgrade().is_some()) + .count(); + if live != 0 { + retained.push((name, live)); + } + } + assert!( + retained.is_empty(), + "retained registries after all caller owners dropped: {retained:?}" + ); +} + +#[test] +fn local_compound_types_and_multiple_methods_do_not_retain_registry() { + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let scalar = table.enum_type("Lifetime.Enum", vec![("One".into(), 1)]); + let inner = table.struct_type("Lifetime.Inner", &[table.i32_type(), scalar.clone()]); + let outer = table.struct_type("Lifetime.Outer", &[inner, table.f64_type()]); + let array = table.array(&outer); + let nested_array = table.array(&array); + let generic = table.parameterized( + &table.generic(dynwinrt::metadata_table::IVECTOR_VIEW, 1), + &[table.hstring()], + ); + let async_type = table.async_operation(&generic); + let mut interface = table.register_interface("Lifetime", IStringable::IID); + for (index, typ) in [scalar, outer, array, nested_array, generic, async_type] + .into_iter() + .enumerate() + { + let name = format!("Method{index}"); + let signature = MethodSignature::new(&table).add_out(typ); + interface = interface + .add_method(&name, signature.clone()) + .add_method(&name, signature); + assert!(interface.method(6 + index).is_some()); + assert!(interface.method_by_name(&name).is_some()); + } + drop(interface); + drop(table); + assert_expired(&weak); +} + +#[test] +fn external_type_handle_keeps_registered_methods_and_layout_usable() { + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + drop(stringable(&table)); + let typ = table.struct_type("Lifetime.Point", &[table.f32_type(), table.f32_type()]); + let clone = typ.clone(); + drop(table); + drop(typ); + assert!(weak.upgrade().is_some()); + assert_eq!(clone.size_of(), 8); + assert_eq!(clone.field_type(1).size_of(), 4); + assert!( + clone + .table() + .interface(IStringable::IID) + .method_by_name("ToString") + .is_some() + ); + let value = clone.default_value(); + drop(clone); + assert_eq!(value.type_handle().field_count(), 2); + drop(value); + assert_expired(&weak); +} + +#[test] +fn unregistered_signature_clones_keep_constructor_and_parameter_owners() { + let constructor = MetadataTable::new(); + let parameters = MetadataTable::new(); + let constructor_weak = Arc::downgrade(&constructor); + let parameters_weak = Arc::downgrade(¶meters); + let signature = MethodSignature::new(&constructor).add_out(parameters.hstring()); + let clone = signature.clone(); + drop(signature); + drop(constructor); + drop(parameters); + assert!(constructor_weak.upgrade().is_some()); + assert!(parameters_weak.upgrade().is_some()); + let method = clone.build(6); + assert_expired(&constructor_weak); + assert!(parameters_weak.upgrade().is_some()); + drop(method); + assert_expired(¶meters_weak); + + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let empty = MethodSignature::new(&table); + drop(table); + assert!(weak.upgrade().is_some()); + drop(empty.build(6)); + assert_expired(&weak); +} + +#[test] +fn foreign_parameters_are_rejected_before_publication_or_lock_poisoning() { + for direction in 0..3 { + for duplicate in [false, true] { + let local = MetadataTable::new(); + let foreign = MetadataTable::new(); + let local_weak = Arc::downgrade(&local); + let foreign_weak = Arc::downgrade(&foreign); + let mut interface = local.register_interface("Lifetime", IStringable::IID); + if duplicate { + interface = interface.add_method("Method", MethodSignature::new(&local)); + } + let signature = match direction { + 0 => MethodSignature::new(&local).add_in(foreign.i32_type()), + 1 => MethodSignature::new(&local).add_out(foreign.hstring()), + _ => MethodSignature::new(&local).add_out_fill(foreign.array(&foreign.i32_type())), + }; + let failure = catch_unwind(AssertUnwindSafe(|| { + interface.clone().add_method("Method", signature) + })); + let failure = failure.expect_err("foreign parameter registration must fail"); + let message = failure + .downcast_ref::() + .map(String::as_str) + .or_else(|| failure.downcast_ref::<&str>().copied()) + .unwrap(); + assert!(message.contains("same MetadataTable"), "{message}"); + assert_eq!(interface.method(6).is_some(), duplicate); + assert!(interface.method(7).is_none()); + interface = interface.add_method( + "Valid", + MethodSignature::new(&local).add_out(local.hstring()), + ); + assert!(interface.method_by_name("Valid").is_some()); + drop(interface); + drop(local); + drop(foreign); + assert_expired(&local_weak); + assert_expired(&foreign_weak); + } + } +} + +#[test] +fn foreign_constructor_with_local_or_no_parameters_is_accepted() { + for has_parameter in [false, true] { + let local = MetadataTable::new(); + let foreign = MetadataTable::new(); + let local_weak = Arc::downgrade(&local); + let foreign_weak = Arc::downgrade(&foreign); + let mut signature = MethodSignature::new(&foreign); + if has_parameter { + signature = signature.add_out(local.hstring()); + } + let interface = local + .register_interface("Lifetime", IStringable::IID) + .add_method("Method", signature); + drop(foreign); + assert_expired(&foreign_weak); + let method = interface.method(6).unwrap(); + drop(interface); + drop(local); + assert!(local_weak.upgrade().is_some()); + drop(method); + assert_expired(&local_weak); + } +} + +#[test] +fn reciprocal_foreign_registrations_cannot_create_table_cycles() { + let first = MetadataTable::new(); + let second = MetadataTable::new(); + let first_weak = Arc::downgrade(&first); + let second_weak = Arc::downgrade(&second); + for (local, foreign) in [(&first, &second), (&second, &first)] { + let interface = local.register_interface("Lifetime", IStringable::IID); + let signature = MethodSignature::new(local).add_out(foreign.hstring()); + assert!( + catch_unwind(AssertUnwindSafe( + || interface.add_method("Method", signature) + )) + .is_err() + ); + } + drop(first); + drop(second); + assert_expired(&first_weak); + assert_expired(&second_weak); +} + +#[test] +fn retained_method_clones_call_sdk_getter_and_release_registry() { + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let method = stringable(&table).method(6).unwrap(); + let clone = method.clone(); + drop(table); + drop(method); + let uri: IStringable = Uri::CreateUri(&HSTRING::from("https://example.com/lifetime")) + .unwrap() + .cast() + .unwrap(); + for _ in 0..8 { + assert_eq!( + clone.call_getter_hstring(uri.as_raw()).unwrap(), + uri.ToString().unwrap() + ); + assert_eq!( + clone.invoke(uri.as_raw(), &[]).unwrap()[0] + .as_hstring() + .unwrap(), + uri.ToString().unwrap() + ); + } + drop(clone); + assert_expired(&weak); +} + +#[test] +fn zero_parameter_handle_keeps_registry_alive_and_calls_sdk() { + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let method = table + .register_interface("IClosable", IClosable::IID) + .add_method("Close", MethodSignature::new(&table)) + .method(6) + .unwrap(); + drop(table); + assert!(weak.upgrade().is_some()); + let buffer: IClosable = MemoryBuffer::Create(16).unwrap().cast().unwrap(); + assert!(method.invoke(buffer.as_raw(), &[]).unwrap().is_empty()); + drop(method); + assert_expired(&weak); +} + +#[test] +fn registered_and_standalone_factory_plans_preserve_needed_owners() { + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let foreign = MetadataTable::new(); + let table_weak = Arc::downgrade(&table); + let foreign_weak = Arc::downgrade(&foreign); + let signature = MethodSignature::new(&table) + .add_in(table.hstring()) + .add_out(table.object()); + let method = table + .register_interface("IUriRuntimeClassFactory", IUriRuntimeClassFactory::IID) + .add_method("CreateUri", signature) + .method(6) + .unwrap(); + let standalone = MethodSignature::new(&table) + .add_in(foreign.hstring()) + .add_out(table.object()) + .build(6); + let factory = WinRTValue::from_activation_factory(&HSTRING::from("Windows.Foundation.Uri")) + .unwrap() + .cast(&IUriRuntimeClassFactory::IID) + .unwrap() + .as_object() + .unwrap(); + drop(table); + drop(foreign); + for _ in 0..8 { + let args = [WinRTValue::HString(HSTRING::from( + "https://example.com/retained", + ))]; + for result in [ + method.invoke(factory.as_raw(), &args).unwrap(), + standalone.call_dynamic(factory.as_raw(), &args).unwrap(), + ] { + let uri: Uri = result[0].as_object().unwrap().cast().unwrap(); + assert_eq!(uri.Host().unwrap(), "example.com"); + } + } + drop(method); + assert!(table_weak.upgrade().is_some()); + assert!(foreign_weak.upgrade().is_some()); + drop(standalone); + assert_expired(&table_weak); + assert_expired(&foreign_weak); +} + +#[test] +fn sdk_struct_result_outlives_method_and_keeps_metadata() { + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let typ = table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &[table.f64_type(), table.f64_type(), table.f64_type()], + ); + let method = table + .register_interface("IGeopoint", IGeopoint::IID) + .add_method("get_Position", MethodSignature::new(&table).add_out(typ)) + .method(6) + .unwrap(); + drop(table); + let point: IGeopoint = Geopoint::Create(BasicGeoposition { + Latitude: 12.0, + Longitude: 34.0, + Altitude: 56.0, + }) + .unwrap() + .cast() + .unwrap(); + let result = method.invoke(point.as_raw(), &[]).unwrap(); + drop(method); + assert!(weak.upgrade().is_some()); + let value = result[0].as_struct().unwrap(); + assert_eq!(value.get_field::(0), 12.0); + assert_eq!(value.get_field::(2), 56.0); + assert_eq!( + value.type_handle().signature_string(), + "struct(Windows.Devices.Geolocation.BasicGeoposition;f8;f8;f8)" + ); + drop(result); + assert_expired(&weak); +} + +#[test] +fn method_clones_are_callable_concurrently_after_original_owners_drop() { + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let method = table + .register_interface("IUriRuntimeClassFactory", IUriRuntimeClassFactory::IID) + .add_method( + "CreateUri", + MethodSignature::new(&table) + .add_in(table.hstring()) + .add_out(table.object()), + ) + .method(6) + .unwrap(); + let threads: Vec<_> = (0..8) + .map(|_| { + let method = method.clone(); + std::thread::spawn(move || { + let _apartment = Apartment::new(); + let factory = + WinRTValue::from_activation_factory(&HSTRING::from("Windows.Foundation.Uri")) + .unwrap() + .cast(&IUriRuntimeClassFactory::IID) + .unwrap() + .as_object() + .unwrap(); + for _ in 0..8 { + let result = method + .invoke( + factory.as_raw(), + &[WinRTValue::HString(HSTRING::from( + "https://example.com/threads", + ))], + ) + .unwrap(); + let uri: Uri = result[0].as_object().unwrap().cast().unwrap(); + assert_eq!(uri.Host().unwrap(), "example.com"); + } + }) + }) + .collect(); + drop(table); + drop(method); + for thread in threads { + thread.join().unwrap(); + } + assert_expired(&weak); +} + +#[test] +fn sdk_array_and_enum_outputs_keep_their_metadata_until_drop() { + use windows::Foundation::{IPropertyValue, PropertyType, PropertyValue}; + + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let enum_type = table.enum_type( + "Windows.Foundation.PropertyType", + vec![("Int32Array".into(), PropertyType::Int32Array.0)], + ); + let mut interface = table + .register_interface("IPropertyValue", IPropertyValue::IID) + .add_method("get_Type", MethodSignature::new(&table).add_out(enum_type)); + for (name, typ) in [ + ("get_IsNumericScalar", table.bool_type()), + ("GetUInt8", table.u8_type()), + ("GetInt16", table.i16_type()), + ("GetUInt16", table.u16_type()), + ("GetInt32", table.i32_type()), + ("GetUInt32", table.u32_type()), + ("GetInt64", table.i64_type()), + ("GetUInt64", table.u64_type()), + ("GetSingle", table.f32_type()), + ("GetDouble", table.f64_type()), + ("GetChar16", table.char16_type()), + ("GetBoolean", table.bool_type()), + ("GetString", table.hstring()), + ("GetGuid", table.guid_type()), + ( + "GetDateTime", + table.struct_type("Windows.Foundation.DateTime", &[table.i64_type()]), + ), + ( + "GetTimeSpan", + table.struct_type("Windows.Foundation.TimeSpan", &[table.i64_type()]), + ), + ( + "GetPoint", + table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ), + ), + ( + "GetSize", + table.struct_type( + "Windows.Foundation.Size", + &[table.f32_type(), table.f32_type()], + ), + ), + ( + "GetRect", + table.struct_type( + "Windows.Foundation.Rect", + &[ + table.f32_type(), + table.f32_type(), + table.f32_type(), + table.f32_type(), + ], + ), + ), + ("GetUInt8Array", table.array(&table.u8_type())), + ("GetInt16Array", table.array(&table.i16_type())), + ("GetUInt16Array", table.array(&table.u16_type())), + ("GetInt32Array", table.array(&table.i32_type())), + ] { + interface = interface.add_method(name, MethodSignature::new(&table).add_out(typ)); + } + let getter = interface.method(6).unwrap(); + let array_getter = interface.method(29).unwrap(); + drop(interface); + drop(table); + let property: IPropertyValue = PropertyValue::CreateInt32Array(&[10, 20, 30]) + .unwrap() + .cast() + .unwrap(); + let enumeration = getter.invoke(property.as_raw(), &[]).unwrap(); + let array = array_getter.invoke(property.as_raw(), &[]).unwrap(); + drop(getter); + drop(array_getter); + let WinRTValue::Enum { value, type_handle } = &enumeration[0] else { + panic!("expected enum result") + }; + assert_eq!(*value, PropertyType::Int32Array.0); + assert_eq!( + type_handle.enum_member_name(*value).as_deref(), + Some("Int32Array") + ); + drop(enumeration); + assert!(weak.upgrade().is_some()); + assert_eq!(array[0].as_array().unwrap().get_i32(2).unwrap(), 30); + drop(array); + assert_expired(&weak); +} + +#[test] +fn sdk_async_result_keeps_result_and_progress_metadata_until_drop() { + use windows::Storage::Streams::{Buffer, IBuffer, IOutputStream, InMemoryRandomAccessStream}; + + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let async_type = table.async_operation_with_progress(&table.u32_type(), &table.u32_type()); + let method = table + .register_interface("IOutputStream", IOutputStream::IID) + .add_method( + "WriteAsync", + MethodSignature::new(&table) + .add_in(table.interface(IBuffer::IID)) + .add_out(async_type), + ) + .method(6) + .unwrap(); + let stream: IOutputStream = InMemoryRandomAccessStream::new().unwrap().cast().unwrap(); + let buffer = Buffer::Create(16).unwrap(); + buffer.SetLength(16).unwrap(); + drop(table); + let result = method + .invoke( + stream.as_raw(), + &[WinRTValue::Object(buffer.cast().unwrap())], + ) + .unwrap(); + drop(method); + let WinRTValue::Async(info) = &result[0] else { + panic!("expected async result") + }; + assert_eq!(info.result_type().unwrap().signature_string(), "u4"); + assert_eq!(info.progress_type().unwrap().signature_string(), "u4"); + assert!(matches!( + futures::executor::block_on(async { (&result[0]).await }).unwrap(), + WinRTValue::U32(16) + )); + assert!(weak.upgrade().is_some()); + drop(result); + assert_expired(&weak); +} + +#[test] +fn delegate_keeps_parameter_metadata_until_final_release() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use windows::Foundation::{IMemoryBufferReference, TypedEventHandler}; + use windows_core::{HRESULT, IInspectable}; + + type Handler = TypedEventHandler; + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + drop(stringable(&table)); + let calls = Arc::new(AtomicUsize::new(0)); + let callback_calls = calls.clone(); + let delegate: Handler = dynwinrt::delegate::try_create_delegate( + Handler::IID, + vec![table.interface(IMemoryBufferReference::IID), table.object()], + Box::new(move |args| { + assert_eq!(args.len(), 2); + callback_calls.fetch_add(1, Ordering::SeqCst); + HRESULT(0) + }), + ) + .unwrap() + .cast() + .unwrap(); + drop(table); + let reference = MemoryBuffer::Create(16).unwrap().CreateReference().unwrap(); + delegate.Invoke(&reference, None).unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(weak.upgrade().is_some()); + drop(delegate); + assert_expired(&weak); +} + +#[test] +fn reverse_call_can_reenter_registration_without_retaining_registry() { + use dynwinrt::{ + WinRtImplementation, WinRtImplementationPlan, WinRtInterfaceDefinition, + WinRtMethodDefinition, WinRtThreadingPolicy, + }; + + let _apartment = Apartment::new(); + let table = MetadataTable::new(); + let weak = Arc::downgrade(&table); + let method = stringable(&table).method(6).unwrap(); + let plan = WinRtImplementationPlan::new( + vec![WinRtInterfaceDefinition { + name: "IStringable".into(), + interface_type: table.interface(IStringable::IID), + required_iids: vec![], + methods: vec![WinRtMethodDefinition { + name: "ToString".into(), + vtable_index: 6, + signature: MethodSignature::new(&table).add_out(table.hstring()), + }], + }], + WinRtThreadingPolicy::OwnerThread, + ) + .unwrap(); + let callback_table = table.clone(); + let owner = WinRtImplementation::new( + plan, + Arc::new(move |_, _, _| { + drop( + callback_table + .register_interface("IClosable", IClosable::IID) + .add_method("Close", MethodSignature::new(&callback_table)), + ); + Ok(vec![WinRTValue::HString(HSTRING::from("reentrant"))]) + }), + None, + ) + .unwrap(); + drop(table); + let object = owner + .to_value() + .unwrap() + .cast(&IStringable::IID) + .unwrap() + .as_object() + .unwrap(); + assert_eq!( + method.invoke(object.as_raw(), &[]).unwrap()[0] + .as_hstring() + .unwrap(), + "reentrant" + ); + drop(method); + assert_eq!( + object.cast::().unwrap().ToString().unwrap(), + "reentrant" + ); + drop(object); + drop(owner); + assert_expired(&weak); +} + +#[test] +fn classic_com_methods_keep_foreign_parameter_owners_without_registry_cycles() { + use dynwinrt::com; + + let table = MetadataTable::new(); + let foreign = MetadataTable::new(); + let local_weak = Arc::downgrade(&table); + let foreign_weak = Arc::downgrade(&foreign); + drop(stringable(&table)); + drop(stringable(&foreign)); + let interface = com::register_interface( + &table, + "Lifetime", + IStringable::IID, + com::InterfaceBase::IUnknown, + ) + .add_method( + "Method", + com::MethodSignature::new(&table).add_in(com::Type::winrt(foreign.i32_type())), + ); + let method = interface.method(3).unwrap(); + drop(interface); + drop(table); + drop(foreign); + assert_expired(&local_weak); + assert!(foreign_weak.upgrade().is_some()); + drop(method); + assert_expired(&foreign_weak); +} diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index d12fc9d2..33f3197f 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -59,6 +59,12 @@ the same private backend, but only their respective semantic layers may decide what a type, parameter direction, return convention, or ownership contract means. +The shared prepared-call allocation owns only its immutable execution strategy +and libffi type graph, not a metadata registry. WinRT registration stores local +type kinds and binds owning types in external method handles. Classic COM keeps +its own owning parameter/return contracts and method registry; the WinRT +same-table registration restriction does not apply to it. + In particular: - WinRT interface methods remain in the WinRT `MetadataTable` and begin at diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md index 35bf4be6..43c76724 100644 --- a/docs/architecture/winrt-interface-implementations.md +++ b/docs/architecture/winrt-interface-implementations.md @@ -49,6 +49,23 @@ for structs, enums, and runtime classes, so an interface cannot alias or replace one of those named types. JavaScript and Python use this same core registry; generated public names and the separate Classic COM registry are unchanged. +Registered method parameter types must belong to the destination +`MetadataTable`. Passing a foreign-table parameter to `TypeHandle::add_method` +panics before changing or locking the method table, even for a duplicate method +name. The signature's constructor table may differ when every actual parameter +is local; zero-parameter signatures are also accepted. Standalone +`MethodSignature::build` calls retain their existing cross-table behavior. + +The registry stores local type kinds and immutable prepared ABI plans, not +owning parameter handles. Each external `MethodHandle` binds those kinds to +strong type handles once at lookup and keeps its registry alive, including for +zero-parameter methods. Clones share the bound method; separate lookups share +the prepared plan. Calls do not rebuild the CIF or hold a registry lock. +Public type handles, signatures, and typed results retain their normal strong +ownership. An independent registry and its prepared plans can therefore be +released after the last external owner drops, without an internal reference +cycle. The JavaScript and Python global registry lifetime is unchanged. + ## Native object model The canonical identity is an IInspectable-rooted allocation. Every interface diff --git a/docs/status/TODO.md b/docs/status/TODO.md index 4f3c00be..6f9e80f3 100644 --- a/docs/status/TODO.md +++ b/docs/status/TODO.md @@ -129,11 +129,6 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy - [ ] **Value-type inputs to `invoke()`**. `invoke()` currently requires `DynWinRtValue` wrappers per argument (`+~0.6-1.6 µs / arg`). Accept raw JS values (`number`/`string`/`bool`) and dispatch via `in_param_types()` on `MethodHandle`. -- [ ] **Method handle without an arena read lock**. `MethodHandle` stores an - arena index; each call briefly reads `AppendOnlyBoxArena` to obtain its - stable method pointer. Store a stable method handle directly if benchmark - results justify removing that lock. - - [ ] **Stack-allocated return path**. `Ok(vec![out])` heap-allocates per call. `SmallVec<[WinRTValue; 2]>` for the common single-out shape. - [ ] **JS binding: raw `Env` lifetime discipline**. The same-thread delegate