Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 4 additions & 21 deletions crates/dynwinrt/src/metadata_table/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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);
Expand Down Expand Up @@ -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<Vec<WinRTValue>> {
// 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)
}

Expand Down
114 changes: 85 additions & 29 deletions crates/dynwinrt/src/metadata_table/method_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MetadataTable>,
// Keep even zero-parameter methods' registry alive.
_table: Arc<MetadataTable>,
pub(crate) index: u32,
method: Arc<crate::signature::Method>,
}

impl std::fmt::Debug for MethodHandle {
Expand All @@ -24,7 +26,14 @@ impl std::fmt::Debug for MethodHandle {

impl MethodHandle {
pub(crate) fn new(table: Arc<MetadataTable>, 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.
Expand All @@ -33,51 +42,50 @@ impl MethodHandle {
obj: *mut std::ffi::c_void,
args: &[WinRTValue],
) -> crate::result::Result<Vec<WinRTValue>> {
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<i32> {
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<bool> {
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<windows_core::HSTRING> {
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)
}

pub fn call_getter_object(
&self,
obj: *mut std::ffi::c_void,
) -> crate::result::Result<WinRTValue> {
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(
&self,
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)
}

Expand All @@ -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)
}

Expand All @@ -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)
}

Expand All @@ -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)
}

Expand All @@ -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)
}

Expand All @@ -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<T: Send + Sync>() {}
assert_send_sync::<PreparedCall>();
assert_send_sync::<MetadataTable>();
assert_send_sync::<TypeHandle>();
assert_send_sync::<MethodHandle>();
assert_send_sync::<crate::signature::Method>();

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());
}
}
30 changes: 9 additions & 21 deletions crates/dynwinrt/src/metadata_table/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand All @@ -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<Method>` 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<Method>,
// 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<RegisteredMethod>,

// --- Indexes (no data duplication, only pointers) ---
/// IID → method table for O(1) interface method lookup.
Expand All @@ -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<Self> {
Arc::new(MetadataTable {
Expand Down
9 changes: 9 additions & 0 deletions crates/dynwinrt/src/metadata_table/type_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
Loading
Loading