From 4f670fad9f93f150f83335a486024b3620a8b039 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Mon, 31 Aug 2026 22:51:21 +0800 Subject: [PATCH 1/4] Support struct-valued WinRT progress callbacks Route by-value WinRT structs through cached ABI-aware libffi closures, retain nested non-blittable fields for asynchronous dispatch, and enable fail-closed JS/Python progress projection with loopback HttpProgress coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/src/lib.rs | 59 +++ bindings/py/src/async_runtime.rs | 50 ++- crates/dynwinrt/src/delegate.rs | 347 +++++++++++++++++- .../dynwinrt/src/metadata_table/value_data.rs | 30 ++ tests/e2e/e2e_specs.json | 14 + tests/e2e/e2e_specs.schema.json | 1 + tests/e2e/runners/py_runner.py | 98 +++++ tests/e2e/runners/ts_runner.ts | 92 +++++ .../tests/ireference_struct_field_test.rs | 10 + 9 files changed, 682 insertions(+), 19 deletions(-) diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index fb259abb..be7980a4 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -33,6 +33,44 @@ mod tsfn_test_hooks; static TABLE: std::sync::LazyLock> = std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new()); +fn ensure_progress_type_supported(progress_type: &dynwinrt::TypeHandle) -> napi::Result<()> { + match progress_type.kind() { + dynwinrt::TypeKind::Guid + | dynwinrt::TypeKind::ArrayOfIUnknown + | dynwinrt::TypeKind::Generic { .. } + | dynwinrt::TypeKind::OutValue(_) + | dynwinrt::TypeKind::Array(_) => Err(napi::Error::from_reason(format!( + "onProgress: progress callbacks do not support {:?} values", + progress_type.kind() + ))), + dynwinrt::TypeKind::Bool + | dynwinrt::TypeKind::I8 + | dynwinrt::TypeKind::U8 + | dynwinrt::TypeKind::I16 + | dynwinrt::TypeKind::U16 + | dynwinrt::TypeKind::Char16 + | dynwinrt::TypeKind::I32 + | dynwinrt::TypeKind::U32 + | dynwinrt::TypeKind::I64 + | dynwinrt::TypeKind::U64 + | dynwinrt::TypeKind::F32 + | dynwinrt::TypeKind::F64 + | dynwinrt::TypeKind::HString + | dynwinrt::TypeKind::Object + | dynwinrt::TypeKind::HResult + | dynwinrt::TypeKind::Interface(_) + | dynwinrt::TypeKind::Delegate(_) + | dynwinrt::TypeKind::IAsyncAction + | dynwinrt::TypeKind::IAsyncActionWithProgress(_) + | dynwinrt::TypeKind::IAsyncOperation(_) + | dynwinrt::TypeKind::IAsyncOperationWithProgress(_) + | dynwinrt::TypeKind::RuntimeClass(_) + | dynwinrt::TypeKind::Parameterized(_) + | dynwinrt::TypeKind::Enum(_) + | dynwinrt::TypeKind::Struct(_) => Ok(()), + } +} + // ====================================================================== // Runtime initialization // ====================================================================== @@ -1319,6 +1357,7 @@ impl DynWinRTValue { let progress_type = async_info .progress_type() .ok_or_else(|| napi::Error::from_reason("onProgress: not a WithProgress async type"))?; + ensure_progress_type_supported(&progress_type)?; let handler_iid = async_info .progress_handler_iid() @@ -1914,6 +1953,26 @@ mod js_boundary_tests { [0x80004005u32 as i32], ); } + + #[test] + fn progress_type_validation_allows_structs_and_rejects_unsupported_shapes() { + let progress = TABLE.struct_type("Test.JsStructProgress", &[TABLE.u64_type()]); + assert!(ensure_progress_type_supported(&progress).is_ok()); + + let value_type = TABLE.u32_type(); + for unsupported in [ + TABLE.guid_type(), + TABLE.array_of_iunknown(), + TABLE.generic( + windows::core::GUID::from_u128(0x11111111_2222_3333_4444_555555555555), + 1, + ), + TABLE.out_value(&value_type), + TABLE.array(&value_type), + ] { + assert!(ensure_progress_type_supported(&unsupported).is_err()); + } + } } // ====================================================================== diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index 644dcbb9..c31e866b 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -53,12 +53,35 @@ pub(crate) fn ensure_progress_type_supported(progress_type: &dynwinrt::TypeHandl | dynwinrt::TypeKind::ArrayOfIUnknown | dynwinrt::TypeKind::Generic { .. } | dynwinrt::TypeKind::OutValue(_) - | dynwinrt::TypeKind::Struct(_) | dynwinrt::TypeKind::Array(_) => Err(PyRuntimeError::new_err(format!( - "progress callbacks do not yet support {:?} values", + "progress callbacks do not support {:?} values", progress_type.kind() ))), - _ => Ok(()), + dynwinrt::TypeKind::Bool + | dynwinrt::TypeKind::I8 + | dynwinrt::TypeKind::U8 + | dynwinrt::TypeKind::I16 + | dynwinrt::TypeKind::U16 + | dynwinrt::TypeKind::Char16 + | dynwinrt::TypeKind::I32 + | dynwinrt::TypeKind::U32 + | dynwinrt::TypeKind::I64 + | dynwinrt::TypeKind::U64 + | dynwinrt::TypeKind::F32 + | dynwinrt::TypeKind::F64 + | dynwinrt::TypeKind::HString + | dynwinrt::TypeKind::Object + | dynwinrt::TypeKind::HResult + | dynwinrt::TypeKind::Interface(_) + | dynwinrt::TypeKind::Delegate(_) + | dynwinrt::TypeKind::IAsyncAction + | dynwinrt::TypeKind::IAsyncActionWithProgress(_) + | dynwinrt::TypeKind::IAsyncOperation(_) + | dynwinrt::TypeKind::IAsyncOperationWithProgress(_) + | dynwinrt::TypeKind::RuntimeClass(_) + | dynwinrt::TypeKind::Parameterized(_) + | dynwinrt::TypeKind::Enum(_) + | dynwinrt::TypeKind::Struct(_) => Ok(()), } } @@ -476,4 +499,25 @@ mod tests { let result = finish_progress_registration(Err(set_progress_error()), || Ok(true)); assert!(result.is_err()); } + + #[test] + fn progress_type_validation_allows_structs_and_rejects_unsupported_shapes() { + let table = dynwinrt::MetadataTable::new(); + let progress = table.struct_type("Test.PythonStructProgress", &[table.u64_type()]); + assert!(ensure_progress_type_supported(&progress).is_ok()); + + let value_type = table.u32_type(); + for unsupported in [ + table.guid_type(), + table.array_of_iunknown(), + table.generic( + windows::core::GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee), + 1, + ), + table.out_value(&value_type), + table.array(&value_type), + ] { + assert!(ensure_progress_type_supported(&unsupported).is_err()); + } + } } diff --git a/crates/dynwinrt/src/delegate.rs b/crates/dynwinrt/src/delegate.rs index d38233d6..12f362e4 100644 --- a/crates/dynwinrt/src/delegate.rs +++ b/crates/dynwinrt/src/delegate.rs @@ -11,9 +11,14 @@ use core::ffi::c_void; use windows_core::{GUID, HRESULT, IUnknown, Interface}; use windows_future::IAsyncInfo; -use crate::metadata_table::TypeHandle; +use crate::metadata_table::{TypeHandle, ValueTypeData}; +use crate::native_callback::{CallbackAbiType, CallbackSignature}; use crate::value::{AsyncInfo, WinRTValue}; +const E_FAIL: HRESULT = HRESULT(0x80004005u32 as i32); +const E_NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); +const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); + // ====================================================================== // DynamicDelegate — general-purpose WinRT delegate COM object // ====================================================================== @@ -21,7 +26,7 @@ use crate::value::{AsyncInfo, WinRTValue}; /// Callback type: receives marshalled Invoke arguments, returns HRESULT. pub type DelegateCallback = Box HRESULT + Send + Sync>; -/// Vtable for a delegate with 2 pointer-sized ABI params (covers ~95% of delegates). +/// Static vtable for a delegate with two general-purpose-register parameters. #[repr(C)] struct Delegate2Vtbl { base: windows_core::IUnknown_Vtbl, @@ -58,18 +63,27 @@ struct Delegate1F32Vtbl { invoke: unsafe extern "system" fn(*mut c_void, f32) -> HRESULT, } +#[repr(C)] +struct DynamicDelegateVtbl { + base: windows_core::IUnknown_Vtbl, + invoke: *const c_void, +} + /// A dynamically-constructed WinRT delegate COM object. /// -/// Supports delegates with up to 2 ABI parameters (pointer-sized). +/// Supports delegates with up to 2 ABI parameters. Struct parameters use an +/// ABI-aware libffi closure; established scalar and float shapes keep their +/// static trampolines. /// This covers TypedEventHandler, AsyncOperationCompletedHandler, /// EventHandler, and most other standard delegates. #[repr(C)] struct DynamicDelegate { - vtable: *const Delegate2Vtbl, + vtable: *const c_void, ref_count: windows_core::imp::RefCount, delegate_iid: GUID, param_types: Vec, callback: DelegateCallback, + _owned_vtable: Option>, } // Safety: DynamicDelegate is ref-counted and the callback is Send+Sync. @@ -140,21 +154,45 @@ impl DynamicDelegate { use crate::metadata_table::TypeKind; + let owned_vtable = if param_types + .iter() + .any(|typ| matches!(typ.kind(), TypeKind::Struct(_))) + { + let signature = Self::libffi_signature(¶m_types) + .expect("unsupported WinRT delegate parameter type used with a struct"); + let invoke = crate::native_callback::callback_code(3, signature, Self::invoke_libffi) + .expect("failed to create the WinRT delegate callback closure"); + Some(Box::new(DynamicDelegateVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::qi, + AddRef: Self::add_ref, + Release: Self::release, + }, + invoke, + })) + } else { + None + }; + // Pick the right vtable based on parameter types. // Float types go in float registers on ARM64/x64, so each distinct // float signature needs its own trampoline with the correct ABI. - let vtable: *const Delegate2Vtbl = match param_types.len() { - 1 => match param_types[0].kind() { - TypeKind::F64 => &Self::VTBL_1_F64 as *const _ as *const Delegate2Vtbl, - TypeKind::F32 => &Self::VTBL_1_F32 as *const _ as *const Delegate2Vtbl, - _ => &Self::VTBL, - }, - 2 => match param_types[1].kind() { - TypeKind::F64 => &Self::VTBL_PTR_F64 as *const _ as *const Delegate2Vtbl, - TypeKind::F32 => &Self::VTBL_PTR_F32 as *const _ as *const Delegate2Vtbl, - _ => &Self::VTBL, - }, - _ => &Self::VTBL, + let vtable = if let Some(vtable) = owned_vtable.as_deref() { + vtable as *const DynamicDelegateVtbl as *const c_void + } else { + match param_types.len() { + 1 => match param_types[0].kind() { + TypeKind::F64 => &Self::VTBL_1_F64 as *const _ as *const c_void, + TypeKind::F32 => &Self::VTBL_1_F32 as *const _ as *const c_void, + _ => &Self::VTBL as *const _ as *const c_void, + }, + 2 => match param_types[1].kind() { + TypeKind::F64 => &Self::VTBL_PTR_F64 as *const _ as *const c_void, + TypeKind::F32 => &Self::VTBL_PTR_F32 as *const _ as *const c_void, + _ => &Self::VTBL as *const _ as *const c_void, + }, + _ => &Self::VTBL as *const _ as *const c_void, + } }; let delegate = Box::new(Self { @@ -163,10 +201,58 @@ impl DynamicDelegate { delegate_iid, param_types, callback, + _owned_vtable: owned_vtable, }); unsafe { IUnknown::from_raw(Box::into_raw(delegate) as *mut c_void) } } + fn libffi_signature(param_types: &[TypeHandle]) -> Option { + let parameters = param_types + .iter() + .map(|typ| Some((Self::callback_abi_type(typ)?, typ.libffi_type()))) + .collect::>>()?; + Some(CallbackSignature::hresult(parameters)) + } + + fn callback_abi_type(typ: &TypeHandle) -> Option { + use crate::metadata_table::TypeKind; + + match typ.kind() { + TypeKind::I8 => Some(CallbackAbiType::I8), + TypeKind::Bool | TypeKind::U8 => Some(CallbackAbiType::U8), + TypeKind::I16 => Some(CallbackAbiType::I16), + TypeKind::U16 | TypeKind::Char16 => Some(CallbackAbiType::U16), + TypeKind::I32 | TypeKind::HResult | TypeKind::Enum(_) => Some(CallbackAbiType::I32), + TypeKind::U32 => Some(CallbackAbiType::U32), + TypeKind::I64 => Some(CallbackAbiType::I64), + TypeKind::U64 => Some(CallbackAbiType::U64), + TypeKind::F32 => Some(CallbackAbiType::F32), + TypeKind::F64 => Some(CallbackAbiType::F64), + TypeKind::Guid => Some(CallbackAbiType::Guid), + TypeKind::HString + | TypeKind::Object + | TypeKind::Interface(_) + | TypeKind::Delegate(_) + | TypeKind::RuntimeClass(_) + | TypeKind::Parameterized(_) + | TypeKind::IAsyncAction + | TypeKind::IAsyncActionWithProgress(_) + | TypeKind::IAsyncOperation(_) + | TypeKind::IAsyncOperationWithProgress(_) => Some(CallbackAbiType::Pointer), + // The full recursive WinRT signature identifies the ABI layout in + // the process-wide closure cache. Dispatch still recovers the + // table-qualified TypeHandle from the delegate instance. + TypeKind::Struct(_) => Some(CallbackAbiType::NativeStruct( + typ.signature_string(), + typ.size_of(), + )), + TypeKind::ArrayOfIUnknown + | TypeKind::Generic { .. } + | TypeKind::OutValue(_) + | TypeKind::Array(_) => None, + } + } + // ------------------------------------------------------------------ // IUnknown // ------------------------------------------------------------------ @@ -295,6 +381,43 @@ impl DynamicDelegate { let delegate = unsafe { &*(this as *const Self) }; (delegate.callback)(&[WinRTValue::F32(arg0)]) } + + unsafe fn invoke_libffi( + _slot: usize, + signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, + ) { + if result.is_null() { + return; + } + unsafe { signature.initialize_failure_result(result, E_FAIL) }; + let invocation = (|| -> Result { + if args.is_null() { + return Err(E_POINTER); + } + let this_storage = unsafe { *args }; + if this_storage.is_null() { + return Err(E_POINTER); + } + let this = unsafe { *this_storage.cast::<*mut c_void>() }; + if this.is_null() { + return Err(E_POINTER); + } + let delegate = unsafe { &*(this.cast::()) }; + if signature.parameters().len() != delegate.param_types.len() { + return Err(E_FAIL); + } + let mut values = Vec::with_capacity(delegate.param_types.len()); + for (index, typ) in delegate.param_types.iter().enumerate() { + let storage = unsafe { *args.add(index + 1) }; + values.push(unsafe { marshal_libffi_arg(storage, typ)? }); + } + Ok((delegate.callback)(&values)) + })(); + let hresult = invocation.unwrap_or_else(|error| error); + unsafe { result.cast::().write(hresult.0) }; + } } /// Convert a raw ABI pointer-sized argument to WinRTValue, based on type. @@ -367,6 +490,63 @@ fn marshal_abi_ptr(raw: *mut c_void, typ: &TypeHandle) -> Result Result { + use crate::metadata_table::TypeKind; + + if storage.is_null() { + return Err(E_POINTER); + } + match typ.kind() { + TypeKind::Bool => Ok(WinRTValue::Bool(unsafe { *storage.cast::() } != 0)), + TypeKind::I8 => Ok(WinRTValue::I8(unsafe { *storage.cast::() })), + TypeKind::U8 => Ok(WinRTValue::U8(unsafe { *storage.cast::() })), + TypeKind::I16 => Ok(WinRTValue::I16(unsafe { *storage.cast::() })), + TypeKind::U16 | TypeKind::Char16 => Ok(WinRTValue::U16(unsafe { *storage.cast::() })), + TypeKind::I32 => Ok(WinRTValue::I32(unsafe { *storage.cast::() })), + TypeKind::Enum(_) => Ok(WinRTValue::Enum { + value: unsafe { *storage.cast::() }, + type_handle: typ.clone(), + }), + TypeKind::U32 => Ok(WinRTValue::U32(unsafe { *storage.cast::() })), + TypeKind::HResult => Ok(WinRTValue::HResult(HRESULT(unsafe { + *storage.cast::() + }))), + TypeKind::I64 => Ok(WinRTValue::I64(unsafe { *storage.cast::() })), + TypeKind::U64 => Ok(WinRTValue::U64(unsafe { *storage.cast::() })), + TypeKind::F32 => Ok(WinRTValue::F32(unsafe { *storage.cast::() })), + TypeKind::F64 => Ok(WinRTValue::F64(unsafe { *storage.cast::() })), + TypeKind::Guid => Ok(WinRTValue::Guid(unsafe { *storage.cast::() })), + TypeKind::Struct(_) => Ok(WinRTValue::Struct(unsafe { + ValueTypeData::from_borrowed_abi(typ, storage) + })), + TypeKind::HString + | TypeKind::Object + | TypeKind::Interface(_) + | TypeKind::Delegate(_) + | TypeKind::RuntimeClass(_) + | TypeKind::Parameterized(_) + | TypeKind::IAsyncAction + | TypeKind::IAsyncActionWithProgress(_) + | TypeKind::IAsyncOperation(_) + | TypeKind::IAsyncOperationWithProgress(_) => { + let raw = unsafe { *storage.cast::<*mut c_void>() }; + marshal_abi_ptr(raw, typ) + } + TypeKind::ArrayOfIUnknown + | TypeKind::Generic { .. } + | TypeKind::OutValue(_) + | TypeKind::Array(_) => Err(E_NOTIMPL), + } +} + // ====================================================================== // Public API // ====================================================================== @@ -410,6 +590,13 @@ mod tests { Arc, atomic::{AtomicBool, Ordering}, }; + use windows_core::IUnknown_Vtbl; + + #[repr(C)] + struct StructProgressHandlerVtbl { + base: IUnknown_Vtbl, + invoke: unsafe extern "system" fn(*mut c_void, *mut c_void, T) -> HRESULT, + } /// P2: Verify that a 2-param delegate with f32 second param /// correctly receives F32 (not F64) via the f32 trampoline. @@ -505,4 +692,132 @@ mod tests { assert_eq!(hr, HRESULT(0)); assert!(called.load(Ordering::SeqCst)); } + + #[test] + fn test_delegate_struct_trampoline_marshals_wide_value() { + #[repr(C)] + #[derive(Clone, Copy)] + struct WideProgress { + completed: u64, + total: u64, + stage: u32, + } + + let table = MetadataTable::new(); + let progress_type = table.struct_type( + "Test.WideProgress", + &[table.u64_type(), table.u64_type(), table.u32_type()], + ); + assert!(progress_type.size_of() > std::mem::size_of::()); + + let received = Arc::new(std::sync::Mutex::new(None)); + let received_callback = received.clone(); + let handler = create_delegate( + GUID::from_u128(0x44444444_4444_4444_4444_444444444444), + vec![table.object(), progress_type.clone()], + Box::new(move |args| { + *received_callback.lock().unwrap() = Some(args[1].clone()); + HRESULT(0) + }), + ); + + let vtable = unsafe { + &**(handler.as_raw() as *const *const StructProgressHandlerVtbl) + }; + let result = unsafe { + (vtable.invoke)( + handler.as_raw(), + std::ptr::null_mut(), + WideProgress { + completed: 17, + total: 42, + stage: 3, + }, + ) + }; + assert_eq!(result, HRESULT(0)); + + let received = received.lock().unwrap().take().unwrap(); + let data = received.as_struct().unwrap(); + assert_eq!(data.type_handle(), &progress_type); + assert_eq!(data.get_field::(0), 17); + assert_eq!(data.get_field::(1), 42); + assert_eq!(data.get_field::(2), 3); + } + + #[test] + fn test_delegate_struct_trampoline_owns_nested_non_blittable_fields() { + #[repr(C)] + #[derive(Clone, Copy)] + struct ReferenceProgress { + label: *mut c_void, + total: *mut c_void, + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct NestedProgress { + sequence: u64, + reference: ReferenceProgress, + } + + let table = MetadataTable::new(); + let value_type = table.u64_type(); + let generic = table.generic(crate::metadata_table::IREFERENCE, 1); + let reference_type = table.parameterized(&generic, std::slice::from_ref(&value_type)); + let reference_progress = + table.struct_type("Test.ReferenceProgress", &[table.hstring(), reference_type]); + let progress_type = table.struct_type( + "Test.NestedReferenceProgress", + &[table.u64_type(), reference_progress], + ); + + let label = windows_core::HSTRING::from("retained progress"); + let label_raw: *mut c_void = unsafe { std::mem::transmute_copy(&label) }; + let boxed = crate::box_ireference(WinRTValue::U64(99), value_type).unwrap(); + let boxed_object = boxed.as_object().unwrap(); + + let received = Arc::new(std::sync::Mutex::new(None)); + let received_callback = received.clone(); + let handler = create_delegate( + GUID::from_u128(0x55555555_5555_5555_5555_555555555555), + vec![table.object(), progress_type.clone()], + Box::new(move |args| { + *received_callback.lock().unwrap() = Some(args[1].clone()); + HRESULT(0) + }), + ); + + let vtable = unsafe { + &**(handler.as_raw() as *const *const StructProgressHandlerVtbl) + }; + let result = unsafe { + (vtable.invoke)( + handler.as_raw(), + std::ptr::null_mut(), + NestedProgress { + sequence: 7, + reference: ReferenceProgress { + label: label_raw, + total: boxed_object.as_raw(), + }, + }, + ) + }; + assert_eq!(result, HRESULT(0)); + + drop(boxed); + drop(boxed_object); + drop(label); + + let received = received.lock().unwrap().take().unwrap(); + let data = received.as_struct().unwrap(); + assert_eq!(data.type_handle(), &progress_type); + assert_eq!(data.get_field::(0), 7); + let reference = data.get_field_struct(1); + assert_eq!(reference.get_field_hstring(0).unwrap(), "retained progress"); + let total = reference.get_field_object(1).unwrap().unwrap(); + let total: windows::Foundation::IReference = total.cast().unwrap(); + assert_eq!(total.Value().unwrap(), 99); + } } diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 9d9bc2d2..6e9942ab 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -139,6 +139,36 @@ impl ValueTypeData { } } + /// Copies a borrowed ABI struct into owned storage, retaining every + /// non-blittable field so the result can outlive the native callback. + /// + /// # Safety + /// + /// `source` must point to a readable ABI value matching `handle` for the + /// duration of this call. + pub(crate) unsafe fn from_borrowed_abi(handle: &TypeHandle, source: *const c_void) -> Self { + assert!( + matches!(handle.kind(), TypeKind::Struct(_)), + "from_borrowed_abi requires a struct type" + ); + let result = Self::new(handle); + let size = handle.size_of(); + if size == 0 { + return result; + } + assert!( + !source.is_null(), + "from_borrowed_abi requires non-null storage for a non-empty struct" + ); + unsafe { + std::ptr::copy_nonoverlapping(source.cast::(), result.ptr, size); + if has_non_blittable_fields(handle) { + duplicate_non_blittable_fields(handle, result.ptr); + } + } + result + } + pub fn type_handle(&self) -> &TypeHandle { &self.type_handle } diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index c2963bf3..a24ad07f 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -612,6 +612,20 @@ { "kind": "vector_index_of", "member": "languages", "search_value": "xx-NONEXISTENT", "expected_index": -1 } ] }, + { + "id": "http_client_struct_progress", + "namespace": "Windows.Web.Http", + "class": "HttpClient", + "langs": ["py", "ts"], + "instantiate": { "kind": "static_factory", "method": "create_default" }, + "checks": [ + { + "kind": "async_struct_progress", + "member": "get_string_async", + "expected_type": "HttpProgress" + } + ] + }, { "id": "python_generated_helper_matrix", "namespace": "Windows.Foundation", diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index 94494f3a..fea7d15d 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -75,6 +75,7 @@ "cross_class_chain", "async_memory_roundtrip", "async_cancellation", + "async_struct_progress", "property_set_equals", "vector_view_access", "vector_index_of", diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index ac5aad69..0806b84f 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -16,10 +16,12 @@ import importlib import inspect import json +import http.server import re import sys import os import threading +import time _WINRT_UINT_SUFFIXES = {'int8', 'int16', 'int32', 'int64'} @@ -113,6 +115,34 @@ def wrap_arg(val): return val +def start_progress_server(): + payload = ('dynwinrt-struct-progress-' * 16_384).encode('utf-8') + + class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + + def do_GET(self): + self.send_response(200) + self.send_header('Content-Length', str(len(payload))) + self.send_header('Content-Type', 'text/plain; charset=utf-8') + self.send_header('Connection', 'close') + self.end_headers() + for offset in range(0, len(payload), 8_192): + self.wfile.write(payload[offset:offset + 8_192]) + self.wfile.flush() + time.sleep(0.005) + self.close_connection = True + + def log_message(self, _format, *_args): + pass + + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + host, port = server.server_address + return server, thread, payload.decode('utf-8'), f'http://{host}:{port}/progress' + + async def run_spec(spec: dict, generated_dir: str, pkg_name: str) -> dict: """Run a single test spec. Returns a result dict.""" ns = spec['namespace'] @@ -1976,6 +2006,74 @@ def block_on_sta(): print(f' generated helper matrix: {counters}') cr['pass'] = True + elif kind == 'async_struct_progress': + server, thread, payload, url = start_progress_server() + try: + uri_type = generated_type(pkg_name, 'Uri') + uri = uri_type(url) + progress_values = [] + operation = getattr(obj, member)(uri) + operation.progress(progress_values.append) + body = await operation + await asyncio.sleep(0.05) + + if body != payload: + cr['error'] = ( + f'loopback response mismatch: expected {len(payload)} ' + f'characters, got {len(str(body))}' + ) + return cr + expected_type = check.get('expected_type') + if ( + not progress_values + or any( + value is None + or ( + expected_type + and type(value).__name__ != expected_type + ) + for value in progress_values + ) + ): + actual_types = ', '.join( + type(value).__name__ for value in progress_values + ) or 'none' + cr['error'] = ( + f'expected projected {expected_type} progress values, ' + f'got {actual_types}' + ) + return cr + received = next( + ( + value + for value in progress_values + if value.bytes_received > 0 + and value.total_bytes_to_receive == len(payload) + ), + None, + ) + if received is None: + totals = ', '.join( + f'{value.bytes_received}/{value.total_bytes_to_receive}' + for value in progress_values + ) + cr['error'] = ( + 'progress did not retain expected receive totals: ' + f'{totals}' + ) + return cr + if ( + not isinstance(received.retries, int) + or not hasattr(received.stage, 'value') + ): + cr['error'] = 'projected progress scalar fields were invalid' + return cr + cr['pass'] = True + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + else: cr['error'] = f'unknown check kind: {kind}' diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index 2bdaa0c8..0b522220 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -14,6 +14,7 @@ import { strict as assert } from "node:assert"; import { spawn } from "node:child_process"; import * as fs from "node:fs"; +import { createServer } from "node:http"; import * as os from "node:os"; import * as path from "node:path"; import { fileURLToPath } from "node:url"; @@ -87,6 +88,50 @@ function toPascalCase(name: string): string { return camel.charAt(0).toUpperCase() + camel.slice(1); } +async function startProgressServer(): Promise<{ + payload: string; + url: string; + close: () => Promise; +}> { + const payload = "dynwinrt-struct-progress-".repeat(16_384); + const server = createServer((_request, response) => { + response.writeHead(200, { + "Content-Length": Buffer.byteLength(payload), + "Content-Type": "text/plain; charset=utf-8", + Connection: "close", + }); + let offset = 0; + const writeNext = () => { + if (offset >= payload.length) { + response.end(); + return; + } + const end = Math.min(offset + 8_192, payload.length); + response.write(payload.slice(offset, end)); + offset = end; + setTimeout(writeNext, 5); + }; + writeNext(); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + throw new Error("loopback HTTP server did not publish a TCP port"); + } + return { + payload, + url: `http://127.0.0.1:${address.port}/progress`, + close: () => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + }; +} + async function runSpec( spec: Spec, generatedDir: string, @@ -938,6 +983,53 @@ async function runCheck( } else { cr.pass = true; } + } else if (kind === "async_struct_progress") { + const server = await startProgressServer(); + try { + const uriClass = await importClass(generatedDir, "Uri"); + const uri = uriClass.createUri(server.url); + const progressValues: any[] = []; + const operation = obj[member](uri); + operation.progress((value: any) => progressValues.push(value)); + const body = await operation; + await new Promise((resolve) => setImmediate(resolve)); + + if (body !== server.payload) { + cr.error = `loopback response mismatch: expected ${server.payload.length} characters, got ${String(body).length}`; + return cr; + } + if ( + progressValues.length === 0 || + progressValues.some( + (value) => + value == null || + typeof value !== "object" || + !("stage" in value) || + !("bytesReceived" in value) || + !("totalBytesToReceive" in value) || + !("retries" in value), + ) + ) { + cr.error = `expected projected HttpProgress objects, got ${progressValues.map((value) => typeof value).join(", ") || "none"}`; + return cr; + } + const received = progressValues.find( + (value) => + value.bytesReceived > 0n && + value.totalBytesToReceive === BigInt(server.payload.length), + ); + if (!received) { + cr.error = `progress did not retain expected receive totals: ${progressValues + .map((value) => `${value.bytesReceived}/${value.totalBytesToReceive}`) + .join(", ")}`; + return cr; + } + assert.equal(typeof received.stage, "number"); + assert.equal(typeof received.retries, "number"); + cr.pass = true; + } finally { + await server.close(); + } } else { cr.error = `unknown check kind: ${kind}`; } diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index c613662e..7e5e6998 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -431,4 +431,14 @@ fn sdk_http_progress_ireference_u64_fields_are_native_optional_values() { ), "{js}" ); + assert!( + js.contains("_unpackHttpProgress(_p)") + && dts.contains("WinRTAsyncWithProgress"), + "JavaScript struct progress projection was not preserved:\n{js}\n{dts}" + ); + assert!( + py.contains("lambda value: _unpack_http_progress(value)") + && pyi.contains("WinRTAsyncWithProgress[str, 'HttpProgress']"), + "Python struct progress projection was not preserved:\n{py}\n{pyi}" + ); } From f6c456762bdfb0ac3d30c20eb4a5240e7b29055a Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Tue, 1 Sep 2026 00:12:50 +0800 Subject: [PATCH 2/4] Fix struct progress CI failures Propagate callback closure creation errors through the JavaScript and Python Result paths, and move live HttpProgress coverage into binding-level loopback tests so the shared generated coverage graph stays at its established baseline. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/__test__/index.spec.ts | 54 ++++++ .../js/__test__/struct-progress-child.mjs | 124 +++++++++++++ bindings/js/src/lib.rs | 14 +- bindings/py/src/async_runtime.rs | 8 +- bindings/py/src/runtime.rs | 25 ++- bindings/py/tests/test_basic.py | 11 ++ bindings/py/tests/test_e2e_winrt.py | 172 +++++++++++++++++- crates/dynwinrt/src/dasync.rs | 24 ++- crates/dynwinrt/src/delegate.rs | 98 ++++++++-- crates/dynwinrt/src/lib.rs | 3 +- tests/e2e/e2e_specs.json | 14 -- tests/e2e/e2e_specs.schema.json | 1 - tests/e2e/runners/py_runner.py | 98 ---------- tests/e2e/runners/ts_runner.ts | 92 ---------- 14 files changed, 505 insertions(+), 233 deletions(-) create mode 100644 bindings/js/__test__/struct-progress-child.mjs diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index e2db2a3c..20e3838f 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -10,6 +10,7 @@ import { fileURLToPath } from 'node:url' import { DynWinRtArray, + DynWinRtDelegate, DynWinRtMethodSig, DynWinRtStruct, DynWinRtType, @@ -701,6 +702,19 @@ test('build WinRT types', (t) => { t.truthy(DynWinRtType.iAsyncOperation(DynWinRtType.object())) }) +test('delegate creation failures are reported as JavaScript errors', (t) => { + const objectType = DynWinRtType.object() + t.throws( + () => + DynWinRtDelegate.create( + WinGuid.parse('699a62d5-a8a5-431c-9c00-a75c70b30524'), + [objectType, objectType, objectType], + () => {}, + ), + { message: /supports up to 2 parameters/ }, + ) +}) + test('invoke WinRT through dynamic metadata', (t) => { roInitialize(1) const factoryIid = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084') @@ -1162,3 +1176,43 @@ test('progress callbacks do not keep Node alive after completion', async (t) => t.is(code, 0, stderr) t.regex(stdout, /progress-exit-ok/) }) + +test('struct progress callbacks retain nested interface values', async (t) => { + const child = spawn(process.execPath, [fileURLToPath(new URL('./struct-progress-child.mjs', import.meta.url))], { + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + }) + + let stdout = '' + let stderr = '' + child.stdout.setEncoding('utf8') + child.stderr.setEncoding('utf8') + child.stdout.on('data', (chunk) => { + stdout += chunk + }) + child.stderr.on('data', (chunk) => { + stderr += chunk + }) + + let timedOut = false + const timeout = setTimeout(() => { + timedOut = true + child.kill() + }, 20_000) + t.teardown(() => { + clearTimeout(timeout) + if (child.exitCode === null && child.signalCode === null) { + child.kill() + } + }) + + const code = await new Promise((resolve, reject) => { + child.once('error', reject) + child.once('close', resolve) + }) + clearTimeout(timeout) + + t.false(timedOut, 'struct progress child timed out') + t.is(code, 0, stderr) + t.regex(stdout, /struct-progress-ok/) +}) diff --git a/bindings/js/__test__/struct-progress-child.mjs b/bindings/js/__test__/struct-progress-child.mjs new file mode 100644 index 00000000..a020c07b --- /dev/null +++ b/bindings/js/__test__/struct-progress-child.mjs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { createServer } from 'node:http' + +import { DynWinRtMethodSig, DynWinRtType, DynWinRtValue, WinGuid, roInitialize } from '../dist/winrt.js' + +roInitialize(1) + +const uriFactoryIid = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084') +const uriFactory = DynWinRtType.registerInterface('IUriRuntimeClassFactoryStructProgressTest', uriFactoryIid).addMethod( + 'CreateUri', + new DynWinRtMethodSig().addIn(DynWinRtType.hstring()).addOut(DynWinRtType.object()), +) + +const activationFactoryIid = WinGuid.parse('00000035-0000-0000-c000-000000000046') +const activationFactory = DynWinRtType.registerInterface( + 'IActivationFactoryStructProgressTest', + activationFactoryIid, +).addMethod('ActivateInstance', new DynWinRtMethodSig().addOut(DynWinRtType.object())) + +const progressStage = DynWinRtType.enumType('Windows.Web.Http.HttpProgressStage') +const referenceU64 = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [ + DynWinRtType.u64(), +]) +const httpProgress = DynWinRtType.structType('Windows.Web.Http.HttpProgress', [ + progressStage, + DynWinRtType.u64(), + referenceU64, + DynWinRtType.u64(), + referenceU64, + DynWinRtType.u32(), +]) +const reference = DynWinRtType.registerInterface('IReference_UInt64_StructProgressTest', referenceU64.iid()).addMethod( + 'get_Value', + new DynWinRtMethodSig().addOut(DynWinRtType.u64()), +) + +const clientIid = WinGuid.parse('7fda1151-3574-4880-a8ba-e6b1e0061f3d') +const clientType = DynWinRtType.registerInterface('IHttpClientStructProgressTest', clientIid) +for (const name of ['DeleteAsync', 'GetAsync', 'GetWithOptionAsync', 'GetBufferAsync', 'GetInputStreamAsync']) { + clientType.addMethod(name, new DynWinRtMethodSig()) +} +clientType.addMethod( + 'GetStringAsync', + new DynWinRtMethodSig() + .addIn(DynWinRtType.object()) + .addOut(DynWinRtType.iAsyncOperationWithProgress(DynWinRtType.hstring(), httpProgress)), +) + +const payload = 'dynwinrt-struct-progress-'.repeat(16_384) +const server = createServer((_request, response) => { + response.writeHead(200, { + 'Content-Length': Buffer.byteLength(payload), + 'Content-Type': 'text/plain; charset=utf-8', + Connection: 'close', + }) + let offset = 0 + const writeNext = () => { + if (offset >= payload.length) { + response.end() + return + } + const end = Math.min(offset + 8_192, payload.length) + response.write(payload.slice(offset, end)) + offset = end + setTimeout(writeNext, 5) + } + writeNext() +}) + +await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) +}) + +try { + const address = server.address() + assert.ok(address && typeof address !== 'string') + const uri = uriFactory + .method(6) + .invoke(DynWinRtValue.activationFactory('Windows.Foundation.Uri').cast(uriFactoryIid), [ + DynWinRtValue.hstring(`http://127.0.0.1:${address.port}/progress`), + ]) + const client = activationFactory + .method(6) + .invoke(DynWinRtValue.activationFactory('Windows.Web.Http.HttpClient').cast(activationFactoryIid), []) + const operation = clientType.method(11).invoke(client.cast(clientIid), [uri]) + const snapshots = [] + + operation.onProgress((value) => { + const progress = value.asStruct() + const totalValue = progress.getObject(4) + const totalBytesToReceive = totalValue.isNull() ? null : reference.method(6).invoke(totalValue, []).toU64Bigint() + snapshots.push({ + stage: progress.getI32(0), + bytesReceived: progress.getU64(3), + totalBytesToReceive, + retries: progress.getU32(5), + }) + }) + + const result = await operation.toPromise() + await new Promise((resolve) => setImmediate(resolve)) + + assert.equal(result.toString(), payload) + assert.ok( + snapshots.some( + (progress) => progress.bytesReceived > 0n && progress.totalBytesToReceive === BigInt(Buffer.byteLength(payload)), + ), + `expected retained receive totals, got ${JSON.stringify( + snapshots.map((progress) => ({ + ...progress, + bytesReceived: progress.bytesReceived.toString(), + totalBytesToReceive: progress.totalBytesToReceive?.toString() ?? null, + })), + )}`, + ) + assert.ok(snapshots.every((progress) => typeof progress.stage === 'number' && typeof progress.retries === 'number')) + console.log('struct-progress-ok') +} finally { + await new Promise((resolve) => server.close(resolve)) +} diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index be7980a4..8efd292a 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -1392,7 +1392,13 @@ impl DynWinRTValue { } }); let handler = - dynwinrt::create_progress_handler_with_result(handler_iid, progress_type, progress_cb); + dynwinrt::try_create_progress_handler_with_result(handler_iid, progress_type, progress_cb) + .map_err(|error| { + napi::Error::from_reason(format!( + "onProgress: failed to create progress handler: {}", + error.message() + )) + })?; async_info .set_progress_handler(&handler) @@ -2818,7 +2824,11 @@ impl DynWinRtDelegate { } }); - let value = dynwinrt::delegate::create_delegate_value(iid.0, type_handles, delegate_callback); + let value = + dynwinrt::delegate::try_create_delegate_value(iid.0, type_handles, delegate_callback) + .map_err(|error| { + napi::Error::from_reason(format!("DynWinRtDelegate.create: {}", error.message())) + })?; Ok(DynWinRtDelegate(value)) } diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index c31e866b..39106fb7 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -444,7 +444,13 @@ impl DynWinRTAsyncWithProgress { }); }); let handler = - dynwinrt::create_progress_handler(handler_iid, progress_type, progress_callback); + dynwinrt::try_create_progress_handler(handler_iid, progress_type, progress_callback) + .map_err(|error| { + map_dynwinrt_error_with_context( + error, + "failed to create WinRT progress handler", + ) + })?; finish_progress_registration(info.set_progress_handler(&handler), || { info.is_started().map_err(map_dynwinrt_error) }) diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index d79e5c24..a2029aba 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -1304,7 +1304,14 @@ impl DynWinRTValue { } }); }); - let handler = dynwinrt::create_progress_handler(handler_iid, progress_type, progress_cb); + let handler = + dynwinrt::try_create_progress_handler(handler_iid, progress_type, progress_cb) + .map_err(|error| { + map_dynwinrt_error_with_context( + error, + "on_progress: failed to create progress handler", + ) + })?; super::async_runtime::finish_progress_registration( async_info.set_progress_handler(&handler), @@ -2138,7 +2145,7 @@ fn create_python_delegate( iid: GUID, type_handles: Vec, callback: Py, -) -> dynwinrt::WinRTValue { +) -> PyResult { let delegate_callback: dynwinrt::delegate::DelegateCallback = Box::new(move |args: &[dynwinrt::WinRTValue]| { Python::attach(|py| { @@ -2165,7 +2172,8 @@ fn create_python_delegate( } }) }); - dynwinrt::delegate::create_delegate_value(iid, type_handles, delegate_callback) + dynwinrt::delegate::try_create_delegate_value(iid, type_handles, delegate_callback) + .map_err(|error| map_dynwinrt_error_with_context(error, "DynWinRtDelegate.create failed")) } #[pymethods] @@ -2183,7 +2191,7 @@ impl DynWinRtDelegate { ) -> PyResult { let type_handles: Vec = param_types.iter().map(|t| t.0.clone()).collect(); - let value = create_python_delegate(iid.0, type_handles, callback); + let value = create_python_delegate(iid.0, type_handles, callback)?; Ok(DynWinRtDelegate(value)) } @@ -2439,7 +2447,8 @@ mod tests { GUID::zeroed(), Vec::new(), locals.get_item("success").unwrap().unwrap().unbind(), - ); + ) + .unwrap(); let failure = create_python_delegate( GUID::zeroed(), Vec::new(), @@ -2449,12 +2458,14 @@ mod tests { .unwrap() .clone() .unbind(), - ); + ) + .unwrap(); let cross_thread_failure = create_python_delegate( GUID::zeroed(), Vec::new(), locals.get_item("failure").unwrap().unwrap().unbind(), - ); + ) + .unwrap(); let success_result = unsafe { invoke_delegate(&success) }; let failure_result = unsafe { invoke_delegate(&failure) }; diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index 26d5408f..e1b54f7f 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -10,6 +10,7 @@ WinGUID, DynWinRTArray, DynWinRTStruct, + DynWinRtDelegate, ro_initialize, ) @@ -19,6 +20,16 @@ def test_ro_initialize(): ro_initialize(1) +def test_delegate_creation_failures_are_python_exceptions(): + object_type = DynWinRTType.object() + with pytest.raises(OSError, match="supports up to 2 parameters"): + DynWinRtDelegate.create( + WinGUID.parse("699a62d5-a8a5-431c-9c00-a75c70b30524"), + [object_type, object_type, object_type], + lambda *_args: None, + ) + + def test_primitive_types(): """All primitive type factories should return DynWinRTType instances.""" assert DynWinRTType.i32_type() is not None diff --git a/bindings/py/tests/test_e2e_winrt.py b/bindings/py/tests/test_e2e_winrt.py index b1d17f75..e9dcfff5 100644 --- a/bindings/py/tests/test_e2e_winrt.py +++ b/bindings/py/tests/test_e2e_winrt.py @@ -13,6 +13,11 @@ Requires: Windows 10/11 with standard SDK (no extra installs needed). """ +import asyncio +import http.server +import threading +import time + from dynwinrt import ( DynWinRTType, DynWinRTMethodSig, @@ -22,6 +27,7 @@ WinGUID, ro_initialize, ) +from dynwinrt.dynwinrt import _DynWinRTAsyncWithProgress # Initialize WinRT once for the entire module ro_initialize(1) @@ -53,6 +59,34 @@ def _register(name, iid_str, methods): return itype, iid, handles +def _start_progress_server(): + payload = ("dynwinrt-struct-progress-" * 16_384).encode() + + class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self): + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Connection", "close") + self.end_headers() + for offset in range(0, len(payload), 8_192): + self.wfile.write(payload[offset : offset + 8_192]) + self.wfile.flush() + time.sleep(0.005) + self.close_connection = True + + def log_message(self, _format, *_args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + host, port = server.server_address + return server, thread, payload.decode(), f"http://{host}:{port}/progress" + + # ====================================================================== # 1. XmlDocument — void methods, object returns, string properties # ====================================================================== @@ -422,7 +456,143 @@ def test_buffer_multiple_sizes(self): # ====================================================================== -# 5. Uri (extended) — more thorough string/int/bool coverage +# 5. HttpClient — struct-valued async progress with nested IReference +# ====================================================================== + +class TestHttpProgress: + def test_struct_progress_survives_asyncio_dispatch(self): + u64 = DynWinRTType.u64_type() + progress_stage = DynWinRTType.enum_type("Windows.Web.Http.HttpProgressStage") + reference_u64 = DynWinRTType.parameterized( + WinGUID.parse("61c17706-2d65-11e0-9ae8-d48564015472"), + [u64], + ) + http_progress = DynWinRTType.struct_type( + "Windows.Web.Http.HttpProgress", + [ + progress_stage, + u64, + reference_u64, + u64, + reference_u64, + DynWinRTType.u32_type(), + ], + ) + reference = DynWinRTType.register_interface( + "IReference_UInt64_StructProgressTest", + reference_u64.iid(), + ).add_method("get_Value", DynWinRTMethodSig().add_out(u64)) + + activation_iid = WinGUID.parse("00000035-0000-0000-c000-000000000046") + activation = DynWinRTType.register_interface( + "IActivationFactoryStructProgressTest", + activation_iid, + ).add_method( + "ActivateInstance", + DynWinRTMethodSig().add_out(DynWinRTType.object()), + ) + client = activation.method(6).invoke( + DynWinRTValue.activation_factory("Windows.Web.Http.HttpClient").cast( + activation_iid + ), + [], + ) + + client_iid = WinGUID.parse("7fda1151-3574-4880-a8ba-e6b1e0061f3d") + client_type = DynWinRTType.register_interface( + "IHttpClientStructProgressTest", + client_iid, + ) + for name in ( + "DeleteAsync", + "GetAsync", + "GetWithOptionAsync", + "GetBufferAsync", + "GetInputStreamAsync", + ): + client_type = client_type.add_method(name, DynWinRTMethodSig()) + client_type = client_type.add_method( + "GetStringAsync", + DynWinRTMethodSig() + .add_in(DynWinRTType.object()) + .add_out( + DynWinRTType.i_async_operation_with_progress( + DynWinRTType.hstring(), + http_progress, + ) + ), + ) + + uri_factory_iid = WinGUID.parse("44a9796f-723e-4fdf-a218-033e75b0c084") + uri_factory = DynWinRTType.register_interface( + "IUriRuntimeClassFactoryStructProgressTest", + uri_factory_iid, + ).add_method( + "CreateUri", + DynWinRTMethodSig() + .add_in(DynWinRTType.hstring()) + .add_out(DynWinRTType.object()), + ) + + server, thread, payload, url = _start_progress_server() + try: + uri = uri_factory.method(6).invoke( + DynWinRTValue.activation_factory("Windows.Foundation.Uri").cast( + uri_factory_iid + ), + [DynWinRTValue.from_hstring(url)], + ) + operation = client_type.method(11).invoke(client.cast(client_iid), [uri]) + + async def run_operation(): + snapshots = [] + + def convert_progress(value): + progress = value.as_struct() + total_value = progress.get_object(4) + total = ( + None + if total_value.is_null() + else reference.method(6).invoke(total_value, []).to_u64() + ) + return { + "stage": progress.get_i32(0), + "bytes_received": progress.get_u64(3), + "total_bytes_to_receive": total, + "retries": progress.get_u32(5), + } + + projected = _DynWinRTAsyncWithProgress( + operation, + lambda value: value.to_string(), + convert_progress, + ) + projected.progress(snapshots.append) + body = await projected + await asyncio.sleep(0.05) + return body, snapshots + + body, snapshots = asyncio.run(run_operation()) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + assert body == payload + assert any( + progress["bytes_received"] > 0 + and progress["total_bytes_to_receive"] == len(payload) + for progress in snapshots + ) + assert all( + isinstance(progress["stage"], int) + and isinstance(progress["retries"], int) + for progress in snapshots + ) + + +# ====================================================================== +# 6. Uri (extended) — more thorough string/int/bool coverage # ====================================================================== class TestUriExtended: diff --git a/crates/dynwinrt/src/dasync.rs b/crates/dynwinrt/src/dasync.rs index 75f64bfd..80d9bc05 100644 --- a/crates/dynwinrt/src/dasync.rs +++ b/crates/dynwinrt/src/dasync.rs @@ -398,7 +398,17 @@ pub fn create_progress_handler( progress_type: TypeHandle, callback: ProgressCallback, ) -> IUnknown { - create_progress_handler_with_result( + try_create_progress_handler(handler_iid, progress_type, callback) + .expect("failed to create WinRT progress handler") +} + +/// Fallible progress-handler creation for language bindings. +pub fn try_create_progress_handler( + handler_iid: GUID, + progress_type: TypeHandle, + callback: ProgressCallback, +) -> Result { + try_create_progress_handler_with_result( handler_iid, progress_type, Box::new(move |value| { @@ -414,6 +424,16 @@ pub fn create_progress_handler_with_result( progress_type: TypeHandle, callback: ProgressResultCallback, ) -> IUnknown { + try_create_progress_handler_with_result(handler_iid, progress_type, callback) + .expect("failed to create WinRT progress handler") +} + +/// Fallible progress-handler creation for callbacks that return an HRESULT. +pub fn try_create_progress_handler_with_result( + handler_iid: GUID, + progress_type: TypeHandle, + callback: ProgressResultCallback, +) -> Result { // Progress handler Invoke signature: (sender: Object, progress: TProgress) let sender_type = progress_type .table() @@ -430,7 +450,7 @@ pub fn create_progress_handler_with_result( } }); - crate::delegate::create_delegate(handler_iid, param_types, delegate_callback) + crate::delegate::try_create_delegate(handler_iid, param_types, delegate_callback) } // --------------------------------------------------------------------------- diff --git a/crates/dynwinrt/src/delegate.rs b/crates/dynwinrt/src/delegate.rs index 12f362e4..39a998a0 100644 --- a/crates/dynwinrt/src/delegate.rs +++ b/crates/dynwinrt/src/delegate.rs @@ -16,9 +16,14 @@ use crate::native_callback::{CallbackAbiType, CallbackSignature}; use crate::value::{AsyncInfo, WinRTValue}; const E_FAIL: HRESULT = HRESULT(0x80004005u32 as i32); +const E_INVALIDARG: HRESULT = HRESULT(0x80070057u32 as i32); const E_NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); +fn delegate_creation_error(code: HRESULT, message: impl AsRef) -> crate::result::Error { + crate::result::Error::WindowsError(windows_core::Error::new(code, message.as_ref())) +} + // ====================================================================== // DynamicDelegate — general-purpose WinRT delegate COM object // ====================================================================== @@ -141,16 +146,20 @@ impl DynamicDelegate { /// - `delegate_iid`: the IID of the delegate interface (for QueryInterface) /// - `param_types`: types of the Invoke method's parameters (excluding `this`) /// - `callback`: function called when WinRT invokes the delegate - pub fn create( + fn try_create( delegate_iid: GUID, param_types: Vec, callback: DelegateCallback, - ) -> IUnknown { - assert!( - param_types.len() <= 2, - "DynamicDelegate currently supports up to 2 parameters, got {}", - param_types.len() - ); + ) -> crate::result::Result { + if param_types.len() > 2 { + return Err(delegate_creation_error( + E_INVALIDARG, + format!( + "DynamicDelegate supports up to 2 parameters, got {}", + param_types.len() + ), + )); + } use crate::metadata_table::TypeKind; @@ -158,10 +167,19 @@ impl DynamicDelegate { .iter() .any(|typ| matches!(typ.kind(), TypeKind::Struct(_))) { - let signature = Self::libffi_signature(¶m_types) - .expect("unsupported WinRT delegate parameter type used with a struct"); + let signature = Self::libffi_signature(¶m_types).ok_or_else(|| { + delegate_creation_error( + E_NOTIMPL, + "WinRT delegate struct callbacks do not support one or more parameter types", + ) + })?; let invoke = crate::native_callback::callback_code(3, signature, Self::invoke_libffi) - .expect("failed to create the WinRT delegate callback closure"); + .map_err(|error| { + delegate_creation_error( + E_FAIL, + format!("failed to create the WinRT delegate callback closure: {error}"), + ) + })?; Some(Box::new(DynamicDelegateVtbl { base: windows_core::IUnknown_Vtbl { QueryInterface: Self::qi, @@ -203,7 +221,7 @@ impl DynamicDelegate { callback, _owned_vtable: owned_vtable, }); - unsafe { IUnknown::from_raw(Box::into_raw(delegate) as *mut c_void) } + Ok(unsafe { IUnknown::from_raw(Box::into_raw(delegate) as *mut c_void) }) } fn libffi_signature(param_types: &[TypeHandle]) -> Option { @@ -243,7 +261,9 @@ impl DynamicDelegate { // the process-wide closure cache. Dispatch still recovers the // table-qualified TypeHandle from the delegate instance. TypeKind::Struct(_) => Some(CallbackAbiType::NativeStruct( - typ.signature_string(), + typ.table() + .try_closed_signature_string_kind(typ.kind()) + .ok()?, typ.size_of(), )), TypeKind::ArrayOfIUnknown @@ -561,12 +581,34 @@ unsafe fn marshal_libffi_arg( /// # Returns /// An `IUnknown` smart pointer to the delegate COM object. /// Pass this to WinRT methods that accept the delegate (e.g. event subscriptions). +pub fn try_create_delegate( + delegate_iid: GUID, + param_types: Vec, + callback: DelegateCallback, +) -> crate::result::Result { + DynamicDelegate::try_create(delegate_iid, param_types, callback) +} + +/// Create a dynamic WinRT delegate, panicking if its callback backend cannot be created. +/// +/// Language bindings should use [`try_create_delegate`] so closure allocation +/// failures become language exceptions. pub fn create_delegate( delegate_iid: GUID, param_types: Vec, callback: DelegateCallback, ) -> IUnknown { - DynamicDelegate::create(delegate_iid, param_types, callback) + try_create_delegate(delegate_iid, param_types, callback) + .expect("failed to create dynamic WinRT delegate") +} + +/// Fallible convenience wrapper around [`try_create_delegate`]. +pub fn try_create_delegate_value( + delegate_iid: GUID, + param_types: Vec, + callback: DelegateCallback, +) -> crate::result::Result { + try_create_delegate(delegate_iid, param_types, callback).map(WinRTValue::Object) } /// Convenience: create a delegate and wrap as WinRTValue::Object. @@ -575,7 +617,8 @@ pub fn create_delegate_value( param_types: Vec, callback: DelegateCallback, ) -> WinRTValue { - WinRTValue::Object(create_delegate(delegate_iid, param_types, callback)) + try_create_delegate_value(delegate_iid, param_types, callback) + .expect("failed to create dynamic WinRT delegate value") } // ====================================================================== @@ -693,6 +736,33 @@ mod tests { assert!(called.load(Ordering::SeqCst)); } + #[test] + fn try_create_delegate_reports_unsupported_struct_callback_signature() { + let table = MetadataTable::new(); + let element_type = table.u32_type(); + let unsupported_field = table.out_value(&element_type); + let progress_type = table.struct_type( + "Test.FallibleProgress", + std::slice::from_ref(&unsupported_field), + ); + + let result = try_create_delegate( + GUID::from_u128(0x66666666_6666_6666_6666_666666666666), + vec![table.object(), progress_type], + Box::new(|_| HRESULT(0)), + ); + + let error = match result { + Ok(_) => panic!("unsupported struct callback signature unexpectedly succeeded"), + Err(error) => error, + }; + assert!( + error + .message() + .contains("do not support one or more parameter types") + ); + } + #[test] fn test_delegate_struct_trampoline_marshals_wide_value() { #[repr(C)] diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 29f120bb..c72cca64 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -38,7 +38,8 @@ pub use crate::composition::{ pub use crate::dasync::{ AsyncCompletedCallback, ProgressCallback, ProgressResultCallback, WinRTAsyncFuture, create_progress_handler, create_progress_handler_with_result, get_async_results, - set_async_completed_handler, + set_async_completed_handler, try_create_progress_handler, + try_create_progress_handler_with_result, }; pub use crate::dispatcher_queue::{SystemDispatcherQueue, SystemDispatcherQueueHandle}; pub use crate::element_factory::{ diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index a24ad07f..c2963bf3 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -612,20 +612,6 @@ { "kind": "vector_index_of", "member": "languages", "search_value": "xx-NONEXISTENT", "expected_index": -1 } ] }, - { - "id": "http_client_struct_progress", - "namespace": "Windows.Web.Http", - "class": "HttpClient", - "langs": ["py", "ts"], - "instantiate": { "kind": "static_factory", "method": "create_default" }, - "checks": [ - { - "kind": "async_struct_progress", - "member": "get_string_async", - "expected_type": "HttpProgress" - } - ] - }, { "id": "python_generated_helper_matrix", "namespace": "Windows.Foundation", diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index fea7d15d..94494f3a 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -75,7 +75,6 @@ "cross_class_chain", "async_memory_roundtrip", "async_cancellation", - "async_struct_progress", "property_set_equals", "vector_view_access", "vector_index_of", diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index 0806b84f..ac5aad69 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -16,12 +16,10 @@ import importlib import inspect import json -import http.server import re import sys import os import threading -import time _WINRT_UINT_SUFFIXES = {'int8', 'int16', 'int32', 'int64'} @@ -115,34 +113,6 @@ def wrap_arg(val): return val -def start_progress_server(): - payload = ('dynwinrt-struct-progress-' * 16_384).encode('utf-8') - - class Handler(http.server.BaseHTTPRequestHandler): - protocol_version = 'HTTP/1.1' - - def do_GET(self): - self.send_response(200) - self.send_header('Content-Length', str(len(payload))) - self.send_header('Content-Type', 'text/plain; charset=utf-8') - self.send_header('Connection', 'close') - self.end_headers() - for offset in range(0, len(payload), 8_192): - self.wfile.write(payload[offset:offset + 8_192]) - self.wfile.flush() - time.sleep(0.005) - self.close_connection = True - - def log_message(self, _format, *_args): - pass - - server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - host, port = server.server_address - return server, thread, payload.decode('utf-8'), f'http://{host}:{port}/progress' - - async def run_spec(spec: dict, generated_dir: str, pkg_name: str) -> dict: """Run a single test spec. Returns a result dict.""" ns = spec['namespace'] @@ -2006,74 +1976,6 @@ def block_on_sta(): print(f' generated helper matrix: {counters}') cr['pass'] = True - elif kind == 'async_struct_progress': - server, thread, payload, url = start_progress_server() - try: - uri_type = generated_type(pkg_name, 'Uri') - uri = uri_type(url) - progress_values = [] - operation = getattr(obj, member)(uri) - operation.progress(progress_values.append) - body = await operation - await asyncio.sleep(0.05) - - if body != payload: - cr['error'] = ( - f'loopback response mismatch: expected {len(payload)} ' - f'characters, got {len(str(body))}' - ) - return cr - expected_type = check.get('expected_type') - if ( - not progress_values - or any( - value is None - or ( - expected_type - and type(value).__name__ != expected_type - ) - for value in progress_values - ) - ): - actual_types = ', '.join( - type(value).__name__ for value in progress_values - ) or 'none' - cr['error'] = ( - f'expected projected {expected_type} progress values, ' - f'got {actual_types}' - ) - return cr - received = next( - ( - value - for value in progress_values - if value.bytes_received > 0 - and value.total_bytes_to_receive == len(payload) - ), - None, - ) - if received is None: - totals = ', '.join( - f'{value.bytes_received}/{value.total_bytes_to_receive}' - for value in progress_values - ) - cr['error'] = ( - 'progress did not retain expected receive totals: ' - f'{totals}' - ) - return cr - if ( - not isinstance(received.retries, int) - or not hasattr(received.stage, 'value') - ): - cr['error'] = 'projected progress scalar fields were invalid' - return cr - cr['pass'] = True - finally: - server.shutdown() - server.server_close() - thread.join(timeout=5) - else: cr['error'] = f'unknown check kind: {kind}' diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index 0b522220..2bdaa0c8 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -14,7 +14,6 @@ import { strict as assert } from "node:assert"; import { spawn } from "node:child_process"; import * as fs from "node:fs"; -import { createServer } from "node:http"; import * as os from "node:os"; import * as path from "node:path"; import { fileURLToPath } from "node:url"; @@ -88,50 +87,6 @@ function toPascalCase(name: string): string { return camel.charAt(0).toUpperCase() + camel.slice(1); } -async function startProgressServer(): Promise<{ - payload: string; - url: string; - close: () => Promise; -}> { - const payload = "dynwinrt-struct-progress-".repeat(16_384); - const server = createServer((_request, response) => { - response.writeHead(200, { - "Content-Length": Buffer.byteLength(payload), - "Content-Type": "text/plain; charset=utf-8", - Connection: "close", - }); - let offset = 0; - const writeNext = () => { - if (offset >= payload.length) { - response.end(); - return; - } - const end = Math.min(offset + 8_192, payload.length); - response.write(payload.slice(offset, end)); - offset = end; - setTimeout(writeNext, 5); - }; - writeNext(); - }); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - const address = server.address(); - if (!address || typeof address === "string") { - server.close(); - throw new Error("loopback HTTP server did not publish a TCP port"); - } - return { - payload, - url: `http://127.0.0.1:${address.port}/progress`, - close: () => - new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }), - }; -} - async function runSpec( spec: Spec, generatedDir: string, @@ -983,53 +938,6 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === "async_struct_progress") { - const server = await startProgressServer(); - try { - const uriClass = await importClass(generatedDir, "Uri"); - const uri = uriClass.createUri(server.url); - const progressValues: any[] = []; - const operation = obj[member](uri); - operation.progress((value: any) => progressValues.push(value)); - const body = await operation; - await new Promise((resolve) => setImmediate(resolve)); - - if (body !== server.payload) { - cr.error = `loopback response mismatch: expected ${server.payload.length} characters, got ${String(body).length}`; - return cr; - } - if ( - progressValues.length === 0 || - progressValues.some( - (value) => - value == null || - typeof value !== "object" || - !("stage" in value) || - !("bytesReceived" in value) || - !("totalBytesToReceive" in value) || - !("retries" in value), - ) - ) { - cr.error = `expected projected HttpProgress objects, got ${progressValues.map((value) => typeof value).join(", ") || "none"}`; - return cr; - } - const received = progressValues.find( - (value) => - value.bytesReceived > 0n && - value.totalBytesToReceive === BigInt(server.payload.length), - ); - if (!received) { - cr.error = `progress did not retain expected receive totals: ${progressValues - .map((value) => `${value.bytesReceived}/${value.totalBytesToReceive}`) - .join(", ")}`; - return cr; - } - assert.equal(typeof received.stage, "number"); - assert.equal(typeof received.retries, "number"); - cr.pass = true; - } finally { - await server.close(); - } } else { cr.error = `unknown check kind: ${kind}`; } From 80515593805774f30581a6d639dc8af6d18f1b73 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Tue, 1 Sep 2026 09:53:02 +0800 Subject: [PATCH 3/4] Harden callback closure creation and x86 alignment Prepare callback CIFs through fallible libffi APIs, make executable closure allocation null-safe, reject zero-sized callback structs, and use unaligned-safe 64-bit callback storage across WinRT and Classic COM. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/__test__/index.spec.ts | 11 ++ bindings/py/tests/test_basic.py | 11 ++ crates/dynwinrt/src/com.rs | 73 +++++++++++-- crates/dynwinrt/src/delegate.rs | 85 +++++++++++++-- crates/dynwinrt/src/native_callback.rs | 139 +++++++++++++++++++++++-- 5 files changed, 293 insertions(+), 26 deletions(-) diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 20e3838f..24bc4a74 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -713,6 +713,17 @@ test('delegate creation failures are reported as JavaScript errors', (t) => { ), { message: /supports up to 2 parameters/ }, ) + + const emptyStruct = DynWinRtType.structType('DynWinRT.Tests.EmptyDelegateArgument', []) + t.throws( + () => + DynWinRtDelegate.create( + WinGuid.parse('f1662550-78fd-4bf1-9022-0a2c85168380'), + [objectType, emptyStruct], + () => {}, + ), + { message: /struct callbacks do not support/ }, + ) }) test('invoke WinRT through dynamic metadata', (t) => { diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index e1b54f7f..cea9aee7 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -29,6 +29,17 @@ def test_delegate_creation_failures_are_python_exceptions(): lambda *_args: None, ) + empty_struct = DynWinRTType.struct_type( + "DynWinRT.Tests.EmptyDelegateArgument", + [], + ) + with pytest.raises(OSError, match="struct callbacks do not support"): + DynWinRtDelegate.create( + WinGUID.parse("f1662550-78fd-4bf1-9022-0a2c85168380"), + [object_type, empty_struct], + lambda *_args: None, + ) + def test_primitive_types(): """All primitive type factories should return DynWinRTType instances.""" diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index d52d9875..fa2b933b 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -2053,10 +2053,10 @@ impl PreparedNativeCallbackOutput { Self::U16(value) => unsafe { target.cast::().write(value) }, Self::I32(value) => unsafe { target.cast::().write(value) }, Self::U32(value) => unsafe { target.cast::().write(value) }, - Self::I64(value) => unsafe { target.cast::().write(value) }, - Self::U64(value) => unsafe { target.cast::().write(value) }, + Self::I64(value) => unsafe { target.cast::().write_unaligned(value) }, + Self::U64(value) => unsafe { target.cast::().write_unaligned(value) }, Self::F32(value) => unsafe { target.cast::().write(value) }, - Self::F64(value) => unsafe { target.cast::().write(value) }, + Self::F64(value) => unsafe { target.cast::().write_unaligned(value) }, Self::Guid(value) => unsafe { target.cast::().write(value) }, Self::Pointer(value) => unsafe { target.cast::<*mut c_void>().write(value) }, Self::Bstr(value) => unsafe { @@ -2675,10 +2675,16 @@ impl CallbackMethodPlan { } TypeKind::I32 => winrt(WinRTValue::I32(unsafe { *value.cast::() })), TypeKind::U32 => winrt(WinRTValue::U32(unsafe { *value.cast::() })), - TypeKind::I64 => winrt(WinRTValue::I64(unsafe { *value.cast::() })), - TypeKind::U64 => winrt(WinRTValue::U64(unsafe { *value.cast::() })), + TypeKind::I64 => winrt(WinRTValue::I64(unsafe { + std::ptr::read_unaligned(value.cast::()) + })), + TypeKind::U64 => winrt(WinRTValue::U64(unsafe { + std::ptr::read_unaligned(value.cast::()) + })), TypeKind::F32 => winrt(WinRTValue::F32(unsafe { *value.cast::() })), - TypeKind::F64 => winrt(WinRTValue::F64(unsafe { *value.cast::() })), + TypeKind::F64 => winrt(WinRTValue::F64(unsafe { + std::ptr::read_unaligned(value.cast::()) + })), TypeKind::Guid => winrt(WinRTValue::Guid(unsafe { *value.cast::() })), TypeKind::HString => { let raw = unsafe { *value.cast::<*mut c_void>() }; @@ -7217,6 +7223,61 @@ mod tests { assert_eq!(invoke!(12, f64), -2.25); } + #[test] + fn callback_eight_byte_scalars_support_four_byte_aligned_storage() { + #[repr(align(8))] + struct AlignedStorage([u8; 16]); + + let table = MetadataTable::new(); + let mut storage = AlignedStorage([0; 16]); + let pointer = unsafe { storage.0.as_mut_ptr().add(4).cast::() }; + assert_eq!(pointer as usize % 4, 0); + assert_ne!(pointer as usize % 8, 0); + + let expected_i64 = -0x1020_3040_5060_708i64; + storage.0[4..12].copy_from_slice(&expected_i64.to_ne_bytes()); + assert!(matches!( + unsafe { + CallbackMethodPlan::read_callback_input( + &ParameterType::WinRT(table.i64_type()), + pointer, + ) + }, + Ok(Value::WinRt(WinRTValue::I64(value))) if value == expected_i64 + )); + unsafe { PreparedNativeCallbackOutput::I64(expected_i64).commit(pointer) }; + assert_eq!(&storage.0[4..12], &expected_i64.to_ne_bytes()); + + let expected_u64 = 0xfedc_ba98_7654_3210u64; + storage.0[4..12].copy_from_slice(&expected_u64.to_ne_bytes()); + assert!(matches!( + unsafe { + CallbackMethodPlan::read_callback_input( + &ParameterType::WinRT(table.u64_type()), + pointer, + ) + }, + Ok(Value::WinRt(WinRTValue::U64(value))) if value == expected_u64 + )); + unsafe { PreparedNativeCallbackOutput::U64(expected_u64).commit(pointer) }; + assert_eq!(&storage.0[4..12], &expected_u64.to_ne_bytes()); + + let expected_f64 = -12345.625f64; + storage.0[4..12].copy_from_slice(&expected_f64.to_ne_bytes()); + assert!(matches!( + unsafe { + CallbackMethodPlan::read_callback_input( + &ParameterType::WinRT(table.f64_type()), + pointer, + ) + }, + Ok(Value::WinRt(WinRTValue::F64(value))) + if value.to_bits() == expected_f64.to_bits() + )); + unsafe { PreparedNativeCallbackOutput::F64(expected_f64).commit(pointer) }; + assert_eq!(&storage.0[4..12], &expected_f64.to_ne_bytes()); + } + #[test] fn dynamic_com_sink_libffi_round_trips_scalars_guid_and_multiple_outputs() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/delegate.rs b/crates/dynwinrt/src/delegate.rs index 39a998a0..93041221 100644 --- a/crates/dynwinrt/src/delegate.rs +++ b/crates/dynwinrt/src/delegate.rs @@ -260,12 +260,18 @@ impl DynamicDelegate { // The full recursive WinRT signature identifies the ABI layout in // the process-wide closure cache. Dispatch still recovers the // table-qualified TypeHandle from the delegate instance. - TypeKind::Struct(_) => Some(CallbackAbiType::NativeStruct( - typ.table() - .try_closed_signature_string_kind(typ.kind()) - .ok()?, - typ.size_of(), - )), + TypeKind::Struct(_) => { + let size = typ.size_of(); + if size == 0 { + return None; + } + Some(CallbackAbiType::NativeStruct( + typ.table() + .try_closed_signature_string_kind(typ.kind()) + .ok()?, + size, + )) + } TypeKind::ArrayOfIUnknown | TypeKind::Generic { .. } | TypeKind::OutValue(_) @@ -539,10 +545,16 @@ unsafe fn marshal_libffi_arg( TypeKind::HResult => Ok(WinRTValue::HResult(HRESULT(unsafe { *storage.cast::() }))), - TypeKind::I64 => Ok(WinRTValue::I64(unsafe { *storage.cast::() })), - TypeKind::U64 => Ok(WinRTValue::U64(unsafe { *storage.cast::() })), + TypeKind::I64 => Ok(WinRTValue::I64(unsafe { + std::ptr::read_unaligned(storage.cast::()) + })), + TypeKind::U64 => Ok(WinRTValue::U64(unsafe { + std::ptr::read_unaligned(storage.cast::()) + })), TypeKind::F32 => Ok(WinRTValue::F32(unsafe { *storage.cast::() })), - TypeKind::F64 => Ok(WinRTValue::F64(unsafe { *storage.cast::() })), + TypeKind::F64 => Ok(WinRTValue::F64(unsafe { + std::ptr::read_unaligned(storage.cast::()) + })), TypeKind::Guid => Ok(WinRTValue::Guid(unsafe { *storage.cast::() })), TypeKind::Struct(_) => Ok(WinRTValue::Struct(unsafe { ValueTypeData::from_borrowed_abi(typ, storage) @@ -763,6 +775,61 @@ mod tests { ); } + #[test] + fn try_create_delegate_rejects_zero_sized_struct_without_panicking() { + let table = MetadataTable::new(); + let progress_type = table.struct_type("Test.EmptyProgress", &[]); + + let result = try_create_delegate( + GUID::from_u128(0x77777777_7777_7777_7777_777777777777), + vec![table.object(), progress_type], + Box::new(|_| HRESULT(0)), + ); + + let error = match result { + Ok(_) => panic!("zero-sized struct callback unexpectedly succeeded"), + Err(error) => error, + }; + assert!( + error + .message() + .contains("do not support one or more parameter types") + ); + } + + #[test] + fn marshal_libffi_arg_reads_eight_byte_scalars_from_four_byte_alignment() { + #[repr(align(8))] + struct AlignedStorage([u8; 16]); + + let table = MetadataTable::new(); + let mut storage = AlignedStorage([0; 16]); + let pointer = unsafe { storage.0.as_mut_ptr().add(4).cast::() }; + assert_eq!(pointer as usize % 4, 0); + assert_ne!(pointer as usize % 8, 0); + + let expected_i64 = -0x1020_3040_5060_708i64; + storage.0[4..12].copy_from_slice(&expected_i64.to_ne_bytes()); + assert!(matches!( + unsafe { marshal_libffi_arg(pointer, &table.i64_type()) }, + Ok(WinRTValue::I64(value)) if value == expected_i64 + )); + + let expected_u64 = 0xfedc_ba98_7654_3210u64; + storage.0[4..12].copy_from_slice(&expected_u64.to_ne_bytes()); + assert!(matches!( + unsafe { marshal_libffi_arg(pointer, &table.u64_type()) }, + Ok(WinRTValue::U64(value)) if value == expected_u64 + )); + + let expected_f64 = -12345.625f64; + storage.0[4..12].copy_from_slice(&expected_f64.to_ne_bytes()); + assert!(matches!( + unsafe { marshal_libffi_arg(pointer, &table.f64_type()) }, + Ok(WinRTValue::F64(value)) if value.to_bits() == expected_f64.to_bits() + )); + } + #[test] fn test_delegate_struct_trampoline_marshals_wide_value() { #[repr(C)] diff --git a/crates/dynwinrt/src/native_callback.rs b/crates/dynwinrt/src/native_callback.rs index 199d12bb..815fb26a 100644 --- a/crates/dynwinrt/src/native_callback.rs +++ b/crates/dynwinrt/src/native_callback.rs @@ -12,8 +12,6 @@ use std::{ use libffi::{low, middle::Type}; use windows_core::HRESULT; -use crate::native_call::system_cif; - const E_FAIL: HRESULT = HRESULT(0x80004005u32 as i32); #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -125,6 +123,21 @@ impl CallbackSignature { &self.return_abi } + fn validate(&self) -> Result<(), String> { + let zero_sized_parameter = self + .parameters + .iter() + .any(|parameter| matches!(parameter, CallbackAbiType::NativeStruct(_, 0))); + let zero_sized_result = matches!( + &self.return_abi, + CallbackReturnAbi::Value(CallbackAbiType::NativeStruct(_, 0)) + ); + if zero_sized_parameter || zero_sized_result { + return Err("libffi callbacks do not support zero-sized native structs".into()); + } + Ok(()) + } + pub(crate) unsafe fn initialize_failure_result(&self, result: *mut c_void, error: HRESULT) { if result.is_null() { return; @@ -172,8 +185,58 @@ struct CallbackContext { dispatch: CallbackDispatch, } +struct PreparedCallbackCif { + cif: Box, + _argument_types: Vec, + _argument_type_ptrs: Vec<*mut low::ffi_type>, + _result_type: Type, +} + +impl PreparedCallbackCif { + fn new(argument_types: Vec, result_type: Type) -> Result { + #[cfg(all(windows, target_arch = "x86"))] + let abi = libffi_sys::ffi_abi_FFI_STDCALL; + #[cfg(not(all(windows, target_arch = "x86")))] + let abi = libffi_sys::ffi_abi_FFI_DEFAULT_ABI; + + Self::new_with_abi(argument_types, result_type, abi) + } + + fn new_with_abi( + argument_types: Vec, + result_type: Type, + abi: libffi_sys::ffi_abi, + ) -> Result { + let mut argument_type_ptrs = argument_types + .iter() + .map(Type::as_raw_ptr) + .collect::>(); + let mut cif = Box::new(low::ffi_cif::default()); + unsafe { + low::prep_cif( + cif.as_mut(), + abi, + argument_type_ptrs.len(), + result_type.as_raw_ptr(), + argument_type_ptrs.as_mut_ptr(), + ) + } + .map_err(|error| format!("libffi could not prepare callback CIF: {error:?}"))?; + Ok(Self { + cif, + _argument_types: argument_types, + _argument_type_ptrs: argument_type_ptrs, + _result_type: result_type, + }) + } + + fn as_raw_ptr(&self) -> *mut low::ffi_cif { + self.cif.as_ref() as *const low::ffi_cif as *mut low::ffi_cif + } +} + struct OwnedCallbackClosure { - _cif: Box, + _cif: PreparedCallbackCif, closure: *mut low::ffi_closure, code: *const c_void, _context: Box, @@ -190,17 +253,26 @@ impl OwnedCallbackClosure { signature: CallbackSignature, dispatch: CallbackDispatch, ) -> Result { - let cif = Box::new(system_cif( - signature.argument_types(), - signature.result_type(), - )); + Self::new_with_allocator(slot, signature, dispatch, |code| unsafe { + libffi_sys::ffi_closure_alloc(size_of::(), code).cast() + }) + } + + fn new_with_allocator( + slot: usize, + signature: CallbackSignature, + dispatch: CallbackDispatch, + allocate: impl FnOnce(*mut *mut c_void) -> *mut low::ffi_closure, + ) -> Result { + let cif = PreparedCallbackCif::new(signature.argument_types(), signature.result_type())?; let context = Box::new(CallbackContext { slot, signature, dispatch, }); - let (closure, code) = low::closure_alloc(); - if closure.is_null() || code.as_ptr().is_null() { + let mut code = std::ptr::null_mut(); + let closure = allocate(&mut code); + if closure.is_null() || code.is_null() { if !closure.is_null() { unsafe { low::closure_free(closure) }; } @@ -212,7 +284,7 @@ impl OwnedCallbackClosure { cif.as_raw_ptr(), Some(invoke_callback), context.as_ref() as *const CallbackContext as *mut c_void, - code.as_mut_ptr(), + code, ) }; if status != libffi_sys::ffi_status_FFI_OK { @@ -224,7 +296,7 @@ impl OwnedCallbackClosure { Ok(Self { _cif: cif, closure, - code: code.as_ptr(), + code, _context: context, }) } @@ -267,6 +339,7 @@ pub(crate) fn callback_code( signature: CallbackSignature, dispatch: CallbackDispatch, ) -> Result<*const c_void, String> { + signature.validate()?; let key = ClosureKey { slot, signature: signature.clone(), @@ -310,4 +383,48 @@ mod tests { unsafe { std::mem::transmute(first) }; assert_eq!(unsafe { callback(std::ptr::null_mut(), 27) }, HRESULT(27)); } + + #[test] + fn callback_cif_preparation_failure_is_returned() { + let result = PreparedCallbackCif::new_with_abi( + vec![Type::pointer()], + Type::i32(), + u32::MAX as libffi_sys::ffi_abi, + ); + let error = match result { + Ok(_) => panic!("invalid callback ABI unexpectedly prepared a CIF"), + Err(error) => error, + }; + assert!(error.contains("could not prepare callback CIF")); + } + + #[test] + fn zero_sized_callback_struct_is_rejected_before_cif_preparation() { + let signature = CallbackSignature { + parameters: vec![CallbackAbiType::NativeStruct("Test.Empty".into(), 0)], + libffi_parameters: vec![Type::void()], + return_abi: CallbackReturnAbi::HResult, + libffi_return: Type::i32(), + }; + let result = callback_code(3, signature, test_dispatch); + let error = match result { + Ok(_) => panic!("zero-sized callback struct unexpectedly created a closure"), + Err(error) => error, + }; + assert!(error.contains("zero-sized native structs")); + } + + #[test] + fn callback_closure_allocation_failure_is_returned() { + let signature = CallbackSignature::hresult(vec![(CallbackAbiType::I32, Type::i32())]); + let result = + OwnedCallbackClosure::new_with_allocator(3, signature, test_dispatch, |_code| { + std::ptr::null_mut() + }); + let error = match result { + Ok(_) => panic!("failed callback allocation unexpectedly succeeded"), + Err(error) => error, + }; + assert!(error.contains("could not allocate executable callback memory")); + } } From f4532f805119bf804a687dca3240bbe1cf1d2cf4 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Tue, 1 Sep 2026 10:01:20 +0800 Subject: [PATCH 4/4] Reject nested empty callback structs Validate struct callback graphs recursively before libffi preparation and add compile-time Send/Sync coverage for cached callback storage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- crates/dynwinrt/src/delegate.rs | 52 ++++++++++++++++---------- crates/dynwinrt/src/native_callback.rs | 8 ++++ 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/crates/dynwinrt/src/delegate.rs b/crates/dynwinrt/src/delegate.rs index 93041221..e67e2d36 100644 --- a/crates/dynwinrt/src/delegate.rs +++ b/crates/dynwinrt/src/delegate.rs @@ -261,15 +261,14 @@ impl DynamicDelegate { // the process-wide closure cache. Dispatch still recovers the // table-qualified TypeHandle from the delegate instance. TypeKind::Struct(_) => { - let size = typ.size_of(); - if size == 0 { + if !Self::supports_callback_struct(typ) { return None; } Some(CallbackAbiType::NativeStruct( typ.table() .try_closed_signature_string_kind(typ.kind()) .ok()?, - size, + typ.size_of(), )) } TypeKind::ArrayOfIUnknown @@ -279,6 +278,15 @@ impl DynamicDelegate { } } + fn supports_callback_struct(typ: &TypeHandle) -> bool { + let field_count = typ.field_count(); + field_count != 0 + && (0..field_count).all(|index| { + let field = typ.field_type(index); + Self::callback_abi_type(&field).is_some() + }) + } + // ------------------------------------------------------------------ // IUnknown // ------------------------------------------------------------------ @@ -776,25 +784,31 @@ mod tests { } #[test] - fn try_create_delegate_rejects_zero_sized_struct_without_panicking() { + fn try_create_delegate_rejects_zero_field_struct_callback_signature() { let table = MetadataTable::new(); - let progress_type = table.struct_type("Test.EmptyProgress", &[]); - - let result = try_create_delegate( - GUID::from_u128(0x77777777_7777_7777_7777_777777777777), - vec![table.object(), progress_type], - Box::new(|_| HRESULT(0)), + let empty = table.struct_type("Test.EmptyProgress", &[]); + let nested = table.struct_type( + "Test.NestedEmptyProgress", + &[empty.clone(), table.u32_type()], ); - let error = match result { - Ok(_) => panic!("zero-sized struct callback unexpectedly succeeded"), - Err(error) => error, - }; - assert!( - error - .message() - .contains("do not support one or more parameter types") - ); + for progress_type in [empty, nested] { + let result = try_create_delegate( + GUID::from_u128(0x77777777_7777_7777_7777_777777777777), + vec![table.object(), progress_type], + Box::new(|_| HRESULT(0)), + ); + + let error = match result { + Ok(_) => panic!("empty struct callback signature unexpectedly succeeded"), + Err(error) => error, + }; + assert!( + error + .message() + .contains("do not support one or more parameter types") + ); + } } #[test] diff --git a/crates/dynwinrt/src/native_callback.rs b/crates/dynwinrt/src/native_callback.rs index 815fb26a..d045062b 100644 --- a/crates/dynwinrt/src/native_callback.rs +++ b/crates/dynwinrt/src/native_callback.rs @@ -427,4 +427,12 @@ mod tests { }; assert!(error.contains("could not allocate executable callback memory")); } + + #[test] + fn callback_storage_is_safe_to_share_after_initialization() { + fn assert_send_sync() {} + + assert_send_sync::(); + assert_send_sync::(); + } }