From 64c14eba5ae8efb884b37f32f13891a7d720b2f0 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 2 Sep 2026 23:38:00 +0800 Subject: [PATCH 1/2] Add copied IBuffer byte conversions Add shared safe copying through IBufferByteAccess and expose copied byte-container APIs for Python, JavaScript, and generated wrappers. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 877667c9-bbc4-4950-b7d3-d03826a19853 --- bindings/js/README.md | 13 ++ bindings/js/__test__/index.spec.ts | 20 ++ bindings/js/src/lib.rs | 18 ++ bindings/py/README.md | 12 ++ bindings/py/dynwinrt.pyi | 3 + bindings/py/src/runtime.rs | 24 +++ bindings/py/tests/test_phase1.py | 25 +++ crates/dynwinrt/src/ibuffer.rs | 171 ++++++++++++++++++ crates/dynwinrt/src/lib.rs | 2 + crates/dynwinrt/src/result.rs | 24 +++ samples/python/cryptography/README.md | 5 +- samples/python/cryptography/app.py | 21 +-- tests/e2e/e2e_specs.json | 3 +- tests/e2e/e2e_specs.schema.json | 1 + tests/e2e/runners/py_runner.py | 22 +++ tests/e2e/runners/ts_runner.ts | 25 +++ tests/e2e/typecheck/python_generated_api.py | 15 +- .../codegen/winrt/javascript/project/mod.rs | 73 ++++++++ .../dynwinrt-codegen/src/codegen/winrt/mod.rs | 12 ++ .../codegen/winrt/python/generator/class.rs | 12 ++ .../codegen/winrt/python/generator/types.rs | 12 ++ .../src/codegen/winrt/python/stubs.rs | 18 +- .../tests/ibuffer_projection_test.rs | 110 +++++++++++ .../dynwinrt-codegen/tests/tsc_check_test.rs | 2 + 24 files changed, 627 insertions(+), 16 deletions(-) create mode 100644 crates/dynwinrt/src/ibuffer.rs create mode 100644 tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs diff --git a/bindings/js/README.md b/bindings/js/README.md index 0ad1b018..07755868 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -95,6 +95,19 @@ Generated `IReference` values use `T | null` in JavaScript. Native values, The same projection applies when `IReference` appears inside a WinRT struct; packing boxes the field automatically and unpacking returns the native value. +Generated `Windows.Storage.Streams.Buffer` and `IBuffer` projections provide +copied byte conversion. `fromBuffer()` accepts a Node.js `Buffer` or +`Uint8Array`, and `toBuffer()` returns a new `Buffer` containing exactly +`Length` bytes: + +```js +const winrtBuffer = IBuffer.fromBuffer(Buffer.from([0, 1, 255])) +const bytes = winrtBuffer.toBuffer() +``` + +Both directions copy. Mutating the input or releasing the WinRT object does not +change the returned bytes, and no native buffer pointer is exposed. + Generated packages export `createProjectedLifetimeScope()`. WinUI/XAML hosts can create a scope after Application and Window setup, then dispose it before the native window and XAML core are destroyed. Active scopes retain projected diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 24bc4a74..80f58c8c 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -1110,6 +1110,26 @@ test('release WinRT object values deterministically', (t) => { t.notThrows(() => value.release()) }) +test('copy between WinRT IBuffer and Buffer or Uint8Array', (t) => { + const empty = DynWinRtValue.fromBuffer(Buffer.alloc(0)) + t.deepEqual(empty.toBuffer(), Buffer.alloc(0)) + + const input = Uint8Array.from([0, 1, 2, 0, 255, 128]) + const value = DynWinRtValue.fromBuffer(input) + input.fill(9) + const copy = value.toBuffer() + value.release() + + t.true(Buffer.isBuffer(copy)) + t.deepEqual(copy, Buffer.from([0, 1, 2, 0, 255, 128])) + t.throws(() => DynWinRtValue.u8Value(1).toBuffer(), { + message: /Expected a Windows\.Storage\.Streams\.IBuffer/, + }) + t.throws(() => DynWinRtValue.activationFactory('Windows.Foundation.Uri').toBuffer(), { + message: /80004002|No such interface/i, + }) +}) + test('round-trip WinRT value arrays', (t) => { const array = DynWinRtArray.fromI32Values([1, 2, 3]) t.is(array.len(), 3) diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 8efd292a..a62eba25 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -1160,6 +1160,16 @@ impl DynWinRTValue { Ok(DynWinRTValue::new(factory)) } + /// Create an owned WinRT IBuffer by copying a Node.js Buffer or Uint8Array. + #[napi] + pub fn from_buffer( + #[napi(ts_arg_type = "Buffer | Uint8Array")] data: napi::bindgen_prelude::Uint8Array, + ) -> napi::Result { + dynwinrt::copy_to_ibuffer(&data) + .map(DynWinRTValue::new) + .map_err(|error| napi::Error::from_reason(error.message())) + } + /// Create a composed WinUI Application that forwards IXamlMetadataProvider /// calls to the supplied provider. #[napi] @@ -1533,6 +1543,14 @@ impl DynWinRTValue { } } + /// Copy the initialized bytes from a WinRT IBuffer into a Node.js Buffer. + #[napi] + pub fn to_buffer(&self) -> napi::Result { + dynwinrt::copy_from_ibuffer(&self.0) + .map(Into::into) + .map_err(|error| napi::Error::from_reason(error.message())) + } + #[napi] pub fn is_null(&self) -> bool { self.3.is_none() && self.4.is_none() && self.5.is_none() && self.0.is_null_object() diff --git a/bindings/py/README.md b/bindings/py/README.md index 69f0796e..1dfc5d11 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -61,6 +61,18 @@ WinRT collection interfaces. Byte arrays accept `bytes` and `bytearray`; GUID, `DateTime`, and `TimeSpan` values use `uuid.UUID`, `datetime.datetime`, and `datetime.timedelta`. +Generated `Windows.Storage.Streams.Buffer` and `IBuffer` projections also +provide copied byte conversion: + +```python +winrt_buffer = IBuffer.from_bytes(bytearray(b"\x00\x01\xff")) +data: bytes = winrt_buffer.to_bytes() +``` + +Both directions copy exactly `Length` bytes. Mutating the input or releasing +the WinRT object does not change the returned `bytes`, and no native buffer +pointer is exposed. + Exceptions raised by Python event or delegate callbacks are reported through `sys.unraisablehook`. The originating WinRT invocation receives `0xA0EE4005` (`PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION`) instead of unconditional diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 42432ff7..3c7766be 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -258,6 +258,8 @@ class DynWinRTValue: @staticmethod def activation_factory(name: str) -> DynWinRTValue: ... @staticmethod + def from_bytes(data: Union[bytes, bytearray]) -> DynWinRTValue: ... + @staticmethod def create_xaml_application( metadata_provider: DynWinRTValue, launched_callback: Optional[DynWinRTValue] = ..., @@ -322,6 +324,7 @@ class DynWinRTValue: def to_u64(self) -> int: ... def to_f64(self) -> float: ... def to_guid(self) -> WinGUID: ... + def to_bytes(self) -> bytes: ... def is_null(self) -> bool: ... def release(self) -> None: ... def as_raw(self) -> int: ... diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index a2029aba..dc981118 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -1077,6 +1077,23 @@ impl DynWinRTValue { .map_err(map_dynwinrt_error) } + /// Create an owned WinRT IBuffer by copying Python bytes or bytearray data. + #[staticmethod] + fn from_bytes(data: &Bound<'_, PyAny>) -> PyResult { + let bytes = if let Ok(data) = data.cast::() { + data.as_bytes().to_vec() + } else if let Ok(data) = data.cast::() { + data.to_vec() + } else { + return Err(pyo3::exceptions::PyTypeError::new_err( + "from_bytes: expected bytes or bytearray", + )); + }; + dynwinrt::copy_to_ibuffer(&bytes) + .map(DynWinRTValue) + .map_err(map_dynwinrt_error) + } + /// Compose a WinUI `Microsoft.UI.Xaml.Application` whose outer object /// exposes the supplied `IXamlMetadataProvider`. /// @@ -1440,6 +1457,13 @@ impl DynWinRTValue { } } + /// Copy the initialized bytes from a WinRT IBuffer into Python bytes. + fn to_bytes<'py>(&self, py: Python<'py>) -> PyResult> { + dynwinrt::copy_from_ibuffer(&self.0) + .map(|bytes| pyo3::types::PyBytes::new(py, &bytes)) + .map_err(map_dynwinrt_error) + } + fn is_null(&self) -> bool { self.0.is_null_object() } diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index b679e050..3152b552 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -10,6 +10,7 @@ * WinRTAsync — public asyncio-compatible protocols * DynWinRTArray.to_bytes/from_bytes — Pythonic byte-buffer interop * DynWinRTArray.from_object_values — T[] of object/interface elements + * DynWinRTValue.to_bytes/from_bytes — copied IBuffer interop """ import asyncio @@ -1066,6 +1067,30 @@ def test_from_bytes_accepts_bytearray(): assert arr.to_bytes() == bytes(data) +def test_ibuffer_bytes_round_trip_and_copy_isolation(): + empty = DynWinRTValue.from_bytes(b"") + assert empty.to_bytes() == b"" + + data = bytearray(b"\x00\x01\x02\x00\xff\x80") + value = DynWinRTValue.from_bytes(data) + data[:] = b"\x09" * len(data) + copied = value.to_bytes() + value.release() + + assert isinstance(copied, bytes) + assert copied == b"\x00\x01\x02\x00\xff\x80" + + +def test_ibuffer_bytes_rejects_unsupported_values(): + with pytest.raises(RuntimeError, match="Windows.Storage.Streams.IBuffer"): + DynWinRTValue.from_u8(1).to_bytes() + + uri_factory = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + with pytest.raises(OSError) as exc_info: + uri_factory.to_bytes() + assert exc_info.value.winerror == -2147467262 # E_NOINTERFACE + + def test_winrt_datetime_round_trip(): value = datetime(2024, 1, 2, 3, 4, 5, 678901, tzinfo=timezone.utc) assert _dynwinrt_ticks_to_datetime(_dynwinrt_datetime_to_ticks(value)) == value diff --git a/crates/dynwinrt/src/ibuffer.rs b/crates/dynwinrt/src/ibuffer.rs new file mode 100644 index 00000000..433aff9a --- /dev/null +++ b/crates/dynwinrt/src/ibuffer.rs @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::ffi::c_void; + +use windows::Storage::Streams::{Buffer, IBuffer}; +use windows_core::{GUID, HRESULT, IUnknown, Interface}; + +use crate::{Error, Result, WinRTValue}; + +const IID_IBUFFER_BYTE_ACCESS: GUID = GUID::from_u128(0x905a0fef_bc53_11df_8c49_001e4fc686da); + +#[repr(C)] +struct IBufferByteAccessVtbl { + base__: windows_core::IUnknown_Vtbl, + buffer: unsafe extern "system" fn(*mut c_void, *mut *mut u8) -> HRESULT, +} + +fn validate_bounds(length: u32, capacity: u32) -> Result { + if length > capacity { + return Err(Error::InvalidIBufferBounds { length, capacity }); + } + Ok(length as usize) +} + +fn query_byte_pointer(owner: &IBuffer) -> Result<(IUnknown, *mut u8)> { + let owner: IUnknown = owner.cast().map_err(Error::WindowsError)?; + let mut raw_access = std::ptr::null_mut(); + unsafe { owner.query(&IID_IBUFFER_BYTE_ACCESS, &mut raw_access) } + .ok() + .map_err(Error::WindowsError)?; + let access = unsafe { IUnknown::from_raw(raw_access) }; + let vtable = unsafe { *(access.as_raw() as *const *const IBufferByteAccessVtbl) }; + let mut bytes = std::ptr::null_mut(); + unsafe { ((*vtable).buffer)(access.as_raw(), &mut bytes) } + .ok() + .map_err(Error::WindowsError)?; + Ok((access, bytes)) +} + +fn copy_borrowed_bytes(bytes: *const u8, length: usize) -> Result> { + if length == 0 { + return Ok(Vec::new()); + } + if bytes.is_null() { + return Err(Error::NullIBufferPointer { length }); + } + + let mut copy = vec![0; length]; + unsafe { std::ptr::copy_nonoverlapping(bytes, copy.as_mut_ptr(), length) }; + Ok(copy) +} + +/// Copy the initialized bytes from a WinRT `Windows.Storage.Streams.IBuffer`. +/// +/// The native byte pointer is borrowed from the buffer and remains internal to +/// this function. The owning `IBuffer` and its `IBufferByteAccess` interface are +/// retained until the copy completes. +pub fn copy_from_ibuffer(value: &WinRTValue) -> Result> { + let object = value + .as_object() + .ok_or_else(|| Error::ExpectedIBuffer(value.get_type_kind()))?; + let buffer: IBuffer = object.cast().map_err(Error::WindowsError)?; + let capacity = buffer.Capacity().map_err(Error::WindowsError)?; + let length = buffer.Length().map_err(Error::WindowsError)?; + let length = validate_bounds(length, capacity)?; + let (_access, bytes) = query_byte_pointer(&buffer)?; + copy_borrowed_bytes(bytes, length) +} + +/// Create an owned WinRT `IBuffer` whose `Length` and `Capacity` equal the +/// number of copied input bytes. +pub fn copy_to_ibuffer(bytes: &[u8]) -> Result { + let length = + u32::try_from(bytes.len()).map_err(|_| Error::IBufferInputTooLarge(bytes.len()))?; + let buffer = Buffer::Create(length).map_err(Error::WindowsError)?; + let ibuffer: IBuffer = buffer.cast().map_err(Error::WindowsError)?; + let (_access, destination) = query_byte_pointer(&ibuffer)?; + + if !bytes.is_empty() { + if destination.is_null() { + return Err(Error::NullIBufferPointer { + length: bytes.len(), + }); + } + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), destination, bytes.len()) }; + } + ibuffer.SetLength(length).map_err(Error::WindowsError)?; + + debug_assert_eq!(ibuffer.Length().ok(), Some(length)); + debug_assert_eq!(ibuffer.Capacity().ok(), Some(length)); + Ok(WinRTValue::Object( + ibuffer.cast().map_err(Error::WindowsError)?, + )) +} + +#[cfg(test)] +mod tests { + use windows::Foundation::Uri; + + use super::*; + + #[test] + fn validates_length_does_not_exceed_capacity() { + assert_eq!(validate_bounds(0, 0).unwrap(), 0); + assert_eq!(validate_bounds(3, 4).unwrap(), 3); + assert!(matches!( + validate_bounds(5, 4), + Err(Error::InvalidIBufferBounds { + length: 5, + capacity: 4 + }) + )); + } + + #[test] + fn handles_null_borrowed_pointers_without_dereferencing_them() { + assert_eq!( + copy_borrowed_bytes(std::ptr::null(), 0).unwrap(), + Vec::::new() + ); + assert!(matches!( + copy_borrowed_bytes(std::ptr::null(), 1), + Err(Error::NullIBufferPointer { length: 1 }) + )); + } + + #[test] + fn copies_empty_and_binary_buffers() -> Result<()> { + let empty = copy_to_ibuffer(&[])?; + assert_eq!(copy_from_ibuffer(&empty)?, Vec::::new()); + + let expected = vec![0, 1, 2, 0, 0xff, 0x80, 3]; + let buffer = copy_to_ibuffer(&expected)?; + assert_eq!(copy_from_ibuffer(&buffer)?, expected); + Ok(()) + } + + #[test] + fn returned_copy_outlives_owner() -> Result<()> { + let buffer = copy_to_ibuffer(&[9, 8, 7, 0])?; + let bytes = copy_from_ibuffer(&buffer)?; + drop(buffer); + assert_eq!(bytes, [9, 8, 7, 0]); + Ok(()) + } + + #[test] + fn input_is_copied() -> Result<()> { + let mut input = vec![1, 2, 3]; + let buffer = copy_to_ibuffer(&input)?; + input.fill(9); + assert_eq!(copy_from_ibuffer(&buffer)?, [1, 2, 3]); + Ok(()) + } + + #[test] + fn rejects_non_ibuffer_objects() { + let uri = Uri::CreateUri(&"https://example.com".into()).unwrap(); + let value = WinRTValue::Object(uri.cast().unwrap()); + let error = copy_from_ibuffer(&value).unwrap_err(); + assert!(matches!(error, Error::WindowsError(_))); + assert!(error.message().contains("0x80004002")); + } + + #[test] + fn rejects_non_object_values() { + let error = copy_from_ibuffer(&WinRTValue::U8(1)).unwrap_err(); + assert!(matches!(error, Error::ExpectedIBuffer(_))); + } +} diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index c72cca64..d22e7283 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -7,6 +7,7 @@ mod abi; mod call; pub mod com; mod composition; +mod ibuffer; mod interfaces; mod native_call; mod native_callback; @@ -46,6 +47,7 @@ pub use crate::element_factory::{ ElementFactoryGetCallback, ElementFactoryRecycleCallback, create_element_factory, create_element_factory_value, }; +pub use crate::ibuffer::{copy_from_ibuffer, copy_to_ibuffer}; pub use crate::metadata_table::{MetadataTable, MethodHandle, TypeHandle, TypeKind, ValueTypeData}; pub use crate::reference::box_ireference; pub use crate::result::{Error, Result}; diff --git a/crates/dynwinrt/src/result.rs b/crates/dynwinrt/src/result.rs index dacf2990..82d09f66 100644 --- a/crates/dynwinrt/src/result.rs +++ b/crates/dynwinrt/src/result.rs @@ -22,6 +22,15 @@ pub enum Error { ExpectedAsync(TypeKind), UnsupportedCollectionElement(TypeKind), InvalidCollectionValue(&'static str), + ExpectedIBuffer(TypeKind), + InvalidIBufferBounds { + length: u32, + capacity: u32, + }, + NullIBufferPointer { + length: usize, + }, + IBufferInputTooLarge(usize), /// An async operation was canceled (status == AsyncStatus::Canceled). Canceled, } @@ -69,6 +78,21 @@ impl Error { Error::InvalidCollectionValue(expected) => { format!("Invalid dynamic collection value: expected {expected}") } + Error::ExpectedIBuffer(actual) => { + format!("Expected a Windows.Storage.Streams.IBuffer object, found {actual:?}") + } + Error::InvalidIBufferBounds { length, capacity } => { + format!("Invalid IBuffer bounds: Length {length} exceeds Capacity {capacity}") + } + Error::NullIBufferPointer { length } => { + format!("IBufferByteAccess returned a null pointer for {length} bytes") + } + Error::IBufferInputTooLarge(length) => { + format!( + "Cannot create an IBuffer from {length} bytes; the maximum is {}", + u32::MAX + ) + } Error::Canceled => "Async operation was canceled".to_string(), } } diff --git a/samples/python/cryptography/README.md b/samples/python/cryptography/README.md index 7b7f5864..b9649b78 100644 --- a/samples/python/cryptography/README.md +++ b/samples/python/cryptography/README.md @@ -3,8 +3,9 @@ This sample computes SHA-256 with generated Windows Runtime cryptography APIs and verifies the result against Python's `hashlib`. -It demonstrates primitive enums, `IBuffer` values, static WinRT APIs, and -hexadecimal conversion without files, hardware, or network access. +It demonstrates copied `bytes`/`IBuffer` conversion, static WinRT APIs, and +digest extraction without files, hardware, or network access. Both conversion +directions own their copy; no native buffer pointer escapes. ```powershell .\generate.ps1 -Codegen ..\..\..\target\release\dynwinrt-codegen.exe diff --git a/samples/python/cryptography/app.py b/samples/python/cryptography/app.py index c9c67488..e0a7c5c3 100644 --- a/samples/python/cryptography/app.py +++ b/samples/python/cryptography/app.py @@ -2,11 +2,8 @@ import hashlib from dynwinrt import RoApartment, projected_lifetime_scope -from generated.windows.security.cryptography import ( - BinaryStringEncoding, - CryptographicBuffer, -) from generated.windows.security.cryptography.core import HashAlgorithmProvider +from generated.windows.storage.streams import IBuffer def sha256(text: str) -> str: @@ -14,16 +11,18 @@ def sha256(text: str) -> str: provider = HashAlgorithmProvider.open_algorithm("SHA256") if provider is None: raise RuntimeError("SHA256 provider is unavailable") - data = CryptographicBuffer.convert_string_to_binary( - text, - BinaryStringEncoding.Utf8, - ) - if data is None: - raise RuntimeError("CryptographicBuffer returned no input buffer") + data = IBuffer.from_bytes(text.encode("utf-8")) digest = provider.hash_data(data) if digest is None: raise RuntimeError("HashAlgorithmProvider returned no digest") - return CryptographicBuffer.encode_to_hex_string(digest).lower() + copied_digest = digest.to_bytes() + expected_length = provider.hash_length + if len(copied_digest) != expected_length: + raise RuntimeError( + f"SHA256 buffer length mismatch: {len(copied_digest)} != " + f"{expected_length}" + ) + return copied_digest.hex() def main() -> None: diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index c2963bf3..709bf04f 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -196,7 +196,8 @@ }, "checks": [ { "kind": "property_equals", "member": "capacity", "expected": 1024 }, - { "kind": "property_equals", "member": "length", "expected": 0 } + { "kind": "property_equals", "member": "length", "expected": 0 }, + { "kind": "ibuffer_copied_roundtrip", "member": "copied_bytes" } ] }, { diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index 94494f3a..fc2ecf9e 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -88,6 +88,7 @@ "static_uuid_roundtrip", "static_uuid_input", "static_bytes_input", + "ibuffer_copied_roundtrip", "static_sequence_input", "closable_context", "method_then_property_equals", diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index e2026415..59f2c6a6 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -191,6 +191,28 @@ async def run_check( else: cr['pass'] = True + elif kind == 'ibuffer_copied_roundtrip': + empty = cls.from_bytes(b'') + if empty.capacity != 0 or empty.length != 0 or empty.to_bytes() != b'': + cr['error'] = 'empty IBuffer copy round-trip failed' + return cr + + mutable = bytearray(b'\x00\x01\x02\x00\xff\x80') + buffer = cls.from_bytes(mutable) + mutable[:] = b'\x09' * len(mutable) + copied = buffer.to_bytes() + if buffer.capacity != 6 or buffer.length != 6: + cr['error'] = ( + f'expected Length/Capacity 6, got ' + f'{buffer.length}/{buffer.capacity}' + ) + return cr + buffer._obj.release() + if copied != b'\x00\x01\x02\x00\xff\x80': + cr['error'] = f'copied bytes changed after owner release: {copied!r}' + return cr + cr['pass'] = True + elif kind == 'property_exists': _ = getattr(obj, member) cr['pass'] = True diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index ee484c86..ee2b447b 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -267,6 +267,31 @@ async function runCheck( } else { cr.pass = true; } + } else if (kind === "ibuffer_copied_roundtrip") { + const empty = cls.fromBuffer(Buffer.alloc(0)); + if ( + empty.capacity !== 0 || + empty.length !== 0 || + !empty.toBuffer().equals(Buffer.alloc(0)) + ) { + cr.error = "empty IBuffer copy round-trip failed"; + return cr; + } + + const mutable = Uint8Array.from([0, 1, 2, 0, 255, 128]); + const buffer = cls.fromBuffer(mutable); + mutable.fill(9); + const copied = buffer.toBuffer(); + if (buffer.capacity !== 6 || buffer.length !== 6) { + cr.error = `expected Length/Capacity 6, got ${buffer.length}/${buffer.capacity}`; + return cr; + } + buffer._obj.release(); + if (!copied.equals(Buffer.from([0, 1, 2, 0, 255, 128]))) { + cr.error = `copied bytes changed after owner release: ${copied.toString("hex")}`; + return cr; + } + cr.pass = true; } else if (kind === "property_exists") { const _ = obj[member]; // should not throw cr.pass = true; diff --git a/tests/e2e/typecheck/python_generated_api.py b/tests/e2e/typecheck/python_generated_api.py index 1acfab37..63a2758e 100644 --- a/tests/e2e/typecheck/python_generated_api.py +++ b/tests/e2e/typecheck/python_generated_api.py @@ -20,7 +20,12 @@ Uri, ) from python_bindings.windows.globalization import Calendar -from python_bindings.windows.storage.streams import DataWriter, IBuffer, IOutputStream +from python_bindings.windows.storage.streams import ( + Buffer as WinRTBuffer, + DataWriter, + IBuffer, + IOutputStream, +) def check_runtime_stubs() -> None: @@ -90,3 +95,11 @@ def check_async_types( write.progress(lambda value: value) progress_awaitable: Awaitable[int] = write _: Tuple[Awaitable[int], Awaitable[int]] = (awaitable, progress_awaitable) + + +def check_ibuffer_bytes() -> None: + interface_buffer: IBuffer = IBuffer.from_bytes(bytearray(b"\x00\xff")) + runtime_buffer: WinRTBuffer = WinRTBuffer.from_bytes(b"\x01\x02") + interface_bytes: bytes = interface_buffer.to_bytes() + runtime_bytes: bytes = runtime_buffer.to_bytes() + _: Tuple[bytes, bytes] = (interface_bytes, runtime_bytes) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs index 70e14b77..2c89fd48 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs @@ -145,6 +145,65 @@ const PIID_IMAP_VIEW: &str = "e480ce40-a338-4ada-adcf-272272e48cb9"; const ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e"; const ISTRINGABLE_IID: &str = "96369f54-8eb6-48f0-abce-c1b211e627c3"; +fn project_ibuffer_members(projected_name: &str, from_native: &str) -> [ProjectedMember; 2] { + let from_buffer = ProjectedMember::Method(ProjectedMethod { + name: "fromBuffer".into(), + doc: Some(DocInfo { + summary: Some( + "Create an owned IBuffer by copying a Node.js Buffer or Uint8Array.".into(), + ), + deprecated: None, + returns: None, + params: vec![("data".into(), "Bytes to copy into the new IBuffer.".into())], + }), + params: vec![ProjectedParam { + name: "data".into(), + ts_type: "Parameters[0]".into(), + optional: false, + delegate_wrap: None, + }], + argument_kinds: vec![Some(JsArgumentKind::Object)], + return_type: projected_name.into(), + async_kind: AsyncKind::None, + is_static: true, + invoke_expr: String::new(), + sync_return_expr: Some(format!("{from_native}(DynWinRtValue.fromBuffer(data))")), + async_convert_v: None, + progress_convert: None, + is_void: false, + array_return_expr: None, + delegate_wraps: vec![], + js_only: false, + overload_of: None, + }); + let to_buffer = ProjectedMember::Method(ProjectedMethod { + name: "toBuffer".into(), + doc: Some(DocInfo { + summary: Some( + "Copy this IBuffer's initialized bytes into a new Node.js Buffer.".into(), + ), + deprecated: None, + returns: None, + params: vec![], + }), + params: vec![], + argument_kinds: vec![], + return_type: "ReturnType".into(), + async_kind: AsyncKind::None, + is_static: false, + invoke_expr: String::new(), + sync_return_expr: Some("this._obj.toBuffer()".into()), + async_convert_v: None, + progress_convert: None, + is_void: false, + array_return_expr: None, + delegate_wraps: vec![], + js_only: false, + overload_of: None, + }); + [from_buffer, to_buffer] +} + fn project_winui_abi_types(types: &[WinUiAbiType]) -> String { types .iter() @@ -633,6 +692,13 @@ pub fn project_class( overload_of: None, })); + if crate::codegen::winrt::is_buffer_class(&class.namespace, &class.name) { + members.extend(project_ibuffer_members( + &class.name, + &format!("{}._fromNative", class.name), + )); + } + // Default constructor (static create/createDefault) if class.has_default_constructor { let ctor_name = default_activation_method_name(class); @@ -1320,6 +1386,13 @@ pub fn project_interface( // Static create() for IVector / IMap project_collection_create(context, iface, known_types, &mut members, &mut imports); + if crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid) { + members.extend(project_ibuffer_members( + &iface.name, + &format!("{}.from", iface.name), + )); + } + if iface.namespace == "Microsoft.UI.Xaml" && context.metadata_type_name(&iface.namespace, &iface.name) == "IElementFactory" { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/mod.rs index 6b6ca290..49f9f905 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/mod.rs @@ -7,3 +7,15 @@ pub mod extensions; pub mod javascript; pub mod python; pub(crate) mod shared; + +pub(crate) const IBUFFER_IID: &str = "905a0fe0-bc53-11df-8c49-001e4fc686da"; + +pub(crate) fn is_ibuffer_interface(namespace: &str, name: &str, iid: &str) -> bool { + namespace == "Windows.Storage.Streams" + && name == "IBuffer" + && iid.eq_ignore_ascii_case(IBUFFER_IID) +} + +pub(crate) fn is_buffer_class(namespace: &str, name: &str) -> bool { + namespace == "Windows.Storage.Streams" && name == "Buffer" +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs index b8e8e56d..7893e33c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -357,6 +357,18 @@ pub fn generate_class( collection_uses_default, )); + if crate::codegen::winrt::is_buffer_class(&class.namespace, &class.name) { + out.push_str( + " @staticmethod\n\ + \x20 def from_bytes(data: bytes | bytearray) -> 'Buffer':\n\ + \x20 \"\"\"Create an owned IBuffer by copying bytes or bytearray data.\"\"\"\n\ + \x20 return Buffer._from_native(DynWinRTValue.from_bytes(data))\n\n\ + \x20 def to_bytes(self) -> bytes:\n\ + \x20 \"\"\"Copy the initialized IBuffer data into a new bytes object.\"\"\"\n\ + \x20 return self._obj.to_bytes()\n\n", + ); + } + // Resolve activation factories per call. Keeping COM factories in Python // class variables lets them outlive the thread's RoApartment and can crash // during interpreter shutdown when WinUI releases them after RoUninitialize. diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs index 01d05b9c..ec56d42a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -411,6 +411,18 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } } + if crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid) { + out.push_str( + " @staticmethod\n\ + \x20 def from_bytes(data: bytes | bytearray) -> 'IBuffer':\n\ + \x20 \"\"\"Create an owned IBuffer by copying bytes or bytearray data.\"\"\"\n\ + \x20 return IBuffer._from_native(DynWinRTValue.from_bytes(data))\n\n\ + \x20 def to_bytes(self) -> bytes:\n\ + \x20 \"\"\"Copy the initialized IBuffer data into a new bytes object.\"\"\"\n\ + \x20 return self._obj.to_bytes()\n\n", + ); + } + if is_element_factory { let get_args = py_runtime_named_symbol( context, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 9af6054e..a9aebc17 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -405,6 +405,13 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf " def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ...\n", ); } + if crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid) { + out.push_str( + "\n @staticmethod\n\ + \x20 def from_bytes(data: bytes | bytearray) -> 'IBuffer': ...\n\ + \x20 def to_bytes(self) -> bytes: ...\n", + ); + } // IVector / IMap create() if let Some(ref piid) = iface.generic_piid { @@ -755,8 +762,11 @@ pub fn generate_class_stub( )), _ => None, }); - let instance_stub_body = + let mut instance_stub_body = emit_class_instance_stubs(class, context, collection_iface, false, has_closable); + if crate::codegen::winrt::is_buffer_class(&class.namespace, &class.name) { + instance_stub_body.push_str(" def to_bytes(self) -> bytes: ...\n"); + } let identity_name = format!("_{}Identity", class.name); let mut identity_bases = base_identity.into_iter().collect::>(); identity_bases.push("Protocol".into()); @@ -810,6 +820,12 @@ pub fn generate_class_stub( " ", )); out.push_str(&emit_constructor_stubs(class, context)); + if crate::codegen::winrt::is_buffer_class(&class.namespace, &class.name) { + out.push_str( + " @staticmethod\n\ + \x20 def from_bytes(data: bytes | bytearray) -> 'Buffer': ...\n", + ); + } if collection_base.is_some() { out.push_str(&emit_class_instance_stubs( class, diff --git a/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs b/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs new file mode 100644 index 00000000..ddc377d9 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +mod common; + +use std::collections::{HashMap, HashSet}; + +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; +use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta}; + +fn ibuffer() -> InterfaceMeta { + InterfaceMeta { + name: "IBuffer".into(), + namespace: "Windows.Storage.Streams".into(), + iid: "905A0FE0-BC53-11DF-8C49-001E4FC686DA".into(), + ..Default::default() + } +} + +fn buffer_class() -> ClassMeta { + ClassMeta { + name: "Buffer".into(), + namespace: "Windows.Storage.Streams".into(), + full_name: "Windows.Storage.Streams.Buffer".into(), + default_interface: Some(ibuffer()), + ..Default::default() + } +} + +#[test] +fn javascript_projects_copied_ibuffer_conversions() { + let class = buffer_class(); + let projected = project::project_class( + &Default::default(), + &class, + &HashSet::from(["Buffer".into(), "IBuffer".into()]), + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let js = render_js::render(&projected); + let dts = render_dts::render(&projected); + + assert!(js.contains("static fromBuffer(data)")); + assert!(js.contains("Buffer._fromNative(DynWinRtValue.fromBuffer(data))")); + assert!(js.contains("toBuffer()")); + assert!(js.contains("return this._obj.toBuffer();")); + assert!(dts.contains("data: Parameters[0]")); + assert!(dts.contains("ReturnType")); + + let interface = ibuffer(); + let projected = project::project_interface( + &Default::default(), + &interface, + &HashSet::from(["IBuffer".into()]), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let js = render_js::render(&projected); + let dts = render_dts::render(&projected); + assert!(js.contains("IBuffer.from(DynWinRtValue.fromBuffer(data))")); + assert!(dts.contains("static fromBuffer(")); + assert!(dts.contains("toBuffer(): ReturnType;")); +} + +#[test] +fn python_projects_copied_ibuffer_conversions() { + let class = buffer_class(); + let known = HashSet::from(["Buffer".into(), "IBuffer".into()]); + let implementation = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let stub = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + assert!(implementation.contains("def from_bytes(data: bytes | bytearray) -> 'Buffer':")); + assert!(implementation.contains("return Buffer._from_native(DynWinRTValue.from_bytes(data))")); + assert!(implementation.contains("return self._obj.to_bytes()")); + assert!(stub.contains("def from_bytes(data: bytes | bytearray) -> 'Buffer': ...")); + assert!(stub.contains("def to_bytes(self) -> bytes: ...")); + + let interface = ibuffer(); + let implementation = common::generate_interface( + &interface, + &HashSet::from(["IBuffer".into()]), + &HashSet::new(), + ); + let stub = common::generate_interface_stub( + &interface, + &HashSet::from(["IBuffer".into()]), + &HashSet::new(), + ); + assert!(implementation.contains("def from_bytes(data: bytes | bytearray) -> 'IBuffer':")); + assert!(implementation.contains("return IBuffer._from_native(DynWinRTValue.from_bytes(data))")); + assert!(stub.contains("def from_bytes(data: bytes | bytearray) -> 'IBuffer': ...")); + assert!(stub.contains("def to_bytes(self) -> bytes: ...")); +} + +#[test] +fn lookalike_interfaces_do_not_receive_ibuffer_conversions() { + let mut interface = ibuffer(); + interface.namespace = "Contoso".into(); + let implementation = common::generate_interface( + &interface, + &HashSet::from(["IBuffer".into()]), + &HashSet::new(), + ); + assert!(!implementation.contains("def from_bytes")); + assert!(!implementation.contains("def to_bytes")); +} diff --git a/tools/dynwinrt-codegen/tests/tsc_check_test.rs b/tools/dynwinrt-codegen/tests/tsc_check_test.rs index 7b6c8847..97b0099c 100644 --- a/tools/dynwinrt-codegen/tests/tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/tsc_check_test.rs @@ -240,6 +240,7 @@ export declare class DynWinRtValue { toF64(): number; toBool(): boolean; toString(): string; + toBuffer(): Uint8Array; asArray(): DynWinRtArray; asStruct(): DynWinRtStruct; cast(iid: WinGuid): DynWinRtValue; @@ -250,6 +251,7 @@ export declare class DynWinRtValue { static hstring(s: string): DynWinRtValue; static fromI32(n: number): DynWinRtValue; static fromBool(b: boolean): DynWinRtValue; + static fromBuffer(data: Uint8Array): DynWinRtValue; static createVector(items: DynWinRtValue[], elemType: DynWinRtType): DynWinRtValue; static createMap(keys: DynWinRtValue[], values: DynWinRtValue[], keyType: DynWinRtType, valueType: DynWinRtType): DynWinRtValue; [key: string]: any; From c6c7aa638919cc16e597a61bb802d23fa1545bc6 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 2 Sep 2026 23:50:16 +0800 Subject: [PATCH 2/2] Reject null IBufferByteAccess results Use a typed exact-IID QueryInterface cast so malformed successful queries with null outputs return E_POINTER before pointer adoption or vtable access. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 877667c9-bbc4-4950-b7d3-d03826a19853 --- crates/dynwinrt/src/ibuffer.rs | 102 +++++++++++++++++++++++++++++---- 1 file changed, 91 insertions(+), 11 deletions(-) diff --git a/crates/dynwinrt/src/ibuffer.rs b/crates/dynwinrt/src/ibuffer.rs index 433aff9a..c28e1036 100644 --- a/crates/dynwinrt/src/ibuffer.rs +++ b/crates/dynwinrt/src/ibuffer.rs @@ -4,14 +4,19 @@ use std::ffi::c_void; use windows::Storage::Streams::{Buffer, IBuffer}; -use windows_core::{GUID, HRESULT, IUnknown, Interface}; +use windows_core::{HRESULT, IUnknown, Interface}; use crate::{Error, Result, WinRTValue}; -const IID_IBUFFER_BYTE_ACCESS: GUID = GUID::from_u128(0x905a0fef_bc53_11df_8c49_001e4fc686da); +windows_core::imp::define_interface!( + IBufferByteAccess, + IBufferByteAccessVtbl, + 0x905a0fef_bc53_11df_8c49_001e4fc686da +); +windows_core::imp::interface_hierarchy!(IBufferByteAccess, IUnknown); #[repr(C)] -struct IBufferByteAccessVtbl { +pub struct IBufferByteAccessVtbl { base__: windows_core::IUnknown_Vtbl, buffer: unsafe extern "system" fn(*mut c_void, *mut *mut u8) -> HRESULT, } @@ -23,16 +28,15 @@ fn validate_bounds(length: u32, capacity: u32) -> Result { Ok(length as usize) } -fn query_byte_pointer(owner: &IBuffer) -> Result<(IUnknown, *mut u8)> { +fn query_byte_access(owner: &IUnknown) -> Result { + owner.cast().map_err(Error::WindowsError) +} + +fn query_byte_pointer(owner: &IBuffer) -> Result<(IBufferByteAccess, *mut u8)> { let owner: IUnknown = owner.cast().map_err(Error::WindowsError)?; - let mut raw_access = std::ptr::null_mut(); - unsafe { owner.query(&IID_IBUFFER_BYTE_ACCESS, &mut raw_access) } - .ok() - .map_err(Error::WindowsError)?; - let access = unsafe { IUnknown::from_raw(raw_access) }; - let vtable = unsafe { *(access.as_raw() as *const *const IBufferByteAccessVtbl) }; + let access = query_byte_access(&owner)?; let mut bytes = std::ptr::null_mut(); - unsafe { ((*vtable).buffer)(access.as_raw(), &mut bytes) } + unsafe { (Interface::vtable(&access).buffer)(Interface::as_raw(&access), &mut bytes) } .ok() .map_err(Error::WindowsError)?; Ok((access, bytes)) @@ -96,9 +100,77 @@ pub fn copy_to_ibuffer(bytes: &[u8]) -> Result { #[cfg(test)] mod tests { + use std::ffi::c_void; + use windows::Foundation::Uri; + use windows_core::{GUID, HRESULT, IUnknown, Interface}; use super::*; + use crate::com_helpers::{E_NOINTERFACE, E_POINTER, S_OK}; + + #[repr(C)] + struct NullByteAccessQuery { + vtable: *const windows_core::IUnknown_Vtbl, + ref_count: windows_core::imp::RefCount, + } + + impl NullByteAccessQuery { + const VTABLE: windows_core::IUnknown_Vtbl = windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }; + + fn new() -> IUnknown { + let object = Box::new(Self { + vtable: &Self::VTABLE, + ref_count: windows_core::imp::RefCount::new(1), + }); + unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) } + } + + unsafe fn from_ptr(this: *mut c_void) -> &'static Self { + unsafe { &*(this as *const Self) } + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + + unsafe { + *result = std::ptr::null_mut(); + if *iid == IUnknown::IID { + *result = this; + Self::from_ptr(this).ref_count.add_ref(); + S_OK + } else if *iid == IBufferByteAccess::IID { + S_OK + } else { + E_NOINTERFACE + } + } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + unsafe { Self::from_ptr(this).ref_count.add_ref() } + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + unsafe { + let object = Self::from_ptr(this); + let remaining = object.ref_count.release(); + if remaining == 0 { + drop(Box::from_raw(this as *mut Self)); + } + remaining + } + } + } #[test] fn validates_length_does_not_exceed_capacity() { @@ -125,6 +197,14 @@ mod tests { )); } + #[test] + fn rejects_successful_query_interface_with_null_output() { + let owner = NullByteAccessQuery::new(); + let error = query_byte_access(&owner).unwrap_err(); + assert!(matches!(error, Error::WindowsError(_))); + assert!(error.message().contains("0x80004003")); + } + #[test] fn copies_empty_and_binary_buffers() -> Result<()> { let empty = copy_to_ibuffer(&[])?;