diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6ce079b2..f584f182 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -73,6 +73,47 @@ jobs: $PSNativeCommandUseErrorActionPreference = $true python eng\release\python\verify_python_release.py source + test-pod-vectors: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-pc-windows-msvc + runner: windows-latest + host: X64 + - target: i686-pc-windows-msvc + runner: windows-latest + host: X64 + - target: aarch64-pc-windows-msvc + runner: windows-11-arm + host: Arm64 + env: + POD_TEST_TARGET: ${{ matrix.target }} + POD_TEST_HOST: ${{ matrix.host }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - name: Verify native POD test host + shell: pwsh + run: | + $hostArchitecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() + if ($hostArchitecture -ne $env:POD_TEST_HOST) { + throw "POD tests require a native $env:POD_TEST_HOST host, found $hostArchitecture" + } + Write-Host "POD vectors: host=$hostArchitecture, target=$env:POD_TEST_TARGET" + - name: Execute optimized collection and callback regressions + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + cargo test --locked --release -p dynwinrt --target $env:POD_TEST_TARGET --lib -- ` + vector:: collection_element:: native_callback:: map:: + # Rust test programs are independent builds, not reusable runtime packages. test-rust: if: needs.changes.outputs.docs_only == 'false' @@ -645,16 +686,16 @@ jobs: # Stable check identities also complete on intentional documentation-only skips. test: if: ${{ always() }} - needs: [changes, format, test-rust] + needs: [changes, format, test-rust, test-pod-vectors] runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Require Rust validation env: NEEDS: ${{ toJSON(needs) }} - REQUIRED_JOBS: changes,format,test-rust + REQUIRED_JOBS: changes,format,test-rust,test-pod-vectors DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} - DOCS_SKIPPABLE_JOBS: test-rust + DOCS_SKIPPABLE_JOBS: test-rust,test-pod-vectors run: | .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') @@ -794,6 +835,7 @@ jobs: changes, format, test-rust, + test-pod-vectors, test, build-codegen-x64, build-bindings-x64, @@ -811,9 +853,9 @@ jobs: - name: Require every Build job env: NEEDS: ${{ toJSON(needs) }} - REQUIRED_JOBS: changes,format,test-rust,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native,e2e,dynwinrt,dynwinrt-codegen + REQUIRED_JOBS: changes,format,test-rust,test-pod-vectors,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native,e2e,dynwinrt,dynwinrt-codegen DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} - DOCS_SKIPPABLE_JOBS: test-rust,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native + DOCS_SKIPPABLE_JOBS: test-rust,test-pod-vectors,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native run: | .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') diff --git a/bindings/js/README.md b/bindings/js/README.md index b45bf24e..e39e99a0 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -370,21 +370,31 @@ complete set of closed collection IIDs before creating a native object. These limits apply to **producing** collections, including generated input conversions, not to consuming collections returned by Windows. +**Phase one (#161), proposed for this release:** the following matrix describes +the proposed capability, subject to PR review, final integration, and platform +CI. POD vector support is independent of Classic COM/Win32 and does not expand +map admission. + | Element / key / value | x64 | ARM64 | i686 | |---|---|---|---| | Boolean, integers, Char16, enum, HRESULT | Supported | Supported | Up to 4 bytes; I64/U64 rejected | | HSTRING; owned nullable interface/object references | Supported | Supported | Supported | -| POD structs in populated vectors or maps | Sizes 1, 2, 4, 8 | Up to 8 bytes, non-HFA only | Up to 4 bytes | -| Additional POD structs in **empty vectors only** | Larger than 8 bytes | Larger than 16 bytes, non-HFA only | None | +| Validated POD structs in empty or populated vectors | Supported | Supported, including HFAs | Supported | +| POD struct map keys/values (unchanged) | Sizes 1, 2, 4, 8 | Up to 8 bytes, non-HFA only | Up to 4 bytes | | Top-level F32/F64/GUID; structs recursively containing HSTRING or references | Rejected, even empty | Rejected, even empty | Rejected, even empty | POD means a validated, reference-free native layout. HFA means an aggregate of one to four same-width floating-point values, including nested aggregates. -Thus `Point`/`Size` work on x64 but are rejected on ARM64 even when empty; -`PointInt32` works on x64 and ARM64. ARM64 also rejects empty `RectInt32`, -`Rect`, and `BasicGeoposition` vectors. `ManipulationDelta` (20 bytes, five floats, -non-HFA) supports empty -vectors on x64 and ARM64. Large map keys/values are rejected even for empty maps. +Examples include `Point`/`Size`, `PointInt32`, `RectInt32`, `Rect`, +`BasicGeoposition`, and nested PODs such as `ManipulationDelta` and +`ManipulationVelocities`; these are not a runtime whitelist. Empty vectors are +real, non-null, fully mutable collections. Large map keys/values and ARM64 HFA +map elements remain rejected even for empty maps. +Struct ABI entrypoints use cached libffi callbacks where the word fast path +does not apply. A process that prohibits executable callback allocation can +reject construction before publishing an object. +See the [POD vector architecture](../../docs/architecture/winrt-pod-vectors.md) +for layout, storage, callback lifetime, and remaining limitations. Structs and typed enums require exact type identity, not a matching byte size or shape. Scalars require the matching value variant, except U16 inputs for @@ -408,7 +418,9 @@ the same checks. The metadata-free Rust `create_value_vector`, `create_vector`, and `create_map` constructors require `unsafe`: callers must prove the native ABI, ownership, element types, and complete IID set themselves. The metadata-free `create_value_vector` retains packed-byte equality, including -padding, rather than metadata-directed field equality. +padding, rather than metadata-directed field equality. Its original restricted +word/empty-indirect ABI contract is unchanged; it does not gain checked POD +vector support. Complete native struct collection support is tracked in [microsoft/dynwinrt#161](https://github.com/microsoft/dynwinrt/issues/161). diff --git a/bindings/js/__test__/collection-struct-equality.e2e.mjs b/bindings/js/__test__/collection-struct-equality.e2e.mjs index d7b2729e..551e57fe 100644 --- a/bindings/js/__test__/collection-struct-equality.e2e.mjs +++ b/bindings/js/__test__/collection-struct-equality.e2e.mjs @@ -68,14 +68,23 @@ test('checked Point map keys compare fields numerically', { skip: process.arch ! } }) -test('Point collection admission is unchanged on non-x64 targets', { skip: process.arch === 'x64' }, (t) => { - const keep = own(t) - const source = keep(point(0, 1)) - const value = keep(DynWinRtValue.i32(7)) - for (const items of [[], [source]]) { - assert.throws(() => DynWinRtValue.createVector(items, pointType)) - assert.throws(() => - DynWinRtValue.createMap(items, items.map(() => value), pointType, DynWinRtType.i32()), - ) - } -}) +test( + 'Point vectors work without broadening map admission on non-x64 targets', + { skip: process.arch === 'x64' }, + (t) => { + const keep = own(t) + const source = keep(point(0, 1)) + const value = keep(DynWinRtValue.i32(7)) + for (const items of [[], [source]]) { + assert.equal(keep(DynWinRtValue.createVector(items, pointType)).isNull(), false) + assert.throws(() => + DynWinRtValue.createMap( + items, + items.map(() => value), + pointType, + DynWinRtType.i32(), + ), + ) + } + }, +) diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index f9e7b134..64643d63 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -1918,10 +1918,6 @@ test('create empty vectors for large struct element types', (t) => { DynWinRtType.i32(), DynWinRtType.i32(), ]) - if (process.arch !== 'x64') { - t.throws(() => DynWinRtValue.createVector([], rectType)) - return - } const vector = DynWinRtValue.createVector([], rectType) const vectorIid = DynWinRtType.parameterized(WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), [rectType]).iid() @@ -2128,7 +2124,7 @@ test('collection producers retain direct strings and nullable references with th } }) -test('collection producers enforce the architecture-specific small POD boundary', (t) => { +test('POD vectors are complete while maps retain their architecture-specific boundary', (t) => { const cases = [ { name: 'CollectionBoundary.Byte', @@ -2183,7 +2179,7 @@ test('collection producers enforce the architecture-specific small POD boundary' const supported = process.arch === 'x64' || (process.arch === 'arm64' && !entry.hfa) || (process.arch === 'ia32' && entry.size <= 4) for (const producer of collectionProducerCases(type, [])) { - if (supported) { + if (producer.name === 'vector' || supported) { t.false(producer.create().isNull()) } else { t.throws(producer.create, undefined, entry.name) @@ -2195,14 +2191,19 @@ test('collection producers enforce the architecture-specific small POD boundary' t.is(entry.read(fromMap.asStruct()), entry.expected) t.is(keyLookup.toNumber(), 0) } else { - for (const producer of collectionProducerCases(type, [value.toValue()])) { + const vector = DynWinRtValue.createVector([value.toValue()], type) + const output = invokeCollectionReader(collectionVectorReader(type), vector, 6, [DynWinRtValue.u32(0)]) + t.is(entry.read(output.asStruct()), entry.expected) + output.release() + vector.release() + for (const producer of collectionProducerCases(type, [value.toValue()]).slice(1)) { t.throws(producer.create, undefined, entry.name) } } } }) -test('collection producers restrict large POD to ABI-compatible empty vectors', (t) => { +test('collection producers support empty and nonempty large POD vectors but not maps', (t) => { const cases = [ { name: 'Windows.Graphics.RectInt32', @@ -2236,19 +2237,18 @@ test('collection producers restrict large POD to ABI-compatible empty vectors', ] for (const entry of cases) { const type = DynWinRtType.structType(entry.name, entry.fields) - const emptySupported = process.arch === 'x64' || (process.arch === 'arm64' && entry.size > 16 && !entry.hfa) - if (emptySupported) { - const vector = DynWinRtValue.createVector([], type) - t.is(invokeCollectionReader(collectionVectorReader(type), vector, 7, []).toNumber(), 0) + for (const items of [[], [DynWinRtStruct.create(type).toValue()]]) { + const vector = DynWinRtValue.createVector(items, type) + t.is(invokeCollectionReader(collectionVectorReader(type), vector, 7, []).toNumber(), items.length) + if (items.length) { + const value = invokeCollectionReader(collectionVectorReader(type), vector, 6, [DynWinRtValue.u32(0)]) + t.false(value.isNull()) + value.release() + } vector.release() - } else { - t.throws(() => DynWinRtValue.createVector([], type)) - } - for (const producer of collectionProducerCases(type, []).slice(1)) { - t.throws(producer.create, undefined, producer.name) - } - for (const producer of collectionProducerCases(type, [DynWinRtStruct.create(type).toValue()])) { - t.throws(producer.create, undefined, producer.name) + for (const producer of collectionProducerCases(type, items).slice(1)) { + t.throws(producer.create, undefined, producer.name) + } } } }) diff --git a/bindings/py/README.md b/bindings/py/README.md index 05860619..b0e92853 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -120,21 +120,31 @@ complete set of closed collection IIDs before creating a native object. These limits apply to **producing** collections, including conversion of Python sequences/mappings, not to consuming collections returned by Windows. +**Phase one (#161), proposed for this release:** the following matrix describes +the proposed capability, subject to PR review, final integration, and platform +CI. POD vector support is independent of Classic COM/Win32 and does not expand +map admission. + | Element / key / value | x64 | ARM64 | i686 | |---|---|---|---| | Boolean, integers, Char16, enum, HRESULT | Supported | Supported | Up to 4 bytes; I64/U64 rejected | | HSTRING; owned nullable interface/object references | Supported | Supported | Supported | -| POD structs in populated vectors or maps | Sizes 1, 2, 4, 8 | Up to 8 bytes, non-HFA only | Up to 4 bytes | -| Additional POD structs in **empty vectors only** | Larger than 8 bytes | Larger than 16 bytes, non-HFA only | None | +| Validated POD structs in empty or populated vectors | Supported | Supported, including HFAs | Supported | +| POD struct map keys/values (unchanged) | Sizes 1, 2, 4, 8 | Up to 8 bytes, non-HFA only | Up to 4 bytes | | Top-level F32/F64/GUID; structs recursively containing HSTRING or references | Rejected, even empty | Rejected, even empty | Rejected, even empty | POD means a validated, reference-free native layout. HFA means an aggregate of one to four same-width floating-point values, including nested aggregates. -Thus `Point`/`Size` work on x64 but are rejected on ARM64 even when empty; -`PointInt32` works on x64 and ARM64. ARM64 also rejects empty `RectInt32`, -`Rect`, and `BasicGeoposition` vectors. `ManipulationDelta` (20 bytes, five floats, -non-HFA) supports empty -vectors on x64 and ARM64. Large map keys/values are rejected even for empty maps. +Examples include `Point`/`Size`, `PointInt32`, `RectInt32`, `Rect`, +`BasicGeoposition`, and nested PODs such as `ManipulationDelta` and +`ManipulationVelocities`; these are not a runtime whitelist. Empty vectors are +real, non-null, fully mutable collections. Large map keys/values and ARM64 HFA +map elements remain rejected even for empty maps. +Struct ABI entrypoints use cached libffi callbacks where the word fast path +does not apply. A process that prohibits executable callback allocation can +reject construction before publishing an object. +See the [POD vector architecture](../../docs/architecture/winrt-pod-vectors.md) +for layout, storage, callback lifetime, and remaining limitations. Structs and typed enums require exact type identity, not a matching byte size or shape. Scalars require the matching value variant, except U16 inputs for @@ -159,7 +169,9 @@ the same checks. The metadata-free Rust `create_value_vector`, `create_vector`, and `create_map` constructors require `unsafe`: callers must prove the native ABI, ownership, element types, and complete IID set themselves. The metadata-free `create_value_vector` retains packed-byte equality, including -padding, rather than metadata-directed field equality. +padding, rather than metadata-directed field equality. Its original restricted +word/empty-indirect ABI contract is unchanged; it does not gain checked POD +vector support. Unsupported layouts raise `RuntimeError`; HRESULT-backed type, range, or QueryInterface failures raise `OSError`. Complete native struct collection support is tracked in diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index 8a75574b..0788db28 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -901,7 +901,7 @@ def test_collection_producers_retain_direct_strings_and_nullable_references_with incompatible.release() -def test_collection_producers_enforce_architecture_specific_small_pod_boundary(): +def test_pod_vectors_work_without_broadening_architecture_specific_map_boundary(): is_x86 = sys.maxsize == 2**31 - 1 is_arm64 = sysconfig.get_platform() == "win-arm64" cases = [ @@ -921,8 +921,8 @@ def test_collection_producers_enforce_architecture_specific_small_pod_boundary() value = DynWinRTStruct.create(typ) getattr(value, setter)(index, expected) supported = not ((is_x86 and size > 4) or (is_arm64 and hfa)) - for create in _collection_producer_cases(typ, []): - if supported: + for producer_index, create in enumerate(_collection_producer_cases(typ, [])): + if producer_index == 0 or supported: assert not create().is_null() else: with pytest.raises(RuntimeError): @@ -935,14 +935,19 @@ def test_collection_producers_enforce_architecture_specific_small_pod_boundary() assert getattr(from_map.as_struct(), getter)(index) == expected assert key_lookup.to_number() == 0 else: - for create in _collection_producer_cases(typ, [value.to_value()]): + vector = DynWinRTValue.create_vector([value.to_value()], typ) + output = _invoke_collection_reader( + _collection_vector_reader(typ), vector, 6, [DynWinRTValue.from_u32(0)] + ) + assert getattr(output.as_struct(), getter)(index) == expected + output.release() + vector.release() + for create in _collection_producer_cases(typ, [value.to_value()])[1:]: with pytest.raises(RuntimeError): create() -def test_collection_producers_restrict_large_pod_to_abi_compatible_empty_vectors(): - is_x86 = sys.maxsize == 2**31 - 1 - is_arm64 = sysconfig.get_platform() == "win-arm64" +def test_collection_producers_support_large_pod_vectors_but_not_maps(): cases = [ ("Windows.Graphics.RectInt32", [DynWinRTType.i32_type()] * 4, False, 16), ("Windows.Foundation.Rect", [DynWinRTType.f32_type()] * 4, True, 16), @@ -957,22 +962,21 @@ def test_collection_producers_restrict_large_pod_to_abi_compatible_empty_vectors ] for name, fields, hfa, size in cases: typ = DynWinRTType.struct_type(name, fields) - empty_supported = not is_x86 and (not is_arm64 or (size > 16 and not hfa)) - if empty_supported: - vector = DynWinRTValue.create_vector([], typ) + for items in [[], [DynWinRTStruct.create(typ).to_value()]]: + vector = DynWinRTValue.create_vector(items, typ) assert _invoke_collection_reader( _collection_vector_reader(typ), vector, 7, [] - ).to_number() == 0 + ).to_number() == len(items) + if items: + output = _invoke_collection_reader( + _collection_vector_reader(typ), vector, 6, [DynWinRTValue.from_u32(0)] + ) + assert not output.is_null() + output.release() vector.release() - else: - with pytest.raises(RuntimeError): - DynWinRTValue.create_vector([], typ) - for create in _collection_producer_cases(typ, [])[1:]: - with pytest.raises(RuntimeError): - create() - for create in _collection_producer_cases(typ, [DynWinRTStruct.create(typ).to_value()]): - with pytest.raises(RuntimeError): - create() + for create in _collection_producer_cases(typ, items)[1:]: + with pytest.raises(RuntimeError): + create() def test_collection_producers_reject_floating_scalars_and_guids_even_when_empty(): diff --git a/crates/dynwinrt/src/collection_element.rs b/crates/dynwinrt/src/collection_element.rs index b61010af..31fedd69 100644 --- a/crates/dynwinrt/src/collection_element.rs +++ b/crates/dynwinrt/src/collection_element.rs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use std::sync::Arc; +use std::{alloc::Layout, sync::Arc}; use windows_core::{HSTRING, IUnknown, Interface}; use crate::{Error, Result, TypeHandle, TypeKind, WinRTValue}; @@ -12,11 +12,12 @@ pub(crate) enum CollectionStorage { HString, Object, EmptyOnly(usize), + Pod(Layout), } impl CollectionStorage { pub(crate) fn is_value_type(self) -> bool { - matches!(self, Self::Word(_) | Self::EmptyOnly(_)) + matches!(self, Self::Word(_) | Self::EmptyOnly(_) | Self::Pod(_)) } pub(crate) fn is_hstring(self) -> bool { @@ -30,6 +31,7 @@ impl CollectionStorage { pub(crate) fn element_size(self) -> usize { match self { Self::Word(size) | Self::EmptyOnly(size) => size, + Self::Pod(layout) => layout.size(), Self::HString | Self::Object => size_of::(), } } @@ -205,6 +207,7 @@ enum ScalarEqualityKind { U64, F32, F64, + Guid, } impl StructEqualityField { @@ -232,6 +235,7 @@ impl StructEqualityField { ScalarEqualityKind::F64 => { f64::from_ne_bytes(self.read(left)) == f64::from_ne_bytes(self.read(right)) } + ScalarEqualityKind::Guid => self.read::<16>(left) == self.read::<16>(right), } } } @@ -285,6 +289,7 @@ impl CollectionEquality { TypeKind::I64 | TypeKind::U64 => ScalarEqualityKind::U64, TypeKind::F32 => ScalarEqualityKind::F32, TypeKind::F64 => ScalarEqualityKind::F64, + TypeKind::Guid => ScalarEqualityKind::Guid, _ => return Err(unsupported()), }; if fields.len() >= size { @@ -295,12 +300,14 @@ impl CollectionEquality { } pub(crate) fn struct_words_equal(&self, left: usize, right: usize) -> Option { + self.struct_bytes_equal(&left.to_ne_bytes(), &right.to_ne_bytes()) + } + + pub(crate) fn struct_bytes_equal(&self, left: &[u8], right: &[u8]) -> Option { let Self::Struct(fields) = self else { return None; }; - let left = left.to_ne_bytes(); - let right = right.to_ne_bytes(); - Some(fields.iter().all(|field| field.equal(&left, &right))) + Some(fields.iter().all(|field| field.equal(left, right))) } } @@ -311,10 +318,40 @@ pub(crate) struct CollectionElementPlan { } impl CollectionElementPlan { - pub(crate) fn new(typ: &TypeHandle, allow_empty: bool) -> Result { + // Maps still use only the original word/reference ABI and storage. + pub(crate) fn for_map(typ: &TypeHandle) -> Result { + Self::new(typ, false) + } + + fn new(typ: &TypeHandle, allow_empty: bool) -> Result { Self::for_target(typ, allow_empty, CollectionTarget::current()) } + pub(crate) fn for_vector(typ: &TypeHandle) -> Result { + if !matches!(typ.kind(), TypeKind::Struct(_)) { + return Self::new(typ, false); + } + let target = CollectionTarget::current(); + let unsupported = || Error::UnsupportedCollectionElement(typ.kind()); + if target == CollectionTarget::Unsupported { + return Err(unsupported()); + } + let layout = pod_layout(typ, 0)?; + // Keep the existing single-word ABI fast path. All other checked PODs + // require a metadata-prepared callback, even when the vector is empty. + if aggregate_storage(target, layout.size, layout.homogeneous.is_some(), false).is_some() { + return Self::new(typ, false); + } + typ.table().try_closed_signature_string_kind(typ.kind())?; + let storage = + Layout::from_size_align(layout.size, layout.align).map_err(|_| unsupported())?; + Ok(Self { + typ: typ.clone(), + storage: CollectionStorage::Pod(storage), + equality: CollectionEquality::for_struct(typ, layout.size)?, + }) + } + fn for_target(typ: &TypeHandle, allow_empty: bool, target: CollectionTarget) -> Result { let unsupported = || Error::UnsupportedCollectionElement(typ.kind()); let storage = match typ.kind() { @@ -420,6 +457,11 @@ impl CollectionElementPlan { "the exact declared struct layout", )); } + if let CollectionStorage::Pod(layout) = self.storage { + return Ok(PreparedCollectionItem::Pod(unsafe { + OwnedPod::copy(layout, data.as_ptr()) + })); + } let mut word = 0usize; unsafe { std::ptr::copy_nonoverlapping( @@ -444,15 +486,18 @@ pub(crate) enum PreparedCollectionItem { Word(usize), HString(HSTRING), Object(Option), + Pod(OwnedPod), } impl PreparedCollectionItem { - /// Borrow the ABI word without transferring ownership. + /// Borrow the storage word without transferring ownership. POD words + /// address full value storage; they are not by-value native argument bits. pub(crate) fn as_raw(&self) -> usize { match self { Self::Word(word) => *word, Self::HString(value) => unsafe { std::mem::transmute_copy::(value) }, Self::Object(object) => object.as_ref().map_or(0, |object| object.as_raw() as usize), + Self::Pod(value) => value.ptr as usize, } } @@ -464,10 +509,48 @@ impl PreparedCollectionItem { raw as usize } Self::Object(object) => object.map_or(0, |object| object.into_raw() as usize), + Self::Pod(value) => value.into_raw(), + } + } +} + +pub(crate) struct OwnedPod { + ptr: *mut u8, + layout: Layout, +} + +impl OwnedPod { + /// `source` must hold one readable POD value with the validated layout. + pub(crate) unsafe fn copy(layout: Layout, source: *const u8) -> Self { + let ptr = unsafe { std::alloc::alloc(layout) }; + if ptr.is_null() { + std::alloc::handle_alloc_error(layout); + } + unsafe { std::ptr::copy_nonoverlapping(source, ptr, layout.size()) }; + Self { ptr, layout } + } + + pub(crate) fn into_raw(self) -> usize { + let raw = self.ptr as usize; + std::mem::forget(self); + raw + } + + /// `raw` must be an owned allocation previously detached with `into_raw`. + pub(crate) unsafe fn from_raw(layout: Layout, raw: usize) -> Self { + Self { + ptr: raw as *mut u8, + layout, } } } +impl Drop for OwnedPod { + fn drop(&mut self) { + unsafe { std::alloc::dealloc(self.ptr, self.layout) }; + } +} + #[cfg(test)] mod tests { use super::*; @@ -829,6 +912,78 @@ mod tests { ); } + #[test] + fn pod_vectors_reject_inexact_identity_before_preparing_storage() { + let table = MetadataTable::new(); + let other = MetadataTable::new(); + let expected = table.struct_type("Test.Large", &vec![table.f64_type(); 3]); + let good = WinRTValue::Struct(expected.default_value()); + for actual in [ + table.struct_type("Test.OtherLarge", &vec![table.f64_type(); 3]), + table.struct_type("Test.Smaller", &[table.f64_type()]), + other.struct_type("Test.Large", &vec![other.f64_type(); 3]), + ] { + assert!( + create_vector_from_values( + &[good.clone(), WinRTValue::Struct(actual.default_value())], + &expected, + table.vector_iids(&expected), + ) + .is_err() + ); + } + } + + #[test] + fn large_nested_pod_equality_compiles_fields_not_padding() { + let table = MetadataTable::new(); + let inner = table.struct_type("Test.PaddedInner", &[table.u8_type(), table.u32_type()]); + let outer = table.struct_type( + "Test.PaddedOuter", + &[table.u8_type(), inner, table.f64_type()], + ); + assert_eq!(outer.size_of(), 24); + let plan = CollectionElementPlan::for_vector(&outer).unwrap(); + let mut left = vec![0; outer.size_of()]; + left[0] = 7; + left[4] = 8; + left[8..12].copy_from_slice(&123u32.to_ne_bytes()); + left[16..24].copy_from_slice(&0.0f64.to_ne_bytes()); + let mut right = left.clone(); + for offset in [1, 2, 3, 5, 6, 7, 12, 13, 14, 15] { + right[offset] = 0xff; + } + right[16..24].copy_from_slice(&(-0.0f64).to_ne_bytes()); + assert_eq!(plan.equality.struct_bytes_equal(&left, &right), Some(true)); + for offset in [0, 4, 8] { + let mut different = right.clone(); + different[offset] ^= 1; + assert_eq!( + plan.equality.struct_bytes_equal(&left, &different), + Some(false) + ); + } + left[16..24].copy_from_slice(&f64::NAN.to_ne_bytes()); + right[16..24].copy_from_slice(&f64::NAN.to_ne_bytes()); + assert_eq!(plan.equality.struct_bytes_equal(&left, &right), Some(false)); + } + + #[test] + fn pod_guid_fields_do_not_admit_top_level_guids_or_map_aggregates() { + let table = MetadataTable::new(); + let typ = table.struct_type("Test.GuidRecord", &[table.u8_type(), table.guid_type()]); + let plan = CollectionElementPlan::for_vector(&typ).unwrap(); + assert_eq!(typ.size_of(), 20); + let left = vec![1; typ.size_of()]; + let mut right = left.clone(); + right[1..4].fill(0xff); + assert_eq!(plan.equality.struct_bytes_equal(&left, &right), Some(true)); + right[19] = 2; + assert_eq!(plan.equality.struct_bytes_equal(&left, &right), Some(false)); + assert!(CollectionElementPlan::for_vector(&table.guid_type()).is_err()); + assert!(CollectionElementPlan::for_map(&typ).is_err()); + } + #[test] fn checked_scalar_aliases_do_not_silently_narrow() { let table = MetadataTable::new(); diff --git a/crates/dynwinrt/src/map.rs b/crates/dynwinrt/src/map.rs index 41f719dc..8c088df9 100644 --- a/crates/dynwinrt/src/map.rs +++ b/crates/dynwinrt/src/map.rs @@ -602,8 +602,8 @@ pub fn create_map_from_values( value_type: &crate::TypeHandle, iids: MapIids, ) -> crate::Result { - let key_plan = CollectionElementPlan::new(key_type, false)?; - let value_plan = CollectionElementPlan::new(value_type, false)?; + let key_plan = CollectionElementPlan::for_map(key_type)?; + let value_plan = CollectionElementPlan::for_map(value_type)?; if !std::sync::Arc::ptr_eq(key_type.table(), value_type.table()) { return Err(crate::Error::InvalidCollectionValue( "map key and value types from the same metadata table", diff --git a/crates/dynwinrt/src/native_callback.rs b/crates/dynwinrt/src/native_callback.rs index d045062b..6a2df184 100644 --- a/crates/dynwinrt/src/native_callback.rs +++ b/crates/dynwinrt/src/native_callback.rs @@ -384,6 +384,56 @@ mod tests { assert_eq!(unsafe { callback(std::ptr::null_mut(), 27) }, HRESULT(27)); } + #[test] + fn pod_callback_panic_returns_hresult_and_allows_another_call() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use windows::Devices::Geolocation::BasicGeoposition; + + unsafe fn dispatch( + _slot: usize, + _signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, + ) { + let calls = unsafe { &**(*args).cast::<*const AtomicUsize>() }; + let value = unsafe { (*args.add(1)).cast::().read_unaligned() }; + assert_eq!(value.Latitude, 1.25); + assert_eq!(value.Longitude, -2.5); + assert_eq!(value.Altitude, 300.0); + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + panic!("POD callback failure"); + } + unsafe { result.cast::().write(0) }; + } + + let table = crate::MetadataTable::new(); + let typ = table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &vec![table.f64_type(); 3], + ); + let signature = CallbackSignature::hresult(vec![( + CallbackAbiType::NativeStruct(typ.signature_string(), typ.size_of()), + typ.libffi_type(), + )]); + let code = callback_code(13, signature.clone(), dispatch).unwrap(); + let callback: unsafe extern "system" fn(*mut c_void, BasicGeoposition) -> HRESULT = + unsafe { std::mem::transmute(code) }; + let calls = AtomicUsize::new(0); + let this = std::ptr::from_ref(&calls).cast_mut().cast(); + let value = BasicGeoposition { + Latitude: 1.25, + Longitude: -2.5, + Altitude: 300.0, + }; + assert_eq!(unsafe { callback(this, value) }, E_FAIL); + assert_eq!(calls.load(Ordering::SeqCst), 1); + drop(typ); + drop(table); + assert_eq!(callback_code(13, signature, dispatch).unwrap(), code); + assert_eq!(unsafe { callback(this, value) }, HRESULT(0)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + #[test] fn callback_cif_preparation_failure_is_returned() { let result = PreparedCallbackCif::new_with_abi( diff --git a/crates/dynwinrt/src/vector.rs b/crates/dynwinrt/src/vector.rs index 22c24b60..fe1bc1c7 100644 --- a/crates/dynwinrt/src/vector.rs +++ b/crates/dynwinrt/src/vector.rs @@ -10,20 +10,23 @@ use core::ffi::c_void; use std::collections::HashMap; use std::sync::{ - Mutex, + Arc, Mutex, atomic::{AtomicI64, Ordering}, }; use windows_core::{GUID, HRESULT, HSTRING, IUnknown, Interface}; use crate::collection_element::{ - CollectionElementPlan, CollectionEquality, CollectionStorage, PreparedCollectionItem, + CollectionElementPlan, CollectionEquality, CollectionStorage, OwnedPod, PreparedCollectionItem, }; +#[path = "vector_pod.rs"] +mod pod; use crate::com_helpers::{ E_BOUNDS, E_FAIL, E_NOTIMPL, IInspectableVtbl, S_OK, com_to_usize, com_usize_addref_out, com_usize_release, }; #[allow(unused_imports)] use crate::com_helpers::{dual_vtable_com, inspectable_stubs, lock_or, single_vtable_com}; +use pod::PodVectorVtables; // ====================================================================== // IIDs for collection PIIDs @@ -52,6 +55,10 @@ struct IterableVtbl { } /// IVector vtable: IInspectable + 12 methods +/// +/// By-value slots are typed for the word/reference fast path. POD tables replace +/// their code with libffi closures; those slots must be called with the native +/// element signature, not these erased Rust signatures. #[repr(C)] struct VectorVtbl { base: IInspectableVtbl, @@ -182,7 +189,9 @@ pub(crate) unsafe fn write_item_out( raw: usize, result: *mut *mut c_void, ) { - if storage.is_hstring() { + if let CollectionStorage::Pod(layout) = storage { + std::ptr::copy_nonoverlapping(raw as *const u8, result.cast::(), layout.size()); + } else if storage.is_hstring() { *result = clone_hstring_raw(raw) as *mut c_void; } else if storage.is_value_type() { let write_size = storage.element_size(); @@ -215,6 +224,9 @@ unsafe fn store_array_item( index: usize, ) -> usize { let slot = values.cast::().add(index * storage.array_stride()); + if matches!(storage, CollectionStorage::Pod(_)) { + return store_abi_item(storage, slot.cast_mut().cast()); + } let raw = if storage.is_value_type() { debug_assert!(!storage.is_empty_only()); let mut word = 0usize; @@ -247,7 +259,9 @@ unsafe fn release_hstring_raw(raw: usize) { } pub(crate) unsafe fn clone_stored_item(storage: CollectionStorage, raw: usize) -> usize { - if storage.is_hstring() { + if let CollectionStorage::Pod(layout) = storage { + OwnedPod::copy(layout, raw as *const u8).into_raw() + } else if storage.is_hstring() { clone_hstring_raw(raw) } else if storage.is_value_type() { raw @@ -256,8 +270,11 @@ pub(crate) unsafe fn clone_stored_item(storage: CollectionStorage, raw: usize) - } } +// POD input is an address supplied by libffi or a packed-array slot, not word bits. pub(crate) unsafe fn store_abi_item(storage: CollectionStorage, raw: *mut c_void) -> usize { - if storage.is_hstring() { + if let CollectionStorage::Pod(layout) = storage { + OwnedPod::copy(layout, raw.cast()).into_raw() + } else if storage.is_hstring() { clone_hstring_raw(raw as usize) } else if storage.is_value_type() { normalize_value_word(raw as usize, storage.element_size()) @@ -267,7 +284,9 @@ pub(crate) unsafe fn store_abi_item(storage: CollectionStorage, raw: *mut c_void } pub(crate) unsafe fn release_stored_item(storage: CollectionStorage, raw: usize) { - if storage.is_hstring() { + if let CollectionStorage::Pod(layout) = storage { + drop(OwnedPod::from_raw(layout, raw)); + } else if storage.is_hstring() { release_hstring_raw(raw); } else if !storage.is_value_type() { com_usize_release(raw); @@ -280,6 +299,14 @@ pub(crate) unsafe fn stored_items_equal( left: usize, right: usize, ) -> bool { + if let CollectionStorage::Pod(layout) = storage { + return equality + .struct_bytes_equal( + std::slice::from_raw_parts(left as *const u8, layout.size()), + std::slice::from_raw_parts(right as *const u8, layout.size()), + ) + .expect("POD storage requires field equality"); + } if let Some(equal) = equality.struct_words_equal(left, right) { return equal; } @@ -317,8 +344,9 @@ fn normalize_value_word(value: usize, elem_size: usize) -> usize { /// /// Stores items as raw `usize` values. For reference types (COM objects), /// each usize is a raw IUnknown pointer with manual AddRef/Release. -/// For value types (structs ≤ pointer size), each usize holds the struct -/// bytes directly — no refcounting needed. +/// For word-ABI value types, each usize holds the bytes directly. +/// Other checked PODs own aligned allocations addressed by +/// each word and use metadata-prepared by-value entrypoints. /// /// Implements four interfaces: /// - IIterable: First() for iteration @@ -338,6 +366,7 @@ struct SingleThreadedVector { storage: CollectionStorage, equality: CollectionEquality, iids: VectorIids, + pod_vtables: Option>, } unsafe impl Send for SingleThreadedVector {} @@ -450,6 +479,12 @@ impl SingleThreadedVector { unsafe { (self as *const Self as *const *const c_void).add(3) as *mut c_void } } + // Keep the owner alive for the whole mutation, including input retention, + // event callbacks and handler destruction, not just the notification borrow. + unsafe fn retain_mutation(this: *mut c_void) -> IUnknown { + IUnknown::from_raw_borrowed(&this).unwrap().clone() + } + fn notify_changed(&self, collection_change: i32, index: u32) -> HRESULT { let handlers: Vec = match self.handlers.lock() { Ok(handlers) => handlers.values().cloned().collect(), @@ -542,6 +577,7 @@ impl SingleThreadedVector { me.storage, me.equality.clone(), me.iids.clone(), + me.pod_vtables.clone(), ); // WinRT ABI: get_view must return an IVectorView pointer (second vtable), // not the identity/IIterable pointer (first vtable). @@ -556,6 +592,18 @@ impl SingleThreadedVector { index: *mut u32, found: *mut bool, ) -> HRESULT { + Self::index_of_impl(this, value, index, found) + } + + unsafe fn index_of_impl( + this: *mut c_void, + value: *mut c_void, + index: *mut u32, + found: *mut bool, + ) -> HRESULT { + if index.is_null() || found.is_null() { + return crate::com_helpers::E_POINTER; + } let me = Self::from_vector_ptr(this); // Empty-only aggregates lower to one pointer, but have no value storage. if me.storage.is_empty_only() { @@ -576,6 +624,11 @@ impl SingleThreadedVector { } unsafe extern "system" fn set_at(this: *mut c_void, index: u32, value: *mut c_void) -> HRESULT { + Self::set_at_impl(this, index, value) + } + + unsafe fn set_at_impl(this: *mut c_void, index: u32, value: *mut c_void) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); { let mut items = lock_or!(me.items, E_FAIL); @@ -597,6 +650,11 @@ impl SingleThreadedVector { index: u32, value: *mut c_void, ) -> HRESULT { + Self::insert_at_impl(this, index, value) + } + + unsafe fn insert_at_impl(this: *mut c_void, index: u32, value: *mut c_void) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); { let mut items = lock_or!(me.items, E_FAIL); @@ -613,6 +671,7 @@ impl SingleThreadedVector { } unsafe extern "system" fn remove_at(this: *mut c_void, index: u32) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); let removed = { let mut items = lock_or!(me.items, E_FAIL); @@ -626,13 +685,24 @@ impl SingleThreadedVector { } unsafe extern "system" fn append(this: *mut c_void, value: *mut c_void) -> HRESULT { + Self::append_impl(this, value) + } + + unsafe fn append_impl(this: *mut c_void, value: *mut c_void) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); if me.storage.is_empty_only() { return E_NOTIMPL; } let val = store_abi_item(me.storage, value); let index = { - let mut items = lock_or!(me.items, E_FAIL); + let mut items = match me.items.lock() { + Ok(items) => items, + Err(_) => { + release_stored_item(me.storage, val); + return E_FAIL; + } + }; let index = items.len() as u32; items.push(val); index @@ -641,6 +711,7 @@ impl SingleThreadedVector { } unsafe extern "system" fn remove_at_end(this: *mut c_void) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); let (removed, index) = { let mut items = lock_or!(me.items, E_FAIL); @@ -659,6 +730,7 @@ impl SingleThreadedVector { } unsafe extern "system" fn clear(this: *mut c_void) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); let old_items: Vec = lock_or!(me.items, E_FAIL).drain(..).collect(); for raw in old_items { @@ -692,6 +764,7 @@ impl SingleThreadedVector { count: u32, values: *const *mut c_void, ) -> HRESULT { + let _keep_alive = Self::retain_mutation(this); let me = Self::from_vector_ptr(this); if count > 0 && me.storage.is_empty_only() { return E_NOTIMPL; @@ -739,6 +812,18 @@ impl SingleThreadedVector { index: *mut u32, found: *mut bool, ) -> HRESULT { + Self::view_index_of_impl(this, value, index, found) + } + + unsafe fn view_index_of_impl( + this: *mut c_void, + value: *mut c_void, + index: *mut u32, + found: *mut bool, + ) -> HRESULT { + if index.is_null() || found.is_null() { + return crate::com_helpers::E_POINTER; + } let me = Self::from_view_ptr(this); if me.storage.is_empty_only() { return E_NOTIMPL; @@ -780,11 +865,13 @@ impl SingleThreadedVector { impl Drop for SingleThreadedVector { fn drop(&mut self) { - if let Ok(items) = self.items.lock() { - for &raw in items.iter() { - unsafe { - release_stored_item(self.storage, raw); - } + let items = self + .items + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for &raw in items.iter() { + unsafe { + release_stored_item(self.storage, raw); } } } @@ -803,6 +890,7 @@ struct SingleThreadedVectorView { storage: CollectionStorage, equality: CollectionEquality, iids: VectorIids, + pod_vtables: Option>, } unsafe impl Send for SingleThreadedVectorView {} @@ -845,15 +933,19 @@ impl SingleThreadedVectorView { storage: CollectionStorage, equality: CollectionEquality, iids: VectorIids, + pod_vtables: Option>, ) -> IUnknown { let view = Box::new(Self { vtable_iterable: &Self::ITERABLE_VTBL, - vtable_view: &Self::VIEW_VTBL, + vtable_view: pod_vtables + .as_ref() + .map_or(&Self::VIEW_VTBL, |plan| &plan.snapshot), ref_count: windows_core::imp::RefCount::new(1), items, storage, equality, iids, + pod_vtables, }); unsafe { IUnknown::from_raw(Box::into_raw(view) as *mut c_void) } } @@ -903,6 +995,18 @@ impl SingleThreadedVectorView { index: *mut u32, found: *mut bool, ) -> HRESULT { + Self::index_of_impl(this, value, index, found) + } + + unsafe fn index_of_impl( + this: *mut c_void, + value: *mut c_void, + index: *mut u32, + found: *mut bool, + ) -> HRESULT { + if index.is_null() || found.is_null() { + return crate::com_helpers::E_POINTER; + } let me = Self::from_view_ptr(this); if me.storage.is_empty_only() { return E_NOTIMPL; @@ -1067,8 +1171,9 @@ impl Drop for SingleThreadedIterator { /// Create an IVector COM object from WinRTValue items. /// /// Validates the complete IID set, exact element types, native argument ABI, -/// and ownership before publication. Only word-sized POD values are stored. -/// Some indirectly passed large POD types support empty-only vectors. +/// and ownership before publication. Checked POD structs use aligned owned +/// storage and metadata-prepared native entrypoints when they do not fit the +/// word ABI. Structs with owned fields and incomplete layouts are rejected. /// Admitted struct fields compare by value, ignoring padding; floating fields /// use numerical equality, including equal signed zeros and unequal NaNs. pub fn create_vector_from_values( @@ -1076,12 +1181,17 @@ pub fn create_vector_from_values( element_type: &crate::TypeHandle, iids: VectorIids, ) -> crate::Result { - let plan = CollectionElementPlan::new(element_type, items.is_empty())?; + let plan = CollectionElementPlan::for_vector(element_type)?; if iids != element_type.table().vector_iids(element_type) { return Err(crate::Error::InvalidCollectionValue( "collection IIDs matching the declared element type", )); } + let pod_vtables = if matches!(plan.storage, CollectionStorage::Pod(_)) { + Some(PodVectorVtables::for_type(element_type)?) + } else { + None + }; let prepared = items .iter() .map(|item| plan.prepare(item)) @@ -1090,7 +1200,13 @@ pub fn create_vector_from_values( .into_iter() .map(PreparedCollectionItem::into_raw) .collect(); - Ok(new_vector(packed, plan.storage, plan.equality, iids)) + Ok(new_vector( + packed, + plan.storage, + plan.equality, + iids, + pod_vtables, + )) } /// Create an IVector COM object from a Vec of IUnknown items (reference types). @@ -1113,6 +1229,7 @@ pub unsafe fn create_vector(items: Vec, iids: VectorIids) -> IUnknown CollectionStorage::Object, CollectionEquality::Storage, iids, + None, ) } @@ -1158,7 +1275,7 @@ pub unsafe fn create_value_vector( val }) .collect(); - new_vector(packed, storage, CollectionEquality::Storage, iids) + new_vector(packed, storage, CollectionEquality::Storage, iids, None) } fn new_vector( @@ -1166,11 +1283,16 @@ fn new_vector( storage: CollectionStorage, equality: CollectionEquality, iids: VectorIids, + pod_vtables: Option>, ) -> IUnknown { let vector = Box::new(SingleThreadedVector { vtable_iterable: &SingleThreadedVector::ITERABLE_VTBL, - vtable_vector: &SingleThreadedVector::VECTOR_VTBL, - vtable_view: &SingleThreadedVector::VIEW_VTBL, + vtable_vector: pod_vtables + .as_ref() + .map_or(&SingleThreadedVector::VECTOR_VTBL, |plan| &plan.vector), + vtable_view: pod_vtables + .as_ref() + .map_or(&SingleThreadedVector::VIEW_VTBL, |plan| &plan.live), vtable_observable: &SingleThreadedVector::OBSERVABLE_VTBL, ref_count: windows_core::imp::RefCount::new(1), items: Mutex::new(items), @@ -1179,6 +1301,7 @@ fn new_vector( storage, equality, iids, + pod_vtables, }); unsafe { IUnknown::from_raw(Box::into_raw(vector) as *mut c_void) } } @@ -1509,7 +1632,7 @@ mod tests { } #[test] - fn test_nonempty_large_struct_vector_remains_unsupported() { + fn test_nonempty_large_struct_vector() { let table = MetadataTable::new(); let rect = table.struct_type( "Windows.Graphics.RectInt32", @@ -1523,12 +1646,14 @@ mod tests { let iids = table.vector_iids(&rect); let item = crate::WinRTValue::Struct(rect.default_value()); - assert!(matches!( - create_vector_from_values(&[item], &rect, iids), - Err(crate::Error::UnsupportedCollectionElement( - crate::TypeKind::Struct(_) - )) - )); + let object = create_vector_from_values(&[item], &rect, iids).unwrap(); + let vector: windows_collections::IVector = + object.cast().unwrap(); + assert_eq!(vector.Size().unwrap(), 1); + assert_eq!( + vector.GetAt(0).unwrap(), + windows::Graphics::RectInt32::default() + ); } #[test] diff --git a/crates/dynwinrt/src/vector_abi_tests.rs b/crates/dynwinrt/src/vector_abi_tests.rs index 5c937c12..701cf7cc 100644 --- a/crates/dynwinrt/src/vector_abi_tests.rs +++ b/crates/dynwinrt/src/vector_abi_tests.rs @@ -6,7 +6,7 @@ use crate::{MetadataTable, TypeHandle, WinRTValue}; use windows::Devices::Geolocation::BasicGeoposition; use windows::Foundation::{Point, Rect, Size}; use windows::Graphics::{PointInt32, RectInt32}; -use windows::UI::Input::ManipulationDelta; +use windows::UI::Input::{ManipulationDelta, ManipulationVelocities}; use windows_collections::{IVector, IVectorView}; macro_rules! exercise_vector { @@ -19,7 +19,36 @@ macro_rules! exercise_vector { .unwrap(); let vector: IVector<$native> = object.cast().unwrap(); let live: IVectorView<$native> = object.cast().unwrap(); + let iterable: windows_collections::IIterable<$native> = object.cast().unwrap(); + let observable: windows::Foundation::Collections::IObservableVector<$native> = + object.cast().unwrap(); + for identity in [ + vector.cast::().unwrap(), + live.cast::().unwrap(), + iterable.cast::().unwrap(), + observable.cast::().unwrap(), + ] { + assert_eq!(identity.as_raw(), object.as_raw()); + } + drop(iterable); + drop(observable); let snapshot = vector.GetView().unwrap(); + let observations = Arc::new(Mutex::new(Vec::new())); + let recording = observations.clone(); + let observable: windows::Foundation::Collections::IObservableVector<$native> = + object.cast().unwrap(); + let handler = windows::Foundation::Collections::VectorChangedEventHandler::<$native>::new( + move |_sender, args| { + let args = args.as_ref().unwrap(); + recording + .lock() + .unwrap() + .push((args.CollectionChange()?.0, args.Index()?)); + Ok(()) + }, + ); + observable.VectorChanged(&handler).unwrap(); + drop(observable); assert_eq!(vector.GetAt(0).unwrap(), values[0]); let mut index = u32::MAX; assert!(vector.IndexOf(values[0], &mut index).unwrap()); @@ -40,71 +69,85 @@ macro_rules! exercise_vector { assert_eq!(&output[..3], &values); assert_eq!(output[3], values[2]); let iterator = vector.First().unwrap(); + assert!(iterator.HasCurrent().unwrap()); + assert_eq!(iterator.Current().unwrap(), values[0]); + assert!(iterator.MoveNext().unwrap()); + assert_eq!(iterator.Current().unwrap(), values[1]); vector.Clear().unwrap(); - assert_eq!(iterator.GetMany(&mut output[..3]).unwrap(), 3); - assert_eq!(&output[..3], &values); + drop(vector); + drop(live); + drop(object); + assert_eq!(iterator.GetMany(&mut output[..3]).unwrap(), 2); + assert_eq!(&output[..2], &values[1..]); + assert_eq!(output[3], values[2]); + assert!(!iterator.HasCurrent().unwrap()); + assert!(!iterator.MoveNext().unwrap()); + assert_eq!(iterator.Current().unwrap_err().code(), E_BOUNDS); + assert_eq!(snapshot.GetAt(0).unwrap(), values[0]); + assert_eq!(snapshot.First().unwrap().Current().unwrap(), values[0]); + assert_eq!( + *observations.lock().unwrap(), + vec![ + (COLLECTION_CHANGE_ITEM_INSERTED, 1), + (COLLECTION_CHANGE_ITEM_CHANGED, 0), + (COLLECTION_CHANGE_ITEM_INSERTED, 1), + (COLLECTION_CHANGE_RESET, 0), + (COLLECTION_CHANGE_RESET, 0), + ] + ); }}; } macro_rules! exercise_empty { - ($native:ty, $element:expr, $value:expr, $supported:expr) => {{ + ($native:ty, $element:expr, $value:expr) => {{ let element = $element; assert_eq!(element.size_of(), size_of::<$native>()); - let result = - create_vector_from_values(&[], &element, element.table().vector_iids(&element)); - assert!( - create_vector_from_values( - &[WinRTValue::Struct(element.default_value())], - &element, - element.table().vector_iids(&element), - ) - .is_err() - ); - if $supported { - let object = result.unwrap(); - let vector: IVector<$native> = object.cast().unwrap(); - let live: IVectorView<$native> = object.cast().unwrap(); - let snapshot = vector.GetView().unwrap(); - let value: $native = $value; - let mut index = 123; - assert_eq!( - vector.IndexOf(value, &mut index).unwrap_err().code(), - E_NOTIMPL - ); - assert_eq!(index, 123); - for view in [live, snapshot] { - assert_eq!( - view.IndexOf(value, &mut index).unwrap_err().code(), - E_NOTIMPL - ); - assert_eq!(index, 123); - let mut out = [value; 2]; - assert_eq!(view.GetMany(0, &mut out).unwrap(), 0); - assert_eq!(out, [value; 2]); - } - assert_eq!(vector.Append(value).unwrap_err().code(), E_NOTIMPL); - assert_eq!(vector.SetAt(0, value).unwrap_err().code(), E_BOUNDS); - assert_eq!(vector.InsertAt(0, value).unwrap_err().code(), E_NOTIMPL); - assert_eq!(vector.InsertAt(1, value).unwrap_err().code(), E_BOUNDS); - assert_eq!(vector.ReplaceAll(&[value]).unwrap_err().code(), E_NOTIMPL); - vector.ReplaceAll(&[]).unwrap(); - assert_eq!(vector.Size().unwrap(), 0); + let object = + create_vector_from_values(&[], &element, element.table().vector_iids(&element)) + .unwrap(); + let vector: IVector<$native> = object.cast().unwrap(); + let live: IVectorView<$native> = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + let value: $native = $value; + let mut index = 123; + assert!(!vector.IndexOf(value, &mut index).unwrap()); + assert_eq!(index, 0); + for view in [&live, &snapshot] { + assert!(!view.IndexOf(value, &mut index).unwrap()); + assert_eq!(index, 0); let mut out = [value; 2]; - assert_eq!(vector.GetMany(0, &mut out).unwrap(), 0); - assert_eq!(out, [value; 2]); - assert_eq!(vector.GetAt(0).unwrap_err().code(), E_BOUNDS); - let iterator = vector.First().unwrap(); - assert!(!iterator.HasCurrent().unwrap()); - assert_eq!(iterator.GetMany(&mut out).unwrap(), 0); + assert_eq!(view.GetMany(0, &mut out).unwrap(), 0); assert_eq!(out, [value; 2]); - assert_eq!(iterator.Current().unwrap_err().code(), E_BOUNDS); - vector.Clear().unwrap(); - } else { - assert!(matches!( - result, - Err(crate::Error::UnsupportedCollectionElement(_)) - )); } + assert_eq!(vector.SetAt(0, value).unwrap_err().code(), E_BOUNDS); + assert_eq!(vector.InsertAt(1, value).unwrap_err().code(), E_BOUNDS); + assert_eq!(vector.RemoveAt(0).unwrap_err().code(), E_BOUNDS); + assert_eq!(vector.RemoveAtEnd().unwrap_err().code(), E_BOUNDS); + assert_eq!(vector.GetAt(0).unwrap_err().code(), E_BOUNDS); + let iterator = vector.First().unwrap(); + assert!(!iterator.HasCurrent().unwrap()); + let mut out = [value; 2]; + assert_eq!(iterator.GetMany(&mut out).unwrap(), 0); + assert_eq!(out, [value; 2]); + assert_eq!(iterator.Current().unwrap_err().code(), E_BOUNDS); + assert!(!iterator.MoveNext().unwrap()); + vector.Append(value).unwrap(); + vector.InsertAt(0, value).unwrap(); + vector.SetAt(1, value).unwrap(); + assert_eq!(vector.Size().unwrap(), 2); + assert_eq!(live.GetAt(1).unwrap(), value); + assert_eq!(snapshot.Size().unwrap(), 0); + assert!(vector.IndexOf(value, &mut index).unwrap()); + assert_eq!(index, 0); + vector.RemoveAt(0).unwrap(); + vector.RemoveAtEnd().unwrap(); + vector.ReplaceAll(&[value]).unwrap(); + assert_eq!(vector.GetAt(0).unwrap(), value); + vector.ReplaceAll(&[]).unwrap(); + assert_eq!(vector.Size().unwrap(), 0); + assert_eq!(vector.GetMany(0, &mut out).unwrap(), 0); + assert_eq!(out, [value; 2]); + vector.Clear().unwrap(); }}; } @@ -218,65 +261,51 @@ fn typed_point_size_and_integer_pair_boundaries() { data.set_field(0, 1.0f32); data.set_field(1, 2.0f32); let item = WinRTValue::Struct(data); - if cfg!(target_arch = "x86_64") { - if element == &point { - exercise_vector!( - Point, - element.clone(), - item, - [ - Point { X: 1.0, Y: 2.0 }, - Point { X: 3.0, Y: 4.0 }, - Point { X: 5.0, Y: 6.0 } - ] - ); - } else { - exercise_vector!( - Size, - element.clone(), - item, - [ - Size { - Width: 1.0, - Height: 2.0 - }, - Size { - Width: 3.0, - Height: 4.0 - }, - Size { - Width: 5.0, - Height: 6.0 - } - ] - ); - } + if element == &point { + exercise_vector!( + Point, + element.clone(), + item, + [ + Point { X: 1.0, Y: 2.0 }, + Point { X: 3.0, Y: 4.0 }, + Point { X: 5.0, Y: 6.0 } + ] + ); } else { - for values in [vec![], vec![item]] { - assert!( - create_vector_from_values(&values, element, table.vector_iids(element)) - .is_err() - ); - } + exercise_vector!( + Size, + element.clone(), + item, + [ + Size { + Width: 1.0, + Height: 2.0 + }, + Size { + Width: 3.0, + Height: 4.0 + }, + Size { + Width: 5.0, + Height: 6.0 + } + ] + ); } } - if cfg!(target_pointer_width = "64") { - exercise_vector!( - PointInt32, - point_int.clone(), - pair(&point_int, 1, 2), - [ - PointInt32 { X: 1, Y: 2 }, - PointInt32 { X: 3, Y: 4 }, - PointInt32 { X: 5, Y: 6 } - ] - ); - } else { - assert!(create_vector_from_values(&[], &point_int, table.vector_iids(&point_int)).is_err()); - } + exercise_vector!( + PointInt32, + point_int.clone(), + pair(&point_int, 1, 2), + [ + PointInt32 { X: 1, Y: 2 }, + PointInt32 { X: 3, Y: 4 }, + PointInt32 { X: 5, Y: 6 } + ] + ); } -#[cfg(target_arch = "x86_64")] fn point_value(typ: &TypeHandle, point: Point) -> WinRTValue { let mut value = typ.default_value(); value.set_field(0, point.X); @@ -284,7 +313,6 @@ fn point_value(typ: &TypeHandle, point: Point) -> WinRTValue { WinRTValue::Struct(value) } -#[cfg(target_arch = "x86_64")] #[test] fn struct_equality_point_signed_zero_matches_all_views() { let table = MetadataTable::new(); @@ -322,7 +350,6 @@ fn struct_equality_point_signed_zero_matches_all_views() { } } -#[cfg(target_arch = "x86_64")] #[test] fn struct_equality_point_nan_never_matches_even_identical_bits() { let table = MetadataTable::new(); @@ -370,7 +397,6 @@ fn struct_equality_point_nan_never_matches_even_identical_bits() { } } -#[cfg(target_arch = "x86_64")] #[test] fn struct_equality_survives_mutation_snapshots_and_metadata_drop() { let (object, weak) = { @@ -416,6 +442,265 @@ fn struct_equality_survives_mutation_snapshots_and_metadata_drop() { assert_eq!(snapshot.GetAt(0).unwrap().X.to_bits(), 0); } +fn native_value(typ: &TypeHandle, value: &T) -> WinRTValue { + assert_eq!(typ.size_of(), size_of::()); + assert_eq!(typ.align_of(), align_of::()); + WinRTValue::Struct(unsafe { + crate::ValueTypeData::from_borrowed_abi(typ, std::ptr::from_ref(value).cast()) + }) +} + +#[test] +fn typed_nonempty_pod_vectors_use_one_generic_plan() { + let table = MetadataTable::new(); + let rect = table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]); + let values = [ + RectInt32 { + X: -1, + Y: 2, + Width: 300, + Height: 40, + }, + RectInt32 { + X: 50, + Y: -6, + Width: 70, + Height: 800, + }, + RectInt32 { + X: 9, + Y: 10, + Width: 11, + Height: 12, + }, + ]; + exercise_vector!( + RectInt32, + rect.clone(), + native_value(&rect, &values[0]), + values + ); + let position = table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &vec![table.f64_type(); 3], + ); + let values = [ + BasicGeoposition { + Latitude: 1.25, + Longitude: -2.5, + Altitude: 300.0, + }, + BasicGeoposition { + Latitude: -4.5, + Longitude: 5.25, + Altitude: -60.0, + }, + BasicGeoposition { + Latitude: 7.75, + Longitude: 8.25, + Altitude: 900.0, + }, + ]; + exercise_vector!( + BasicGeoposition, + position.clone(), + native_value(&position, &values[0]), + values + ); + let point = table.struct_type("Windows.Foundation.Point", &vec![table.f32_type(); 2]); + let delta = table.struct_type( + "Windows.UI.Input.ManipulationDelta", + &[ + point.clone(), + table.f32_type(), + table.f32_type(), + table.f32_type(), + ], + ); + let values = [1.0f32, -2.0, 30.0].map(|x| ManipulationDelta { + Translation: Point { X: x, Y: x + 1.0 }, + Scale: x + 2.0, + Rotation: x + 3.0, + Expansion: x + 4.0, + }); + exercise_vector!( + ManipulationDelta, + delta.clone(), + native_value(&delta, &values[0]), + values + ); + let velocities = table.struct_type( + "Windows.UI.Input.ManipulationVelocities", + &[point, table.f32_type(), table.f32_type()], + ); + let values = [1.5f32, -20.25, 300.75].map(|x| ManipulationVelocities { + Linear: Point { X: x, Y: x + 1.0 }, + Angular: x + 2.0, + Expansion: x + 3.0, + }); + exercise_vector!( + ManipulationVelocities, + velocities.clone(), + native_value(&velocities, &values[0]), + values + ); +} + +#[test] +fn pod_f64_equality_ignores_zero_sign_and_never_matches_nan() { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &vec![table.f64_type(); 3], + ); + for latitude in [0.0f64, -0.0, f64::from_bits(0x7ff8_0000_0000_0001)] { + let value = BasicGeoposition { + Latitude: latitude, + Longitude: 2.0, + Altitude: 3.0, + }; + let object = + create_vector_from_values(&[native_value(&typ, &value)], &typ, table.vector_iids(&typ)) + .unwrap(); + let vector: IVector = object.cast().unwrap(); + let live: IVectorView = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + for query in [ + value, + BasicGeoposition { + Latitude: -latitude, + ..value + }, + ] { + let mut index = u32::MAX; + assert_eq!( + vector.IndexOf(query, &mut index).unwrap(), + !latitude.is_nan() + ); + assert_eq!(index, 0); + for view in [&live, &snapshot] { + assert_eq!(view.IndexOf(query, &mut index).unwrap(), !latitude.is_nan()); + assert_eq!(index, 0); + } + } + assert_eq!( + vector.GetAt(0).unwrap().Latitude.to_bits(), + latitude.to_bits() + ); + } +} + +#[test] +fn pod_observable_notifications_allow_reentrant_mutation_and_final_release() { + use std::sync::atomic::AtomicUsize; + use windows::Foundation::Collections::{ + CollectionChange, IObservableVector, VectorChangedEventHandler, + }; + + let table = MetadataTable::new(); + let typ = table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]); + let object = create_vector_from_values(&[], &typ, table.vector_iids(&typ)).unwrap(); + let vector: IVector = object.cast().unwrap(); + let observable: IObservableVector = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let released = Arc::new(AtomicUsize::new(0)); + let owned_raw = Arc::new(AtomicUsize::new(0)); + let token = Arc::new(AtomicI64::new(0)); + let changed = Arc::new(Mutex::new(Vec::new())); + let recording = changed.clone(); + let observer = VectorChangedEventHandler::::new(move |sender, args| { + let sender = sender.as_ref().unwrap(); + let args = args.as_ref().unwrap(); + recording + .lock() + .unwrap() + .push((args.CollectionChange()?, args.Index()?)); + assert!(sender.cast::>()?.Size()? > 0); + Ok(()) + }); + observable.VectorChanged(&observer).unwrap(); + let callback_calls = calls.clone(); + let callback_raw = owned_raw.clone(); + let callback_released = released.clone(); + let callback_token = token.clone(); + let item = RectInt32 { + X: -1, + Y: 2, + Width: 3, + Height: 4, + }; + let handler = VectorChangedEventHandler::::new(move |sender, _args| { + callback_calls.fetch_add(1, Ordering::SeqCst); + let sender = sender.as_ref().unwrap(); + sender.RemoveVectorChanged(callback_token.load(Ordering::SeqCst))?; + let vector = sender.cast::>()?; + vector.Append(item)?; + assert_eq!(vector.GetAt(1)?, item); + drop(vector); + let raw = callback_raw.swap(0, Ordering::SeqCst); + assert_ne!(raw, 0); + // Release the original caller's only reference while its ABI entrypoint + // and all remaining handler invocations are still active. + unsafe { drop(IVector::::from_raw(raw as *mut c_void)) }; + callback_released.fetch_add(1, Ordering::SeqCst); + assert_eq!(sender.cast::>()?.Size()?, 2); + Ok(()) + }); + token.store( + observable.VectorChanged(&handler).unwrap(), + Ordering::SeqCst, + ); + drop(handler); + drop(observer); + drop(observable); + drop(object); + let append = vector.vtable().Append; + let raw = vector.into_raw(); + owned_raw.store(raw as usize, Ordering::SeqCst); + unsafe { append(raw, item).ok().unwrap() }; + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(released.load(Ordering::SeqCst), 1); + assert_eq!(Arc::strong_count(&owned_raw), 1); + assert_eq!(Arc::strong_count(&calls), 1); + let changes = changed.lock().unwrap(); + assert_eq!(changes.len(), 2); + assert!(changes.contains(&(CollectionChange::ItemInserted, 0))); + assert!(changes.contains(&(CollectionChange::ItemInserted, 1))); + assert_eq!(snapshot.Size().unwrap(), 0); +} + +#[test] +fn pod_lookup_validates_required_output_cells_with_the_sdk_signature() { + let table = MetadataTable::new(); + let typ = table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]); + let object = create_vector_from_values(&[], &typ, table.vector_iids(&typ)).unwrap(); + let vector: IVector = object.cast().unwrap(); + let live: IVectorView = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + let value = RectInt32::default(); + let mut index = u32::MAX; + let mut found = true; + unsafe { + assert_eq!( + (vector.vtable().IndexOf)(vector.as_raw(), value, std::ptr::null_mut(), &mut found), + crate::com_helpers::E_POINTER + ); + assert_eq!( + (vector.vtable().IndexOf)(vector.as_raw(), value, &mut index, std::ptr::null_mut()), + crate::com_helpers::E_POINTER + ); + for view in [live, snapshot] { + assert_eq!( + (view.vtable().IndexOf)(view.as_raw(), value, std::ptr::null_mut(), &mut found), + crate::com_helpers::E_POINTER + ); + } + } + assert_eq!(index, u32::MAX); + assert!(found); +} + #[cfg(target_arch = "x86_64")] #[test] fn struct_equality_point_map_duplicate_constructor_agrees_with_mutators_and_snapshot() { @@ -554,7 +839,7 @@ fn struct_equality_raw_constructor_preserves_packed_byte_comparison() { } #[test] -fn typed_empty_only_uses_indirect_argument_abi() { +fn typed_empty_pod_vectors_publish_complete_native_abis() { let table = MetadataTable::new(); let rect_int = table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]); exercise_empty!( @@ -565,8 +850,7 @@ fn typed_empty_only_uses_indirect_argument_abi() { Y: 2, Width: 3, Height: 4 - }, - cfg!(target_arch = "x86_64") + } ); let rect = table.struct_type("Windows.Foundation.Rect", &vec![table.f32_type(); 4]); exercise_empty!( @@ -577,8 +861,7 @@ fn typed_empty_only_uses_indirect_argument_abi() { Y: 2.0, Width: 3.0, Height: 4.0 - }, - cfg!(target_arch = "x86_64") + } ); let position = table.struct_type( "Windows.Devices.Geolocation.BasicGeoposition", @@ -591,8 +874,7 @@ fn typed_empty_only_uses_indirect_argument_abi() { Latitude: 1.0, Longitude: 2.0, Altitude: 3.0 - }, - cfg!(target_arch = "x86_64") + } ); let point = table.struct_type( "Windows.Foundation.Point", @@ -610,28 +892,32 @@ fn typed_empty_only_uses_indirect_argument_abi() { Scale: 3.0, Rotation: 4.0, Expansion: 5.0 - }, - cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) + } ); } #[test] fn typed_constructors_reject_mismatched_iids_before_publication() { let table = MetadataTable::new(); - let element = table.i32_type(); - let expected = table.vector_iids(&element); - for field in 0..6 { - let mut iids = expected.clone(); - let fields = [ - &mut iids.iterable, - &mut iids.vector, - &mut iids.vector_view, - &mut iids.observable_vector, - &mut iids.vector_changed_handler, - &mut iids.iterator, - ]; - *fields.into_iter().nth(field).unwrap() = GUID::zeroed(); - assert!(create_vector_from_values(&[], &element, iids).is_err()); + for element in [ + table.i32_type(), + table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]), + table.struct_type("Windows.Foundation.Point", &vec![table.f32_type(); 2]), + ] { + let expected = table.vector_iids(&element); + for field in 0..6 { + let mut iids = expected.clone(); + let fields = [ + &mut iids.iterable, + &mut iids.vector, + &mut iids.vector_view, + &mut iids.observable_vector, + &mut iids.vector_changed_handler, + &mut iids.iterator, + ]; + *fields.into_iter().nth(field).unwrap() = GUID::zeroed(); + assert!(create_vector_from_values(&[], &element, iids).is_err()); + } } } diff --git a/crates/dynwinrt/src/vector_bulk_tests.rs b/crates/dynwinrt/src/vector_bulk_tests.rs index 308e5156..a4918f22 100644 --- a/crates/dynwinrt/src/vector_bulk_tests.rs +++ b/crates/dynwinrt/src/vector_bulk_tests.rs @@ -18,7 +18,7 @@ fn check_output( invoke: impl FnOnce(*mut *mut c_void, *mut u32) -> HRESULT, ) { const PREFIX: usize = 16; - let pattern = usize::from_ne_bytes([0xa5; size_of::()]); + let pattern = u64::from_ne_bytes([0xa5; size_of::()]); let mut storage = [pattern; 32]; let bytes = unsafe { std::slice::from_raw_parts_mut(storage.as_mut_ptr().cast::(), size_of_val(&storage)) @@ -82,8 +82,13 @@ fn check_value_bulk(element: TypeHandle, items: Vec>) { } TypeKind::Struct(_) => { let mut data = element.default_value(); - data.set_field(0, bytes[0]); - data.set_field(1, bytes[1]); + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + data.as_mut_ptr(), + bytes.len(), + ) + }; WinRTValue::Struct(data) } kind => panic!("unexpected bulk test type: {kind:?}"), @@ -151,7 +156,7 @@ fn check_value_bulk(element: TypeHandle, items: Vec>) { } let replacement = items.iter().rev().flatten().copied().collect::>(); - let mut source = [usize::from_ne_bytes([0xa5; size_of::()]); 32]; + let mut source = [u64::from_ne_bytes([0xa5; size_of::()]); 32]; let source_bytes = unsafe { std::slice::from_raw_parts_mut(source.as_mut_ptr().cast::(), size_of_val(&source)) }; @@ -217,6 +222,76 @@ fn value_bulk_operations_use_element_size() { } } +#[test] +fn pod_bulk_operations_preserve_layout_alignment_and_guards() { + let table = MetadataTable::new(); + let point = table.struct_type("Windows.Foundation.Point", &vec![table.f32_type(); 2]); + for (typ, values) in [ + ( + point.clone(), + vec![1.0f32, 2.0, 3.0] + .into_iter() + .map(|x| [x.to_ne_bytes(), (x + 1.0).to_ne_bytes()].concat()) + .collect::>(), + ), + ( + table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]), + [1i32, -2, 300] + .into_iter() + .map(|x| { + [x, x + 1, x + 2, x + 3] + .into_iter() + .flat_map(i32::to_ne_bytes) + .collect() + }) + .collect(), + ), + ( + table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &vec![table.f64_type(); 3], + ), + [1.25f64, -2.5, 300.75] + .into_iter() + .map(|x| { + [x, x + 1.0, x + 2.0] + .into_iter() + .flat_map(f64::to_ne_bytes) + .collect() + }) + .collect(), + ), + ( + table.struct_type("Test.NestedHfa", &[point.clone(), point]), + [1.25f32, -2.5, 300.75] + .into_iter() + .map(|x| { + [x, x + 1.0, x + 2.0, x + 3.0] + .into_iter() + .flat_map(f32::to_ne_bytes) + .collect() + }) + .collect(), + ), + ] { + check_value_bulk(typ, values); + } + let inner = table.struct_type("Test.BulkInner", &[table.u8_type(), table.f64_type()]); + let padded = table.struct_type("Test.BulkPadded", &[inner, table.u8_type()]); + assert_eq!(padded.size_of(), 24); + let values = [1, 2, 3] + .into_iter() + .map(|byte| { + let mut bytes = vec![0xa5; 24]; + bytes[0] = byte; + bytes[8..16].copy_from_slice(&(byte as f64).to_ne_bytes()); + bytes[16] = byte + 1; + bytes + }) + .collect(); + check_value_bulk(padded, values); +} + #[test] fn enum_bulk_operations_match_typed_winrt_abi() { use windows_future::AsyncStatus; diff --git a/crates/dynwinrt/src/vector_pod.rs b/crates/dynwinrt/src/vector_pod.rs new file mode 100644 index 00000000..d17546d8 --- /dev/null +++ b/crates/dynwinrt/src/vector_pod.rs @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::sync::LazyLock; + +use libffi::middle::Type; + +use super::*; +use crate::{ + TypeHandle, + native_callback::{CallbackAbiType, CallbackSignature, callback_code}, +}; + +pub(super) struct PodVectorVtables { + pub vector: VectorVtbl, + pub live: VectorViewVtbl, + pub snapshot: VectorViewVtbl, +} + +// Tables contain only immutable function pointers. The shared callback cache +// owns the executable pages and prepared CIF/type graphs for the process lifetime. +unsafe impl Send for PodVectorVtables {} +unsafe impl Sync for PodVectorVtables {} + +static TABLES: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn preparation_error(message: String) -> crate::Error { + windows_core::Error::new(E_FAIL, &message).into() +} + +impl PodVectorVtables { + // Called only after CollectionElementPlan validates the complete POD layout. + pub fn for_type(typ: &TypeHandle) -> crate::Result> { + let signature = typ.signature_string(); + let mut tables = TABLES + .lock() + .map_err(|_| preparation_error("POD vector vtable cache is poisoned".into()))?; + if let Some(tables) = tables.get(&signature) { + return Ok(tables.clone()); + } + let element = ( + CallbackAbiType::NativeStruct(signature.clone(), typ.size_of()), + typ.libffi_type(), + ); + let pointer = || (CallbackAbiType::Pointer, Type::pointer()); + let index = || (CallbackAbiType::U32, Type::u32()); + let lookup = CallbackSignature::hresult(vec![element.clone(), pointer(), pointer()]); + let indexed = CallbackSignature::hresult(vec![index(), element.clone()]); + let append = CallbackSignature::hresult(vec![element]); + let vector = VectorVtbl { + index_of: unsafe { + std::mem::transmute( + callback_code(9, lookup.clone(), vector_dispatch).map_err(preparation_error)?, + ) + }, + set_at: unsafe { + std::mem::transmute( + callback_code(10, indexed.clone(), vector_dispatch) + .map_err(preparation_error)?, + ) + }, + insert_at: unsafe { + std::mem::transmute( + callback_code(11, indexed, vector_dispatch).map_err(preparation_error)?, + ) + }, + append: unsafe { + std::mem::transmute( + callback_code(13, append, vector_dispatch).map_err(preparation_error)?, + ) + }, + ..SingleThreadedVector::VECTOR_VTBL + }; + let live = VectorViewVtbl { + index_of: unsafe { + std::mem::transmute( + callback_code(8, lookup.clone(), live_dispatch).map_err(preparation_error)?, + ) + }, + ..SingleThreadedVector::VIEW_VTBL + }; + let snapshot = VectorViewVtbl { + index_of: unsafe { + std::mem::transmute( + callback_code(8, lookup, snapshot_dispatch).map_err(preparation_error)?, + ) + }, + ..SingleThreadedVectorView::VIEW_VTBL + }; + let plan = Arc::new(Self { + vector, + live, + snapshot, + }); + tables.insert(signature, plan.clone()); + Ok(plan) + } +} + +unsafe fn argument(args: *const *const c_void, index: usize) -> T { + unsafe { (*args.add(index)).cast::().read_unaligned() } +} + +unsafe fn vector_dispatch( + slot: usize, + _signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, +) { + let this = unsafe { argument(args, 0) }; + // libffi presents by-value aggregates as addresses of complete native + // storage, independently of register/HFA/indirect/stack classification. + let hr = unsafe { + match slot { + 9 => SingleThreadedVector::index_of_impl( + this, + (*args.add(1)).cast_mut(), + argument(args, 2), + argument(args, 3), + ), + 10 => SingleThreadedVector::set_at_impl( + this, + argument(args, 1), + (*args.add(2)).cast_mut(), + ), + 11 => SingleThreadedVector::insert_at_impl( + this, + argument(args, 1), + (*args.add(2)).cast_mut(), + ), + 13 => SingleThreadedVector::append_impl(this, (*args.add(1)).cast_mut()), + _ => unreachable!("unpublished POD vector slot"), + } + }; + unsafe { result.cast::().write(hr.0) }; +} + +unsafe fn live_dispatch( + _slot: usize, + _signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, +) { + let hr = unsafe { + SingleThreadedVector::view_index_of_impl( + argument(args, 0), + (*args.add(1)).cast_mut(), + argument(args, 2), + argument(args, 3), + ) + }; + unsafe { result.cast::().write(hr.0) }; +} + +unsafe fn snapshot_dispatch( + _slot: usize, + _signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, +) { + let hr = unsafe { + SingleThreadedVectorView::index_of_impl( + argument(args, 0), + (*args.add(1)).cast_mut(), + argument(args, 2), + argument(args, 3), + ) + }; + unsafe { result.cast::().write(hr.0) }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn immutable_pod_tables_are_cached_without_retaining_metadata() { + fn assert_send_sync() {} + assert_send_sync::(); + let table = crate::MetadataTable::new(); + let typ = table.struct_type("Test.CachedPod", &vec![table.f64_type(); 3]); + let plan = PodVectorVtables::for_type(&typ).unwrap(); + let second = PodVectorVtables::for_type(&typ).unwrap(); + assert!(Arc::ptr_eq(&plan, &second)); + let other = crate::MetadataTable::new(); + let equivalent = other.struct_type("Test.CachedPod", &vec![other.f64_type(); 3]); + assert!(Arc::ptr_eq( + &plan, + &PodVectorVtables::for_type(&equivalent).unwrap() + )); + let weak = Arc::downgrade(&table); + drop(typ); + drop(table); + assert!(weak.upgrade().is_none()); + } + + #[test] + fn concurrent_pod_preparation_shares_one_immutable_table() { + const WORKERS: usize = 8; + let barrier = Arc::new(std::sync::Barrier::new(WORKERS)); + let workers = (0..WORKERS) + .map(|_| { + let barrier = barrier.clone(); + std::thread::spawn(move || { + let table = crate::MetadataTable::new(); + let weak = Arc::downgrade(&table); + let typ = table.struct_type("Test.ConcurrentPod", &vec![table.f64_type(); 3]); + barrier.wait(); + let plan = PodVectorVtables::for_type(&typ).unwrap(); + drop(typ); + drop(table); + assert!(weak.upgrade().is_none()); + plan + }) + }) + .collect::>(); + let plans = workers + .into_iter() + .map(|worker| worker.join().unwrap()) + .collect::>(); + for plan in &plans[1..] { + assert!(Arc::ptr_eq(&plans[0], plan)); + } + } + + #[test] + fn same_size_pods_with_different_field_abis_do_not_share_callbacks() { + let floating = crate::MetadataTable::new(); + let floating_type = floating.struct_type("Test.SameSizePod", &vec![floating.f64_type(); 2]); + let integer = crate::MetadataTable::new(); + let integer_type = integer.struct_type("Test.SameSizePod", &vec![integer.u64_type(); 2]); + assert_eq!(floating_type.size_of(), integer_type.size_of()); + assert_eq!(floating_type.align_of(), integer_type.align_of()); + let floating = PodVectorVtables::for_type(&floating_type).unwrap(); + let integer = PodVectorVtables::for_type(&integer_type).unwrap(); + assert!(!Arc::ptr_eq(&floating, &integer)); + assert_ne!( + floating.vector.append as usize, + integer.vector.append as usize + ); + assert_ne!( + floating.live.index_of as usize, + integer.live.index_of as usize + ); + assert_ne!( + floating.snapshot.index_of as usize, + integer.snapshot.index_of as usize + ); + } +} diff --git a/docs/architecture/winrt-pod-vectors.md b/docs/architecture/winrt-pod-vectors.md new file mode 100644 index 00000000..2b67462d --- /dev/null +++ b/docs/architecture/winrt-pod-vectors.md @@ -0,0 +1,139 @@ +# Checked WinRT POD vectors + +**Phase one of #161 (proposed).** This change implements checked POD +**vectors**, not the whole struct-collection issue. Inclusion in the current +release remains subject to PR review, final integration, and platform CI. +Maps, owning structs, and unrelated top-level scalar expansion remain out of +scope. No permanent feature flag is introduced. + +## Validation and ABI planning + +The existing generated JavaScript array and Python sequence conversions call +`create_vector_from_values`. Neither projection infers an ABI from a language +value's shape. `CollectionElementPlan::for_vector` validates the supplied +WinRT metadata first: + +- a closed type signature and the exact six collection IIDs; +- recursively complete, nonempty, naturally aligned POD layouts, with checked + field offsets, total size, alignment, and nesting depth; +- scalar/enum/GUID or recursively POD struct fields, with no HSTRING, + interface, reference, array, or other owning/unknown fields; and +- exact `TypeHandle` identity for every supplied struct, not just its size. + +The existing integer-word, HSTRING, reference, and single-word aggregate +paths remain in use where their native ABI is valid. Char16/U16 and enum/I32 +aliases and reference QueryInterface/ownership/null behavior are unchanged. +Maps still call the original word-ABI planner; extending vector admission +does not expose a new map key/value ABI. + +Other validated structs use the metadata's recursive libffi type graph. +`vector_pod.rs` prepares `IndexOf`, `SetAt`, `InsertAt`, and `Append`, plus +both live and snapshot view `IndexOf`, through the existing private +`native_callback` cache. The system calling convention is used, including +stdcall on i686. libffi, not a hand-written register/stack adapter, handles +ARM64 HFAs, multi-register aggregates, indirect x64 aggregates, and i686 +stack values. Dispatch receives addresses of complete argument values. + +All other published slots have element-independent pointer/scalar argument +ABIs: `GetAt`, `Current`, `GetMany`, `ReplaceAll`, view/iterator creation, +size, removal, clearing, and observable registration reuse the existing +entrypoints. These slots copy the full planned element size, not a machine +word. Empty input is never permission to publish an incompatible by-value +slot or substitute a null reference. + +The table cache is keyed by the closed recursive signature; natural WinRT +layout is deterministic for that signature on the running target. It owns +immutable tables only, not metadata handles or objects. The shared callback +cache owns prepared CIFs, type graphs, contexts and executable pages for the +process lifetime. Failure to prepare/allocate executable callbacks returns +an error before any COM object is published. + +This is WinRT-local planning. It does not change COM/Win32 registries, +contracts, generated output, or public subpaths. See +[Classic COM support](classic-com-support.md) for the shared private ABI +boundary. + +## Storage, equality, and lifetime + +New POD storage consists of individually owned allocations with the validated +native `Layout`. The existing vector's word slots address those allocations; +they are never treated as inline words or COM references. Prepared inputs have +RAII owners until all inputs are validated. Mutation copies borrowed native +values into owned storage; removal and destruction deallocate with the same +layout. No closure or vtable is allocated per element. + +This deliberately favors ownership correctness over allocation throughput. +Each non-word POD element has its own allocation, and snapshots and iterators +copy their elements; this is not a zero-copy projection. Contiguous aligned +storage should be considered separately if measured collection workloads +justify it. Callback caches grow with distinct closed type signatures, not +element or vector counts. Eviction would require proving that no native caller +can still enter a cached callback, so it is not part of this phase. + +Vector, live view, and observable views share canonical identity and storage. +`GetView` and `First` retain the existing independent snapshot semantics. +Snapshots and iterators own their copied POD allocations and remain usable +after the source vector or metadata table is released. Pointer-only iterator +slots need no dynamic table; their copied layout is sufficient for output and +cleanup. Vector/snapshot objects retain their immutable table plans. + +`GetMany` and `ReplaceAll` use native packed element strides and caller +capacity/count contracts, not the internal pointer stride. Field equality +recurses over metadata leaves and ignores internal/tail padding. Floating +leaves compare numerically: signed zeros match and NaNs never match. Stored +field bits are not normalized. + +Mutation retains its owner for the entire entrypoint, including input +retention, callbacks, and handler destruction, and unlocks before notifying +observers. Unsubscribe, reentrant mutation, and releasing the caller's last +reference cannot destroy the sender while its state is borrowed. +Dynamic dispatch runs inside the centralized panic boundary; its Rust method +bodies do not cross a second non-unwinding FFI boundary. + +The metadata-free unsafe constructors retain their original requirements and +packed-byte comparison. In particular, `create_value_vector` still only +permits its documented single-word or empty-indirect subset. This work does +not silently make those APIs checked or broaden their native ABI. + +## Coverage and limits + +SDK-typed tests cover `Point`, `Size`, `PointInt32`, `RectInt32`, +`BasicGeoposition`, nested `ManipulationDelta`, and nested-HFA +`ManipulationVelocities`. They cover all vector/view/iterator slots, identity, +bulk buffer guards, snapshots, metadata lifetime, numerical equality, +observable reentrancy/final release, and unchanged map/rejection boundaries. +Additional metadata-layout tests cover nested padding. These names are test +examples, not a production allowlist. + +The Build workflow's required `test-pod-vectors` matrix executes optimized +collection, map, element-plan, and callback regressions for all three targets: +x64 on `windows-latest`, i686 under WOW64 on an x64 host, and native ARM64 on +`windows-11-arm`. An explicit target and host-architecture guard prevent +emulated x64/i686 execution on ARM64 from being counted as those native-host +lanes. This is execution, not `--no-run` cross-compilation, and requires no +optional WinAppSDK, AI, or UI inputs. It gates `test`, `ci-success`, and final +artifact assembly while leaving production E2E consumers parallel. +The same selectors include concurrent cache preparation, distinct same-size +field ABIs, and a native POD callback that panics, returns an HRESULT failure, +and remains callable after its source metadata is dropped. + +The standard E2E specs exercise generated Point arrays/lists through +`InkStrokeBuilder.CreateStroke` and BasicGeoposition arrays/lists through all +three `Geopath` factory and `GeoboundingBox.TryCompute` overloads. An empty +`TryCompute` input returns native null; that is distinct from the non-null +empty input collection. An empty producer does not imply that every native +consumer accepts an empty collection (for example, `Geopath.Create`). + +`tests/e2e/pod_hint_specs.json` is an additional, explicitly selected metadata +fixture. Generate `Microsoft.Windows.AI.Imaging.ImageObjectExtractorHint` +from the configured AI Imaging WinMD, with Windows SDK metadata as a reference, +then run the existing `ts_runner.ts` / `py_runner.py` with that specs file and +the isolated generated directory. It exercises the generated RectInt32 vector +factory and all its mutation/bulk operations without activating the hint, AI, +WinAppSDK bootstrap, UI, or a model. It does **not** qualify AI hint execution. + +Native ARM64 and Windows x64/i686 emulation are separate evidence categories; +emulated results are not native x64/i686 hardware qualification. Generated +consumers must run against the matching locally built runtime. Local validation +does not replace PR review, final integration, or platform CI for release +admission. diff --git a/docs/status/TODO.md b/docs/status/TODO.md index 6f9e80f3..a5015b92 100644 --- a/docs/status/TODO.md +++ b/docs/status/TODO.md @@ -11,12 +11,17 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy - [ ] **Complete native struct collection producers** ([#161](https://github.com/microsoft/dynwinrt/issues/161)). Typed vector/map factories validate exact types, native layout, recursive ownership, and - complete closed IID sets. Non-POD structs, top-level F32/F64/GUID, ARM64 - HFAs, and i686 values wider than 4 bytes are rejected even when empty. - Large POD structs remain empty-vector-only where the ABI passes them - indirectly: x64 >8 bytes; ARM64 non-HFA >16 bytes. Maps reject large - keys/values even when empty. Full native struct ABI/ownership support is - future work; see the [JS](../../bindings/js/README.md#creating-winrt-collections) + complete closed IID sets. **Phase one, proposed for this release:** + checked POD vectors have layout-aware storage and cached ABI-correct + callbacks on ARM64, x64, and i686, including HFAs, larger and nested + PODs. Release admission remains subject to PR review, final integration, + and platform CI. Empty vectors have the same complete ABI as populated ones. + See the [architecture](../architecture/winrt-pod-vectors.md). + Non-POD structs, top-level F32/F64/GUID and i686 top-level I64/U64 remain + rejected even when empty. Maps retain their original word-sized + admission and reject unsupported keys/values even when empty. Full + collection ABI/ownership support remains future work; see the + [JS](../../bindings/js/README.md#creating-winrt-collections) and [Python](../../bindings/py/README.md#creating-winrt-collections) matrices. These are producer limits, not restrictions on OS-returned collections. Metadata-free Rust `create_value_vector`, `create_vector`, and `create_map` diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py index e0eeada5..4146436b 100644 --- a/eng/ci/test_ci.py +++ b/eng/ci/test_ci.py @@ -21,7 +21,7 @@ WORKFLOW = yaml.safe_load((ROOT / ".github" / "workflows" / "build.yml").read_text(encoding="utf-8")) JOBS = WORKFLOW["jobs"] HEAVY = { - "test-rust", "build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", + "test-rust", "test-pod-vectors", "build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", "build-arm64", "e2e-runtime", "e2e-native", } GATES = {"test", "e2e", "dynwinrt", "dynwinrt-codegen", "ci-success"} @@ -210,11 +210,79 @@ def test_graph_and_parallel_consumers(self): for producer in ("build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", "build-arm64"): self.assertEqual(set(JOBS[producer]["needs"]), {"format", "changes"}) for consumer in ("e2e-runtime", "e2e-native"): - self.assertTrue(self.ancestors(consumer).isdisjoint({"test", "test-rust", "build-arm64"})) + self.assertTrue(self.ancestors(consumer).isdisjoint({ + "test", "test-rust", "test-pod-vectors", "build-arm64", + })) for final in ("dynwinrt", "dynwinrt-codegen"): - self.assertTrue({"test", "e2e", "build-arm64"} <= self.ancestors(final)) + self.assertTrue({"test", "test-pod-vectors", "e2e", "build-arm64"} <= self.ancestors(final)) self.assertEqual(set(JOBS["ci-success"]["needs"]), set(JOBS) - {"ci-success"}) + def test_pod_vectors_execute_every_supported_target_on_native_hosts(self): + job = JOBS["test-pod-vectors"] + self.assertEqual(set(job["needs"]), {"changes", "format"}) + self.assertEqual(job["runs-on"], "${{ matrix.runner }}") + self.assertFalse(job["strategy"]["fail-fast"]) + targets = job["strategy"]["matrix"]["include"] + self.assertEqual(len(targets), 3) + self.assertEqual( + {item["target"]: (item["runner"], item["host"]) for item in targets}, + { + "x86_64-pc-windows-msvc": ("windows-latest", "X64"), + "i686-pc-windows-msvc": ("windows-latest", "X64"), + "aarch64-pc-windows-msvc": ("windows-11-arm", "Arm64"), + }, + ) + self.assertEqual(job["env"]["POD_TEST_TARGET"], "${{ matrix.target }}") + self.assertEqual(job["env"]["POD_TEST_HOST"], "${{ matrix.host }}") + toolchain, = [ + step for step in job["steps"] + if step.get("uses") == "dtolnay/rust-toolchain@stable" + ] + self.assertEqual(toolchain["with"]["targets"], "${{ matrix.target }}") + execution, = [ + step for step in job["steps"] + if step.get("name") == "Execute optimized collection and callback regressions" + ] + self.assertEqual(execution["shell"], "pwsh") + self.assertIn("$PSNativeCommandUseErrorActionPreference = $true", execution["run"]) + self.assertIn( + "cargo test --locked --release -p dynwinrt --target $env:POD_TEST_TARGET --lib --", + execution["run"], + ) + for selected in ("vector::", "collection_element::", "native_callback::", "map::"): + self.assertIn(selected, execution["run"]) + self.assertNotIn("--no-run", execution["run"]) + for config in (job, *job["steps"]): + self.assertNotIn("continue-on-error", config) + self.assertIn("test-pod-vectors", JOBS["test"]["needs"]) + + def test_pod_host_guard_rejects_an_emulated_host(self): + guard, = [ + step for step in JOBS["test-pod-vectors"]["steps"] + if step.get("name") == "Verify native POD test host" + ] + self.assertEqual(guard["shell"], "pwsh") + with tempfile.TemporaryDirectory(prefix="dynwinrt-ci-pod-host-") as directory: + step = Path(directory) / "guard.ps1" + step.write_text(guard["run"], encoding="utf-8") + harness = Path(directory) / "check.ps1" + harness.write_text( + "param([string]$Step)\n" + "$ErrorActionPreference = 'Stop'\n" + "$hostArchitecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()\n" + "$env:POD_TEST_TARGET = 'test-target'\n" + "foreach ($expected in @($true, $false)) {\n" + " $env:POD_TEST_HOST = if ($expected) { $hostArchitecture } " + "elseif ($hostArchitecture -eq 'Arm64') { 'X64' } else { 'Arm64' }\n" + " $passed = $true\n" + " try { & $Step } catch { $passed = $false }\n" + " if ($passed -ne $expected) { throw 'Native POD host guard admitted the wrong host' }\n" + "}\n", + encoding="utf-8", + ) + result = powershell(harness, step) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_current_run_artifacts_and_no_consumer_rebuilds(self): uploads = {} for job, config in JOBS.items(): diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index 709bf04f..464d9ce0 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -200,6 +200,27 @@ { "kind": "ibuffer_copied_roundtrip", "member": "copied_bytes" } ] }, + { + "id": "pod_point_collection_input", + "namespace": "Windows.UI.Input.Inking", + "class": "InkStrokeBuilder", + "langs": ["py", "ts"], + "instantiate": { "kind": "activate" }, + "checks": [ + { "kind": "pod_point_input", "member": "create_stroke" } + ] + }, + { + "id": "pod_geoposition_collection_input", + "namespace": "Windows.Devices.Geolocation", + "class": "Geopath", + "extra_classes": ["GeoboundingBox"], + "langs": ["py", "ts"], + "instantiate": { "kind": "none" }, + "checks": [ + { "kind": "pod_geoposition_input", "member": "create" } + ] + }, { "id": "struct_point_roundtrip", "namespace": "Windows.Foundation", diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index fc2ecf9e..84ca8f10 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -68,6 +68,9 @@ "interface_cast", "projection_identity", "struct_roundtrip", + "pod_point_input", + "pod_geoposition_input", + "pod_rect_vector_factory", "array_roundtrip", "static_string_length", "static_expect_error", diff --git a/tests/e2e/pod_hint_specs.json b/tests/e2e/pod_hint_specs.json new file mode 100644 index 00000000..904ae9be --- /dev/null +++ b/tests/e2e/pod_hint_specs.json @@ -0,0 +1,15 @@ +{ + "$schema": "./e2e_specs.schema.json", + "specs": [ + { + "id": "pod_hint_rect_vector_preparation", + "namespace": "Microsoft.Windows.AI.Imaging", + "class": "ImageObjectExtractorHint", + "langs": ["py", "ts"], + "instantiate": { "kind": "none" }, + "checks": [ + { "kind": "pod_rect_vector_factory", "member": "include_rects" } + ] + } + ] +} diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index 9bde333f..5df7ce7f 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1623,6 +1623,120 @@ def block_on_sta(): else: cr['pass'] = True + elif kind == 'pod_point_input': + from dynwinrt import release_projected + + point_type = generated_type(pkg_name, 'Point') + points = [point_type(x=1.25, y=2.5), point_type(x=3.5, y=4.75)] + owned = [] + try: + stroke = obj.create_stroke(points) + assert stroke is not None + owned.append(stroke) + view = stroke.get_ink_points() + assert view is not None + owned.append(view) + output = list(view) + owned.extend(output) + assert [point.position for point in output] == points + cr['pass'] = True + finally: + for value in reversed(owned): + release_projected(value) + + elif kind == 'pod_geoposition_input': + from dynwinrt import release_projected + + position_type = generated_type(pkg_name, 'BasicGeoposition') + positions = [ + position_type(latitude=10, longitude=20, altitude=30), + position_type(latitude=11, longitude=21, altitude=40), + ] + box_type = generated_type(pkg_name, 'GeoboundingBox') + altitude_type = generated_type(pkg_name, 'AltitudeReferenceSystem') + shape_type = generated_type(pkg_name, 'GeoshapeType') + reference = altitude_type.Ellipsoid + factories = [cls.create, cls.create_with_altitude_reference, + cls.create_with_altitude_reference_and_spatial_reference] + computations = [box_type.try_compute, box_type.try_compute_with_altitude_reference, + box_type.try_compute_with_altitude_reference_and_spatial_reference] + for factory, compute, args in zip( + factories, computations, [(), (reference,), (reference, 4326)] + ): + owned = [] + try: + path = factory(positions, *args) + owned.append(path) + view = path.positions + assert view is not None + owned.append(view) + assert list(view) == positions + assert view.get_many(1, positions) == positions[1:] + assert view.index_of(positions[1]) == (1, True) + constructed = cls(positions, *args) + owned.append(constructed) + constructed_view = constructed.positions + assert constructed_view is not None + owned.append(constructed_view) + assert list(constructed_view) == positions + expected_altitude = reference if args else altitude_type.Terrain + for candidate in (path, constructed): + assert candidate.geoshape_type == shape_type.Geopath + assert candidate.spatial_reference_id == 4326 + assert candidate.altitude_reference_system == expected_altitude + bounds = compute(positions, *args) + assert bounds is not None + owned.append(bounds) + assert bounds.northwest_corner == position_type(latitude=11, longitude=20, altitude=40) + assert bounds.southeast_corner == position_type(latitude=10, longitude=21, altitude=30) + assert bounds.min_altitude == 30 + assert bounds.max_altitude == 40 + rebuilt = box_type(bounds.northwest_corner, bounds.southeast_corner, *args) + owned.append(rebuilt) + assert rebuilt.northwest_corner == bounds.northwest_corner + assert rebuilt.southeast_corner == bounds.southeast_corner + assert rebuilt.center == bounds.center + for candidate in (bounds, rebuilt): + assert candidate.geoshape_type == shape_type.GeoboundingBox + assert candidate.spatial_reference_id == 4326 + assert candidate.altitude_reference_system == expected_altitude + assert compute([], *args) is None + finally: + for value in reversed(owned): + release_projected(value) + cr['pass'] = True + + elif kind == 'pod_rect_vector_factory': + from dynwinrt import release_projected + + vector_type = generated_type(pkg_name, 'IVector_RectInt32') + rect_type = generated_type(pkg_name, 'RectInt32') + rects = [rect_type(x=-1, y=2, width=30, height=40), + rect_type(x=50, y=-6, width=70, height=80)] + # Exercise only the generated hint input, never AI activation. + for initial in [[], rects]: + vector = vector_type.create(initial) + snapshot = vector.get_view() + assert snapshot is not None + try: + assert not vector._obj.is_null() + assert list(vector) == initial + vector.append(rects[0]) + vector.set_at(0, rects[1]) + vector.insert_at(0, rects[0]) + assert vector.index_of(rects[1]) == (1, True) + vector.replace_all(rects) + assert vector.get_many(0, [rects[0]] * 3) == rects + assert list(snapshot) == initial + vector.remove_at(0) + vector.remove_at_end() + assert vector.size == 0 + vector.clear() + finally: + release_projected(vector) + release_projected(snapshot) + cr['pass'] = True + elif kind == 'nested_struct_runtime': from typing import get_type_hints diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index 8d173384..ef591ad4 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -703,6 +703,115 @@ async function runCheck( obj.setToNow(); cr.pass = true; } + } else if (kind === "pod_point_input") { + const mod = generatedRoot(generatedDir); + const points = [ + { x: 1.25, y: 2.5 }, + { x: 3.5, y: 4.75 }, + ]; + const owned: any[] = []; + try { + const stroke = obj.createStroke(points); + assert.ok(stroke); + owned.push(stroke); + const view = stroke.getInkPoints(); + assert.ok(view); + owned.push(view); + const output = view.toArray(); + owned.push(...output); + assert.deepEqual( + output.map((point: any) => point.position), + points, + ); + cr.pass = true; + } finally { + for (const value of owned.reverse()) mod.releaseProjected(value); + } + } else if (kind === "pod_geoposition_input") { + const mod = generatedRoot(generatedDir); + const positions = [ + { latitude: 10, longitude: 20, altitude: 30 }, + { latitude: 11, longitude: 21, altitude: 40 }, + ]; + const reference = mod.AltitudeReferenceSystem.Ellipsoid; + for (const args of [[], [reference], [reference, 4326]]) { + const owned: any[] = []; + try { + const path = + args.length === 0 + ? cls.create(positions) + : args.length === 1 + ? cls.createWithAltitudeReference(positions, ...args) + : cls.createWithAltitudeReferenceAndSpatialReference( + positions, + ...args, + ); + owned.push(path); + const view = path.positions; + assert.ok(view); + owned.push(view); + assert.deepEqual(view.toArray(), positions); + const bounds = mod.GeoboundingBox.tryCompute(positions, ...args); + assert.ok(bounds); + owned.push(bounds); + assert.deepEqual(bounds.northwestCorner, { + latitude: 11, + longitude: 20, + altitude: 40, + }); + assert.deepEqual(bounds.southeastCorner, { + latitude: 10, + longitude: 21, + altitude: 30, + }); + assert.equal(bounds.minAltitude, 30); + assert.equal(bounds.maxAltitude, 40); + assert.equal(mod.GeoboundingBox.tryCompute([], ...args), null); + } finally { + for (const value of owned.reverse()) mod.releaseProjected(value); + } + } + cr.pass = true; + } else if (kind === "pod_rect_vector_factory") { + const mod = generatedRoot(generatedDir); + const names = Object.keys(mod).filter((name) => + name.startsWith("IVector_WindowsGraphicsRectInt32_"), + ); + assert.equal(names.length, 1); + const Vector = mod[names[0]]; + const rects = [ + { x: -1, y: 2, width: 30, height: 40 }, + { x: 50, y: -6, width: 70, height: 80 }, + ]; + // Only prepare the metadata-generated hint input. Do not activate AI, + // bootstrap WinAppSDK, load a model, or invoke the hint factory. + for (const initial of [[], rects]) { + const vector = Vector.create(initial); + const snapshot = vector.getView(); + assert.ok(snapshot); + try { + assert.equal(vector._obj.isNull(), false); + assert.deepEqual(vector.toArray(), initial); + vector.append(rects[0]); + vector.setAt(0, rects[1]); + vector.insertAt(0, rects[0]); + assert.equal(vector.indexOf(rects[1]), 1); + vector.replaceAll(rects); + assert.deepEqual( + vector.getMany(0, [rects[0], rects[0], rects[0]]), + rects, + ); + assert.deepEqual(snapshot.toArray(), initial); + vector.removeAt(0); + vector.removeAtEnd(); + assert.equal(vector.size, 0); + vector.clear(); + } finally { + mod.releaseProjected(vector); + mod.releaseProjected(snapshot); + } + } + cr.pass = true; } else if (kind === "nested_struct_runtime") { const mod = generatedRoot(generatedDir); const DirectXPixelFormat = await importClass(