diff --git a/bindings/js/README.md b/bindings/js/README.md index 200597a0..2aeb7add 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -350,6 +350,46 @@ the standard `VectorChanged` collection-change notifications. Generated `IObservableVector` projections expose `asVector()` for mutating collection properties, and codegen emits the paired `IVector` binding automatically. +### Creating WinRT collections + +`DynWinRtValue.createVector(items, elementType)` and +`DynWinRtValue.createMap(keys, values, keyType, valueType)` keep their public +signatures. They validate element identity, native layout, ownership, and the +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. + +| 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 | +| 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. + +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 +Char16, I32 inputs for enum/HRESULT, and range-checked I32 inputs for +I8/U8/Char16. For example, I32 `255` is accepted for U8; I32 `257` throws instead +of wrapping. Reference inputs are retained and queried for the declared IID; +an incompatible interface throws, while a null reference remains null. + +The JavaScript helpers use validated typed core factories. Rust callers can use +the safe `create_vector_from_values` / `create_map_from_values` factories for +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. +Complete native struct collection support is tracked in +[microsoft/dynwinrt#161](https://github.com/microsoft/dynwinrt/issues/161). + ## Platform support - **Windows 10 / 11** — x64 and arm64 native binaries shipped via `napi-rs` prebuilds diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index fc53f56f..f9e7b134 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -1918,12 +1918,376 @@ 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() t.notThrows(() => vector.cast(vectorIid)) }) +function collectionProducerCases(elementType: DynWinRtType, items: DynWinRtValue[]) { + const indexes = items.map((_, index) => DynWinRtValue.i32(index)) + return [ + { name: 'vector', create: () => DynWinRtValue.createVector(items, elementType) }, + { + name: 'map key', + create: () => DynWinRtValue.createMap(items, indexes, elementType, DynWinRtType.i32()), + }, + { + name: 'map value', + create: () => DynWinRtValue.createMap(indexes, items, DynWinRtType.i32(), elementType), + }, + ] +} + +function collectionVectorReader(elementType: DynWinRtType) { + const iid = DynWinRtType.parameterized(WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), [elementType]).iid() + return DynWinRtType.registerInterface(`CollectionBoundary.Vector.${iid.toString()}`, iid) + .addMethod('GetAt', new DynWinRtMethodSig().addIn(DynWinRtType.u32()).addOut(elementType)) + .addMethod('get_Size', new DynWinRtMethodSig().addOut(DynWinRtType.u32())) +} + +function collectionMapReader(keyType: DynWinRtType, valueType: DynWinRtType) { + const iid = DynWinRtType.parameterized(WinGuid.parse('3c2925fe-8519-45c1-aa79-197b6718c1c1'), [ + keyType, + valueType, + ]).iid() + return DynWinRtType.registerInterface(`CollectionBoundary.Map.${iid.toString()}`, iid) + .addMethod('Lookup', new DynWinRtMethodSig().addIn(keyType).addOut(valueType)) + .addMethod('get_Size', new DynWinRtMethodSig().addOut(DynWinRtType.u32())) +} + +function invokeCollectionReader(reader: DynWinRtType, collection: DynWinRtValue, slot: number, args: DynWinRtValue[]) { + const typed = collection.cast(reader.iid()) + try { + return reader.method(slot).invoke(typed, args) + } finally { + typed.release() + } +} + +function collectionProducerRoundTrips(elementType: DynWinRtType, item: DynWinRtValue, lookupKey = item) { + const [vector, keyMap, valueMap] = collectionProducerCases(elementType, [item]).map(({ create }) => create()) + try { + return [ + invokeCollectionReader(collectionVectorReader(elementType), vector, 6, [DynWinRtValue.u32(0)]), + invokeCollectionReader(collectionMapReader(DynWinRtType.i32(), elementType), valueMap, 6, [DynWinRtValue.i32(0)]), + invokeCollectionReader(collectionMapReader(elementType, DynWinRtType.i32()), keyMap, 6, [lookupKey]), + ] + } finally { + vector.release() + keyMap.release() + valueMap.release() + } +} + +test('collection producers reject recursively owned structs even when empty', (t) => { + const referenceType = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [ + DynWinRtType.u32(), + ]) + for (const [name, fieldType] of [ + ['String', DynWinRtType.hstring()], + ['Reference', referenceType], + ] as const) { + const inner = DynWinRtType.structType(`CollectionBoundary.Owned${name}`, [fieldType]) + const outer = DynWinRtType.structType(`CollectionBoundary.NestedOwned${name}`, [inner]) + for (const type of [inner, outer]) { + for (const items of [[], [DynWinRtStruct.create(type).toValue()]]) { + for (const producer of collectionProducerCases(type, items)) { + t.throws(producer.create, undefined, producer.name) + } + } + } + } +}) + +test('collection producers require exact struct and enum identities', (t) => { + const expected = DynWinRtType.structType('CollectionBoundary.Expected', [DynWinRtType.i32()]) + const wrongStructs = [ + DynWinRtType.structType('CollectionBoundary.SameShape', [DynWinRtType.i32()]), + DynWinRtType.structType('CollectionBoundary.Smaller', [DynWinRtType.u8()]), + DynWinRtType.structType('CollectionBoundary.CrossType', [DynWinRtType.u32()]), + ] + const enumType = DynWinRtType.enumType('CollectionBoundary.Enum', ['One'], [1]) + const otherEnum = DynWinRtType.enumType('CollectionBoundary.OtherEnum', ['One'], [1]) + const cases: [DynWinRtType, DynWinRtValue][] = [ + ...wrongStructs.map((type): [DynWinRtType, DynWinRtValue] => [expected, DynWinRtStruct.create(type).toValue()]), + [expected, DynWinRtValue.i32(1)], + [DynWinRtType.i32(), DynWinRtStruct.create(expected).toValue()], + [enumType, DynWinRtValue.enumValue(otherEnum, 1)], + [DynWinRtType.i32(), DynWinRtValue.u32(1)], + [DynWinRtType.boolType(), DynWinRtValue.u8Value(1)], + ] + for (const [type, value] of cases) { + for (const producer of collectionProducerCases(type, [value])) { + t.throws(producer.create, undefined, producer.name) + } + } +}) + +test('collection producers preserve exact scalars and checked projection aliases', (t) => { + const enumType = DynWinRtType.enumType('CollectionBoundary.ScalarEnum', ['One'], [1]) + const cases: [DynWinRtType, DynWinRtValue, number, DynWinRtValue?][] = [ + [DynWinRtType.boolType(), DynWinRtValue.boolValue(true), 1], + [DynWinRtType.i8Type(), DynWinRtValue.i8Value(-128), -128], + [DynWinRtType.u8(), DynWinRtValue.u8Value(255), 255], + [DynWinRtType.i16(), DynWinRtValue.i16(-32768), -32768], + [DynWinRtType.u16(), DynWinRtValue.u16(65535), 65535], + [DynWinRtType.i32(), DynWinRtValue.i32(-123), -123], + [DynWinRtType.u32(), DynWinRtValue.u32(0xffffffff), 0xffffffff], + [DynWinRtType.char16(), DynWinRtValue.u16(0x03bb), 0x03bb], + [enumType, DynWinRtValue.enumValue(enumType, 1), 1], + [enumType, DynWinRtValue.i32(1), 1], + // HRESULT and I32 share collection IIDs; Lookup uses the common I32 projection. + [DynWinRtType.hresult(), DynWinRtValue.hresult(-1), -1, DynWinRtValue.i32(-1)], + [DynWinRtType.hresult(), DynWinRtValue.i32(-1), -1], + [DynWinRtType.i8Type(), DynWinRtValue.i32(-128), -128], + [DynWinRtType.i8Type(), DynWinRtValue.i32(127), 127], + [DynWinRtType.u8(), DynWinRtValue.i32(0), 0], + [DynWinRtType.u8(), DynWinRtValue.i32(255), 255], + [DynWinRtType.char16(), DynWinRtValue.i32(65535), 65535], + ] + for (const [type, value, expected, lookupKey] of cases) { + const [fromVector, fromMap, keyLookup] = collectionProducerRoundTrips(type, value, lookupKey) + t.is(fromVector.toNumber(), expected) + t.is(fromMap.toNumber(), expected) + t.is(keyLookup.toNumber(), 0) + } + for (const [type, values] of [ + [DynWinRtType.i8Type(), [-129, 128]], + [DynWinRtType.u8(), [-1, 256, 257]], + [DynWinRtType.char16(), [-1, 65536]], + ] as const) { + for (const value of values) { + for (const producer of collectionProducerCases(type, [DynWinRtValue.i32(value)])) { + t.throws(producer.create, undefined, producer.name) + } + } + } +}) + +test('collection producers retain direct strings and nullable references with the expected IID', (t) => { + roInitialize(1) + const [stringVector, stringMap, stringKey] = collectionProducerRoundTrips( + DynWinRtType.hstring(), + DynWinRtValue.hstring('owned \u03bb'), + ) + t.is(stringVector.toString(), 'owned \u03bb') + t.is(stringMap.toString(), 'owned \u03bb') + t.is(stringKey.toNumber(), 0) + + const referenceType = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [ + DynWinRtType.u32(), + ]) + const reference = DynWinRtType.registerInterface('CollectionBoundary.Reference', referenceType.iid()).addMethod( + 'get_Value', + new DynWinRtMethodSig().addOut(DynWinRtType.u32()), + ) + for (const type of [referenceType, DynWinRtType.interface(referenceType.iid()), DynWinRtType.object()]) { + const source = DynWinRtValue.boxReference(DynWinRtValue.u32(17), DynWinRtType.u32()) + const items = [source, DynWinRtValue.nullValue()] + const vector = DynWinRtValue.createVector(items, type) + const mapping = DynWinRtValue.createMap( + [DynWinRtValue.i32(0), DynWinRtValue.i32(1)], + items, + DynWinRtType.i32(), + type, + ) + source.release() + try { + const vectorReader = collectionVectorReader(type) + const mapReader = collectionMapReader(DynWinRtType.i32(), type) + for (const value of [ + invokeCollectionReader(vectorReader, vector, 6, [DynWinRtValue.u32(0)]), + invokeCollectionReader(mapReader, mapping, 6, [DynWinRtValue.i32(0)]), + ]) { + const typed = value.cast(referenceType.iid()) + t.is(reference.method(6).invoke(typed, []).toNumber(), 17) + typed.release() + value.release() + } + t.true(invokeCollectionReader(vectorReader, vector, 6, [DynWinRtValue.u32(1)]).isNull()) + t.true(invokeCollectionReader(mapReader, mapping, 6, [DynWinRtValue.i32(1)]).isNull()) + } finally { + vector.release() + mapping.release() + } + } + const incompatible = DynWinRtValue.activationFactory('Windows.Foundation.Uri') + try { + for (const value of [incompatible, DynWinRtValue.i32(17)]) { + for (const producer of collectionProducerCases(referenceType, [value])) { + t.throws(producer.create, undefined, producer.name) + } + } + } finally { + incompatible.release() + } +}) + +test('collection producers enforce the architecture-specific small POD boundary', (t) => { + const cases = [ + { + name: 'CollectionBoundary.Byte', + fields: [DynWinRtType.u8()], + size: 1, + hfa: false, + write: (s: DynWinRtStruct) => s.setU8(0, 201), + read: (s: DynWinRtStruct) => s.getU8(0), + expected: 201, + }, + { + name: 'CollectionBoundary.Short', + fields: [DynWinRtType.i16()], + size: 2, + hfa: false, + write: (s: DynWinRtStruct) => s.setI16(0, -1234), + read: (s: DynWinRtStruct) => s.getI16(0), + expected: -1234, + }, + { + name: 'CollectionBoundary.Int', + fields: [DynWinRtType.i32()], + size: 4, + hfa: false, + write: (s: DynWinRtStruct) => s.setI32(0, 123456), + read: (s: DynWinRtStruct) => s.getI32(0), + expected: 123456, + }, + { + name: 'Windows.Graphics.PointInt32', + fields: [DynWinRtType.i32(), DynWinRtType.i32()], + size: 8, + hfa: false, + write: (s: DynWinRtStruct) => s.setI32(1, -42), + read: (s: DynWinRtStruct) => s.getI32(1), + expected: -42, + }, + ...['Point', 'Size'].map((name) => ({ + name: `Windows.Foundation.${name}`, + fields: [DynWinRtType.f32(), DynWinRtType.f32()], + size: 8, + hfa: true, + write: (s: DynWinRtStruct) => s.setF32(1, 2.5), + read: (s: DynWinRtStruct) => s.getF32(1), + expected: 2.5, + })), + ] + for (const entry of cases) { + const type = DynWinRtType.structType(entry.name, entry.fields) + const value = DynWinRtStruct.create(type) + entry.write(value) + const supported = + process.arch === 'x64' || (process.arch === 'arm64' && !entry.hfa) || (process.arch === 'ia32' && entry.size <= 4) + for (const producer of collectionProducerCases(type, [])) { + if (supported) { + t.false(producer.create().isNull()) + } else { + t.throws(producer.create, undefined, entry.name) + } + } + if (supported) { + const [fromVector, fromMap, keyLookup] = collectionProducerRoundTrips(type, value.toValue()) + t.is(entry.read(fromVector.asStruct()), entry.expected) + t.is(entry.read(fromMap.asStruct()), entry.expected) + t.is(keyLookup.toNumber(), 0) + } else { + for (const producer of collectionProducerCases(type, [value.toValue()])) { + t.throws(producer.create, undefined, entry.name) + } + } + } +}) + +test('collection producers restrict large POD to ABI-compatible empty vectors', (t) => { + const cases = [ + { + name: 'Windows.Graphics.RectInt32', + fields: Array.from({ length: 4 }, () => DynWinRtType.i32()), + hfa: false, + size: 16, + }, + { + name: 'Windows.Foundation.Rect', + fields: Array.from({ length: 4 }, () => DynWinRtType.f32()), + hfa: true, + size: 16, + }, + { + name: 'Windows.Devices.Geolocation.BasicGeoposition', + fields: Array.from({ length: 3 }, () => DynWinRtType.f64()), + hfa: true, + size: 24, + }, + { + name: 'Windows.UI.Input.ManipulationDelta', + fields: [ + DynWinRtType.structType('Windows.Foundation.Point', [DynWinRtType.f32(), DynWinRtType.f32()]), + DynWinRtType.f32(), + DynWinRtType.f32(), + DynWinRtType.f32(), + ], + hfa: false, + size: 20, + }, + ] + 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) + 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) + } + } +}) + +test('collection producers reject floating scalars and GUIDs even when empty', (t) => { + const cases: [DynWinRtType, DynWinRtValue][] = [ + [DynWinRtType.f32(), DynWinRtValue.f32(1.5)], + [DynWinRtType.f64(), DynWinRtValue.f64(1.5)], + [DynWinRtType.guidType(), DynWinRtValue.guid(WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc'))], + ] + for (const [type, value] of cases) { + for (const items of [[], [value]]) { + for (const producer of collectionProducerCases(type, items)) { + t.throws(producer.create, undefined, producer.name) + } + } + } +}) + +test('collection producers reject 64-bit scalars on i686 even when empty', (t) => { + for (const [type, value, read] of [ + [DynWinRtType.i64(), DynWinRtValue.i64(-123n), (value: DynWinRtValue) => value.toI64Bigint()], + [DynWinRtType.u64(), DynWinRtValue.u64(123n), (value: DynWinRtValue) => value.toU64Bigint()], + ] as const) { + if (process.arch === 'ia32') { + for (const items of [[], [value]]) { + for (const producer of collectionProducerCases(type, items)) { + t.throws(producer.create, undefined, producer.name) + } + } + } else { + const [fromVector, fromMap, keyLookup] = collectionProducerRoundTrips(type, value) + t.is(read(fromVector), read(value)) + t.is(read(fromMap), read(value)) + t.is(keyLookup.toNumber(), 0) + } + } +}) + test('parse GUIDs', (t) => { const iid = '00000000-0000-0000-c000-000000000046' t.is(WinGuid.parse(iid).toString().toLowerCase(), iid) diff --git a/bindings/py/README.md b/bindings/py/README.md index cb6476cc..518ff4e9 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -74,7 +74,8 @@ slicing, assignment, insertion, and deletion; mutable maps support standard mapping assignment and deletion. Method inputs accept normal Python sequences and mappings in place of compatible -WinRT collection interfaces. Byte arrays accept `bytes` and `bytearray`; GUID, +WinRT collection interfaces, subject to the producer limits below. +Byte arrays accept `bytes` and `bytearray`; GUID, `DateTime`, and `TimeSpan` values use `uuid.UUID`, `datetime.datetime`, and `datetime.timedelta`. @@ -110,6 +111,49 @@ composition, raise a class-named `TypeError` on normal construction and their stubs expose no public constructor. Native return values still use the internal `_from_native`/`DynWinRTValue` wrapping path. +### Creating WinRT collections + +`DynWinRTValue.create_vector(items, element_type)` and +`DynWinRTValue.create_map(keys, values, key_type, value_type)` keep their public +signatures. They validate element identity, native layout, ownership, and the +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. + +| 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 | +| 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. + +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 +Char16, I32 inputs for enum/HRESULT, and range-checked I32 inputs for +I8/U8/Char16. For example, `from_i32(255)` is accepted for U8; +`from_i32(257)` raises instead of wrapping. Reference inputs are retained and +queried for the declared IID; an incompatible interface raises, while +`DynWinRTValue.null_value()` remains a null reference. + +The Python helpers use validated typed core factories. Rust callers can use +the safe `create_vector_from_values` / `create_map_from_values` factories for +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. +Unsupported layouts raise +`RuntimeError`; HRESULT-backed type, range, or QueryInterface failures raise +`OSError`. Complete native struct collection support is tracked in +[microsoft/dynwinrt#161](https://github.com/microsoft/dynwinrt/issues/161). + ## Raw object projection Use `project_as(value, Type)` when metadata returns `Object`/`IInspectable` but diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index cea9aee7..fdd5f57b 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +import sys +import sysconfig + import dynwinrt import pytest from dynwinrt import ( @@ -631,3 +634,348 @@ def test_struct_indexed_accessors_raise_runtime_error_for_wrong_field_shape(): value.set_object(0, DynWinRTValue.null_value()) with pytest.raises(RuntimeError): DynWinRTStruct.create(DynWinRTType.i32_type()).get_i32(0) + + +def _collection_producer_cases(element_type, items): + indexes = [DynWinRTValue.from_i32(index) for index in range(len(items))] + return [ + lambda: DynWinRTValue.create_vector(items, element_type), + lambda: DynWinRTValue.create_map( + items, indexes, element_type, DynWinRTType.i32_type() + ), + lambda: DynWinRTValue.create_map( + indexes, items, DynWinRTType.i32_type(), element_type + ), + ] + + +def _collection_vector_reader(element_type): + iid = DynWinRTType.parameterized( + WinGUID.parse("913337e9-11a1-4345-a3a2-4e7f956e222d"), [element_type] + ).iid() + return ( + DynWinRTType.register_interface( + f"CollectionBoundary.Vector.{iid.to_string()}", iid + ) + .add_method( + "GetAt", + DynWinRTMethodSig().add_in(DynWinRTType.u32_type()).add_out(element_type), + ) + .add_method("get_Size", DynWinRTMethodSig().add_out(DynWinRTType.u32_type())) + ) + + +def _collection_map_reader(key_type, value_type): + iid = DynWinRTType.parameterized( + WinGUID.parse("3c2925fe-8519-45c1-aa79-197b6718c1c1"), + [key_type, value_type], + ).iid() + return ( + DynWinRTType.register_interface( + f"CollectionBoundary.Map.{iid.to_string()}", iid + ) + .add_method("Lookup", DynWinRTMethodSig().add_in(key_type).add_out(value_type)) + .add_method("get_Size", DynWinRTMethodSig().add_out(DynWinRTType.u32_type())) + ) + + +def _invoke_collection_reader(reader, collection, slot, args): + typed = collection.cast(reader.iid()) + try: + return reader.method(slot).invoke(typed, args) + finally: + typed.release() + + +def _collection_producer_round_trips(element_type, item, lookup_key=None): + if lookup_key is None: + lookup_key = item + vector, key_map, value_map = [ + create() for create in _collection_producer_cases(element_type, [item]) + ] + try: + return [ + _invoke_collection_reader( + _collection_vector_reader(element_type), vector, 6, + [DynWinRTValue.from_u32(0)], + ), + _invoke_collection_reader( + _collection_map_reader(DynWinRTType.i32_type(), element_type), + value_map, 6, [DynWinRTValue.from_i32(0)], + ), + _invoke_collection_reader( + _collection_map_reader(element_type, DynWinRTType.i32_type()), + key_map, 6, [lookup_key], + ), + ] + finally: + vector.release() + key_map.release() + value_map.release() + + +def test_collection_producers_reject_recursively_owned_structs_even_when_empty(): + reference_type = DynWinRTType.parameterized( + WinGUID.parse("61c17706-2d65-11e0-9ae8-d48564015472"), + [DynWinRTType.u32_type()], + ) + for name, field_type in [ + ("String", DynWinRTType.hstring()), + ("Reference", reference_type), + ]: + inner = DynWinRTType.struct_type( + f"CollectionBoundary.Owned{name}", [field_type] + ) + outer = DynWinRTType.struct_type( + f"CollectionBoundary.NestedOwned{name}", [inner] + ) + for typ in [inner, outer]: + for items in [[], [DynWinRTStruct.create(typ).to_value()]]: + for create in _collection_producer_cases(typ, items): + with pytest.raises(RuntimeError): + create() + + +def test_collection_producers_require_exact_struct_and_enum_identities(): + expected = DynWinRTType.struct_type( + "CollectionBoundary.Expected", [DynWinRTType.i32_type()] + ) + wrong_structs = [ + DynWinRTType.struct_type( + "CollectionBoundary.SameShape", [DynWinRTType.i32_type()] + ), + DynWinRTType.struct_type( + "CollectionBoundary.Smaller", [DynWinRTType.u8_type()] + ), + DynWinRTType.struct_type( + "CollectionBoundary.CrossType", [DynWinRTType.u32_type()] + ), + ] + enum_type = DynWinRTType.enum_type("CollectionBoundary.Enum", ["One"], [1]) + other_enum = DynWinRTType.enum_type("CollectionBoundary.OtherEnum", ["One"], [1]) + cases = [ + *[(expected, DynWinRTStruct.create(typ).to_value()) for typ in wrong_structs], + (expected, DynWinRTValue.from_i32(1)), + (DynWinRTType.i32_type(), DynWinRTStruct.create(expected).to_value()), + (enum_type, DynWinRTValue.enum_value(other_enum, 1)), + (DynWinRTType.i32_type(), DynWinRTValue.from_u32(1)), + (DynWinRTType.bool_type(), DynWinRTValue.from_u8(1)), + ] + for typ, value in cases: + for create in _collection_producer_cases(typ, [value]): + with pytest.raises(OSError): + create() + + +def test_collection_producers_preserve_exact_scalars_and_checked_projection_aliases(): + enum_type = DynWinRTType.enum_type("CollectionBoundary.ScalarEnum", ["One"], [1]) + cases = [ + (DynWinRTType.bool_type(), DynWinRTValue.from_bool(True), 1), + (DynWinRTType.i8_type(), DynWinRTValue.from_i8(-128), -128), + (DynWinRTType.u8_type(), DynWinRTValue.from_u8(255), 255), + (DynWinRTType.i16_type(), DynWinRTValue.from_i16(-32768), -32768), + (DynWinRTType.u16_type(), DynWinRTValue.from_u16(65535), 65535), + (DynWinRTType.i32_type(), DynWinRTValue.from_i32(-123), -123), + (DynWinRTType.u32_type(), DynWinRTValue.from_u32(0xFFFFFFFF), 0xFFFFFFFF), + (DynWinRTType.char16(), DynWinRTValue.from_u16(0x03BB), 0x03BB), + (enum_type, DynWinRTValue.enum_value(enum_type, 1), 1), + (enum_type, DynWinRTValue.from_i32(1), 1), + # HRESULT and I32 share collection IIDs; Lookup uses the common I32 projection. + (DynWinRTType.hresult(), DynWinRTValue.from_hresult(-1), -1, + DynWinRTValue.from_i32(-1)), + (DynWinRTType.hresult(), DynWinRTValue.from_i32(-1), -1), + (DynWinRTType.i8_type(), DynWinRTValue.from_i32(-128), -128), + (DynWinRTType.i8_type(), DynWinRTValue.from_i32(127), 127), + (DynWinRTType.u8_type(), DynWinRTValue.from_i32(0), 0), + (DynWinRTType.u8_type(), DynWinRTValue.from_i32(255), 255), + (DynWinRTType.char16(), DynWinRTValue.from_i32(65535), 65535), + ] + for typ, value, expected, *lookup_keys in cases: + from_vector, from_map, key_lookup = _collection_producer_round_trips( + typ, value, lookup_keys[0] if lookup_keys else value + ) + assert from_vector.to_number() == expected + assert from_map.to_number() == expected + assert key_lookup.to_number() == 0 + + for typ, values in [ + (DynWinRTType.i8_type(), [-129, 128]), + (DynWinRTType.u8_type(), [-1, 256, 257]), + (DynWinRTType.char16(), [-1, 65536]), + ]: + for value in values: + for create in _collection_producer_cases(typ, [DynWinRTValue.from_i32(value)]): + with pytest.raises(OSError): + create() + + +def test_collection_producers_retain_direct_strings_and_nullable_references_with_expected_iid(): + ro_initialize(1) + from_vector, from_map, key_lookup = _collection_producer_round_trips( + DynWinRTType.hstring(), DynWinRTValue.from_hstring("owned \u03bb") + ) + assert from_vector.to_string() == "owned \u03bb" + assert from_map.to_string() == "owned \u03bb" + assert key_lookup.to_number() == 0 + + reference_type = DynWinRTType.parameterized( + WinGUID.parse("61c17706-2d65-11e0-9ae8-d48564015472"), + [DynWinRTType.u32_type()], + ) + reference = DynWinRTType.register_interface( + "CollectionBoundary.Reference", reference_type.iid() + ).add_method("get_Value", DynWinRTMethodSig().add_out(DynWinRTType.u32_type())) + for typ in [ + reference_type, + DynWinRTType.interface(reference_type.iid()), + DynWinRTType.object(), + ]: + source = DynWinRTValue.box_reference( + DynWinRTValue.from_u32(17), DynWinRTType.u32_type() + ) + items = [source, DynWinRTValue.null_value()] + vector = DynWinRTValue.create_vector(items, typ) + mapping = DynWinRTValue.create_map( + [DynWinRTValue.from_i32(0), DynWinRTValue.from_i32(1)], + items, DynWinRTType.i32_type(), typ, + ) + source.release() + try: + vector_reader = _collection_vector_reader(typ) + map_reader = _collection_map_reader(DynWinRTType.i32_type(), typ) + for value in [ + _invoke_collection_reader( + vector_reader, vector, 6, [DynWinRTValue.from_u32(0)] + ), + _invoke_collection_reader( + map_reader, mapping, 6, [DynWinRTValue.from_i32(0)] + ), + ]: + typed = value.cast(reference_type.iid()) + assert reference.method(6).invoke(typed, []).to_number() == 17 + typed.release() + value.release() + assert _invoke_collection_reader( + vector_reader, vector, 6, [DynWinRTValue.from_u32(1)] + ).is_null() + assert _invoke_collection_reader( + map_reader, mapping, 6, [DynWinRTValue.from_i32(1)] + ).is_null() + finally: + vector.release() + mapping.release() + + incompatible = DynWinRTValue.activation_factory("Windows.Foundation.Uri") + try: + for value in [incompatible, DynWinRTValue.from_i32(17)]: + for create in _collection_producer_cases(reference_type, [value]): + with pytest.raises(OSError): + create() + finally: + incompatible.release() + + +def test_collection_producers_enforce_architecture_specific_small_pod_boundary(): + is_x86 = sys.maxsize == 2**31 - 1 + is_arm64 = sysconfig.get_platform() == "win-arm64" + cases = [ + ("CollectionBoundary.Byte", [DynWinRTType.u8_type()], 1, False, + "set_u8", "get_u8", 0, 201), + ("CollectionBoundary.Short", [DynWinRTType.i16_type()], 2, False, + "set_i16", "get_i16", 0, -1234), + ("CollectionBoundary.Int", [DynWinRTType.i32_type()], 4, False, + "set_i32", "get_i32", 0, 123456), + ("Windows.Graphics.PointInt32", [DynWinRTType.i32_type()] * 2, 8, False, + "set_i32", "get_i32", 1, -42), + *[(f"Windows.Foundation.{name}", [DynWinRTType.f32_type()] * 2, 8, True, + "set_f32", "get_f32", 1, 2.5) for name in ["Point", "Size"]], + ] + for name, fields, size, hfa, setter, getter, index, expected in cases: + typ = DynWinRTType.struct_type(name, fields) + 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: + assert not create().is_null() + else: + with pytest.raises(RuntimeError): + create() + if supported: + from_vector, from_map, key_lookup = _collection_producer_round_trips( + typ, value.to_value() + ) + assert getattr(from_vector.as_struct(), getter)(index) == expected + 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()]): + 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" + cases = [ + ("Windows.Graphics.RectInt32", [DynWinRTType.i32_type()] * 4, False, 16), + ("Windows.Foundation.Rect", [DynWinRTType.f32_type()] * 4, True, 16), + ("Windows.Devices.Geolocation.BasicGeoposition", + [DynWinRTType.f64_type()] * 3, True, 24), + ("Windows.UI.Input.ManipulationDelta", [ + DynWinRTType.struct_type( + "Windows.Foundation.Point", [DynWinRTType.f32_type()] * 2 + ), + DynWinRTType.f32_type(), DynWinRTType.f32_type(), DynWinRTType.f32_type(), + ], False, 20), + ] + 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) + assert _invoke_collection_reader( + _collection_vector_reader(typ), vector, 7, [] + ).to_number() == 0 + 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() + + +def test_collection_producers_reject_floating_scalars_and_guids_even_when_empty(): + cases = [ + (DynWinRTType.f32_type(), DynWinRTValue.from_f32(1.5)), + (DynWinRTType.f64_type(), DynWinRTValue.from_f64(1.5)), + (DynWinRTType.guid_type(), DynWinRTValue.from_guid( + WinGUID.parse("9e365e57-48b2-4160-956f-c7385120bbfc") + )), + ] + for typ, value in cases: + for items in [[], [value]]: + for create in _collection_producer_cases(typ, items): + with pytest.raises(RuntimeError): + create() + + +def test_collection_producers_reject_64_bit_scalars_on_i686_even_when_empty(): + for typ, value in [ + (DynWinRTType.i64_type(), DynWinRTValue.from_i64(-123)), + (DynWinRTType.u64_type(), DynWinRTValue.from_u64(123)), + ]: + if sys.maxsize == 2**31 - 1: + for items in [[], [value]]: + for create in _collection_producer_cases(typ, items): + with pytest.raises(RuntimeError): + create() + else: + from_vector, from_map, key_lookup = _collection_producer_round_trips(typ, value) + assert from_vector.to_int() == value.to_int() + assert from_map.to_int() == value.to_int() + assert key_lookup.to_number() == 0 diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index 1a57ef06..7e1e3c59 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -574,15 +574,39 @@ def test_observable_vector_reports_mutations_and_unsubscribes(): "IVector_HString_Test", vector_type.iid(), ) - for index in range(7): - vector_interface.add_method( - f"unused_{index}", - DynWinRTMethodSig(), - ) - vector_interface.add_method( - "Append", - DynWinRTMethodSig().add_in(element_type), + vector_view_type = DynWinRTType.parameterized( + WinGUID.parse("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56"), + [element_type], ) + u32_type = DynWinRTType.u32_type() + # This real IID shares metadata with other projections, including readers. + # Register its actual ABI prefix rather than padding up to Append's slot. + for name, signature in [ + ( + "GetAt", + DynWinRTMethodSig().add_in(u32_type).add_out(element_type), + ), + ("get_Size", DynWinRTMethodSig().add_out(u32_type)), + ("GetView", DynWinRTMethodSig().add_out(vector_view_type)), + ( + "IndexOf", + DynWinRTMethodSig() + .add_in(element_type) + .add_out(u32_type) + .add_out(DynWinRTType.bool_type()), + ), + ( + "SetAt", + DynWinRTMethodSig().add_in(u32_type).add_in(element_type), + ), + ( + "InsertAt", + DynWinRTMethodSig().add_in(u32_type).add_in(element_type), + ), + ("RemoveAt", DynWinRTMethodSig().add_in(u32_type)), + ("Append", DynWinRTMethodSig().add_in(element_type)), + ]: + vector_interface.add_method(name, signature) event_args_interface = DynWinRTType.register_interface( "IVectorChangedEventArgs_Test", @@ -612,6 +636,10 @@ def changed(_sender, args): ) observable_value = vector_value.cast(observable_type.iid()) mutable_value = vector_value.cast(vector_type.iid()) + assert vector_interface.method(6).invoke( + mutable_value, [DynWinRTValue.from_u32(0)] + ).to_string() == "first" + assert vector_interface.method(7).invoke(mutable_value, []).to_u32() == 1 delegate = DynWinRtDelegate.create( handler_type.iid(), [observable_type, event_args_type], @@ -634,6 +662,10 @@ def changed(_sender, args): [DynWinRTValue.from_hstring("third")], ) assert notifications == [(1, 1)] + assert vector_interface.method(7).invoke(mutable_value, []).to_u32() == 3 + assert vector_interface.method(6).invoke( + mutable_value, [DynWinRTValue.from_u32(2)] + ).to_string() == "third" mutable_value.release() observable_value.release() diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index 48ee3908..177accf0 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -67,7 +67,7 @@ tokio = { version = "1.49.0", features = ["macros", "rt"] } [dev-dependencies.windows] version = ">=0.59, <=0.62" -features = ["Win32_Graphics_Imaging", "Win32_Media_MediaFoundation", "ApplicationModel_Background", "Win32_System_Pipes"] +features = ["Win32_Graphics_Imaging", "Win32_Media_MediaFoundation", "ApplicationModel_Background", "Win32_System_Pipes", "Graphics", "UI_Input"] [[bench]] name = "bench" diff --git a/crates/dynwinrt/src/collection_element.rs b/crates/dynwinrt/src/collection_element.rs new file mode 100644 index 00000000..d0271aa7 --- /dev/null +++ b/crates/dynwinrt/src/collection_element.rs @@ -0,0 +1,590 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use windows_core::{HSTRING, IUnknown, Interface}; + +use crate::{Error, Result, TypeHandle, TypeKind, WinRTValue}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CollectionStorage { + Word(usize), + HString, + Object, + EmptyOnly(usize), +} + +impl CollectionStorage { + pub(crate) fn is_value_type(self) -> bool { + matches!(self, Self::Word(_) | Self::EmptyOnly(_)) + } + + pub(crate) fn is_hstring(self) -> bool { + self == Self::HString + } + + pub(crate) fn is_empty_only(self) -> bool { + matches!(self, Self::EmptyOnly(_)) + } + + pub(crate) fn element_size(self) -> usize { + match self { + Self::Word(size) | Self::EmptyOnly(size) => size, + Self::HString | Self::Object => size_of::(), + } + } + + pub(crate) fn array_stride(self) -> usize { + self.element_size() + } + + pub(crate) fn raw_value(size: usize, empty: bool) -> Self { + assert!( + size > 0, + "create_value_vector: element size must be nonzero" + ); + // The unsafe byte constructor's caller must exclude floating aggregates. + aggregate_storage(CollectionTarget::current(), size, false, empty) + .expect("create_value_vector: element size has no supported collection ABI") + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CollectionTarget { + X86, + X64, + Arm64, + Unsupported, +} + +impl CollectionTarget { + fn current() -> Self { + match std::env::consts::ARCH { + "x86" => Self::X86, + "x86_64" => Self::X64, + "aarch64" => Self::Arm64, + _ => Self::Unsupported, + } + } + + fn word_size(self) -> usize { + match self { + Self::X86 => 4, + Self::X64 | Self::Arm64 => 8, + Self::Unsupported => 0, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ArgumentAbi { + DirectWord, + IndirectPointer, + MultipleWords, + FloatingAggregate, + Unsupported, +} + +// Windows ARM64 classifies HFAs before applying the >16-byte indirect rule. +fn aggregate_abi(target: CollectionTarget, size: usize, hfa: bool) -> ArgumentAbi { + if size == 0 { + return ArgumentAbi::Unsupported; + } + match target { + CollectionTarget::X86 if size <= 4 => ArgumentAbi::DirectWord, + CollectionTarget::X86 => ArgumentAbi::MultipleWords, + CollectionTarget::X64 if matches!(size, 1 | 2 | 4 | 8) => ArgumentAbi::DirectWord, + CollectionTarget::X64 => ArgumentAbi::IndirectPointer, + CollectionTarget::Arm64 if hfa => ArgumentAbi::FloatingAggregate, + CollectionTarget::Arm64 if size <= 8 => ArgumentAbi::DirectWord, + CollectionTarget::Arm64 if size <= 16 => ArgumentAbi::MultipleWords, + CollectionTarget::Arm64 => ArgumentAbi::IndirectPointer, + CollectionTarget::Unsupported => ArgumentAbi::Unsupported, + } +} + +fn aggregate_storage( + target: CollectionTarget, + size: usize, + hfa: bool, + allow_empty: bool, +) -> Option { + match aggregate_abi(target, size, hfa) { + ArgumentAbi::DirectWord => Some(CollectionStorage::Word(size)), + ArgumentAbi::IndirectPointer if allow_empty && size > target.word_size() => { + Some(CollectionStorage::EmptyOnly(size)) + } + _ => None, + } +} + +#[derive(Clone, Copy)] +struct PodLayout { + size: usize, + align: usize, + homogeneous: Option<(TypeKind, usize)>, +} + +fn pod_layout(typ: &TypeHandle, depth: usize) -> Result { + let unsupported = || Error::UnsupportedCollectionElement(typ.kind()); + if depth > 64 { + return Err(unsupported()); + } + if let Some(size) = typ.kind().primitive_size() { + return Ok(PodLayout { + size, + align: typ.align_of(), + homogeneous: match typ.kind() { + TypeKind::F32 | TypeKind::F64 => Some((typ.kind(), 1)), + _ => None, + }, + }); + } + if !matches!(typ.kind(), TypeKind::Struct(_)) || typ.field_count() == 0 { + return Err(unsupported()); + } + let mut end = 0usize; + let mut align = 1; + let mut homogeneous = None; + for index in 0..typ.field_count() { + let field = pod_layout(&typ.field_type(index), depth + 1)?; + let offset = end + .checked_next_multiple_of(field.align) + .ok_or_else(unsupported)?; + if typ.field_offset(index) != offset { + return Err(unsupported()); + } + end = offset.checked_add(field.size).ok_or_else(unsupported)?; + align = align.max(field.align); + homogeneous = if index == 0 { + field.homogeneous + } else { + match (homogeneous, field.homogeneous) { + (Some((left, count)), Some((right, added))) if left == right => { + Some((left, count.saturating_add(added))) + } + _ => None, + } + }; + } + let size = end + .checked_next_multiple_of(align) + .ok_or_else(unsupported)?; + if size == 0 || size != typ.size_of() || align != typ.align_of() { + return Err(unsupported()); + } + let homogeneous = homogeneous.filter(|(kind, count)| { + (1..=4).contains(count) + && kind + .primitive_size() + .and_then(|width| width.checked_mul(*count)) + == Some(size) + }); + Ok(PodLayout { + size, + align, + homogeneous, + }) +} + +pub(crate) struct CollectionElementPlan { + typ: TypeHandle, + pub(crate) storage: CollectionStorage, +} + +impl CollectionElementPlan { + pub(crate) fn new(typ: &TypeHandle, allow_empty: bool) -> Result { + Self::for_target(typ, allow_empty, CollectionTarget::current()) + } + + fn for_target(typ: &TypeHandle, allow_empty: bool, target: CollectionTarget) -> Result { + let unsupported = || Error::UnsupportedCollectionElement(typ.kind()); + let storage = match typ.kind() { + TypeKind::Bool + | TypeKind::I8 + | TypeKind::U8 + | TypeKind::I16 + | TypeKind::U16 + | TypeKind::Char16 + | TypeKind::I32 + | TypeKind::U32 + | TypeKind::I64 + | TypeKind::U64 + | TypeKind::Enum(_) + | TypeKind::HResult => { + let size = typ.size_of(); + if size > target.word_size() { + return Err(unsupported()); + } + CollectionStorage::Word(size) + } + TypeKind::Struct(_) => { + let layout = pod_layout(typ, 0).map_err(|_| unsupported())?; + aggregate_storage( + target, + layout.size, + layout.homogeneous.is_some(), + allow_empty, + ) + .ok_or_else(unsupported)? + } + TypeKind::HString => CollectionStorage::HString, + kind if kind.is_com_pointer() => CollectionStorage::Object, + _ => return Err(unsupported()), + }; + typ.table().try_closed_signature_string_kind(typ.kind())?; + if storage == CollectionStorage::Object + && typ.kind() != TypeKind::Object + && typ + .iid() + .is_none_or(|iid| iid == windows_core::GUID::zeroed()) + { + return Err(unsupported()); + } + Ok(Self { + typ: typ.clone(), + storage, + }) + } + + pub(crate) fn prepare(&self, item: &WinRTValue) -> Result { + if self.storage.is_empty_only() { + return Err(Error::UnsupportedCollectionElement(self.typ.kind())); + } + if self.storage == CollectionStorage::Object { + if item.is_null_object() { + return Ok(PreparedCollectionItem::Object(None)); + } + let Some(WinRTValue::Object(object)) = + crate::native_call::coerce_input_object(&self.typ, item)? + else { + return Err(Error::InvalidCollectionValue( + "an object implementing the declared interface", + )); + }; + return Ok(PreparedCollectionItem::Object(Some(object))); + } + if self.storage == CollectionStorage::HString && !matches!(item, WinRTValue::HString(_)) { + return Err(Error::InvalidCollectionValue("HSTRING")); + } + let coerced = crate::native_call::coerce_scalar_input(&self.typ, item)?; + let item = coerced.as_ref().unwrap_or(item); + if let WinRTValue::HString(value) = item { + return Ok(PreparedCollectionItem::HString(value.clone())); + } + let word = match item { + WinRTValue::Bool(value) => usize::from(*value), + WinRTValue::I8(value) => *value as usize, + WinRTValue::U8(value) => *value as usize, + WinRTValue::I16(value) => *value as usize, + WinRTValue::U16(value) => *value as usize, + WinRTValue::I32(value) => *value as usize, + WinRTValue::U32(value) => *value as usize, + WinRTValue::I64(value) => *value as usize, + WinRTValue::U64(value) => *value as usize, + WinRTValue::Enum { value, .. } => *value as usize, + WinRTValue::HResult(value) => value.0 as usize, + WinRTValue::Struct(data) => { + let actual = data.type_handle(); + if actual != &self.typ + || actual.size_of() != self.storage.element_size() + || actual.align_of() != self.typ.align_of() + { + return Err(Error::InvalidCollectionValue( + "the exact declared struct layout", + )); + } + let mut word = 0usize; + unsafe { + std::ptr::copy_nonoverlapping( + data.as_ptr(), + (&mut word as *mut usize).cast::(), + self.storage.element_size(), + ); + } + word + } + _ => { + return Err(Error::InvalidCollectionValue( + "the declared collection element type", + )); + } + }; + Ok(PreparedCollectionItem::Word(word)) + } +} + +pub(crate) enum PreparedCollectionItem { + Word(usize), + HString(HSTRING), + Object(Option), +} + +impl PreparedCollectionItem { + pub(crate) fn into_raw(self) -> usize { + match self { + Self::Word(word) => word, + Self::HString(value) => { + let raw: *mut core::ffi::c_void = unsafe { std::mem::transmute(value) }; + raw as usize + } + Self::Object(object) => object.map_or(0, |object| object.into_raw() as usize), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MetadataTable, map::create_map_from_values, vector::create_vector_from_values}; + + #[test] + fn target_argument_classification_and_empty_policy() { + use ArgumentAbi::*; + use CollectionTarget::*; + for size in [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16, 17, 24, 32] { + assert_eq!( + aggregate_abi(X86, size, false), + if size <= 4 { DirectWord } else { MultipleWords } + ); + assert_eq!( + aggregate_abi(X64, size, true), + if matches!(size, 1 | 2 | 4 | 8) { + DirectWord + } else { + IndirectPointer + } + ); + assert_eq!(aggregate_abi(Arm64, size, true), FloatingAggregate); + assert_eq!( + aggregate_abi(Arm64, size, false), + if size <= 8 { + DirectWord + } else if size <= 16 { + MultipleWords + } else { + IndirectPointer + } + ); + assert_eq!( + aggregate_storage(X86, size, false, true).is_some(), + size <= 4 + ); + assert_eq!( + aggregate_storage(X64, size, false, true).is_some(), + matches!(size, 1 | 2 | 4 | 8) || size > 8 + ); + assert_eq!( + aggregate_storage(Arm64, size, false, true).is_some(), + size <= 8 || size > 16 + ); + assert!(aggregate_storage(Arm64, size, true, true).is_none()); + for target in [X86, X64, Arm64] { + assert_eq!( + aggregate_storage(target, size, false, false).is_some(), + aggregate_abi(target, size, false) == DirectWord + ); + } + } + assert_eq!(aggregate_abi(Arm64, 0, false), ArgumentAbi::Unsupported); + assert_eq!( + aggregate_abi(CollectionTarget::Unsupported, 8, false), + ArgumentAbi::Unsupported + ); + } + + #[test] + fn recursive_layout_distinguishes_hfa_from_mixed_and_five_members() { + let table = MetadataTable::new(); + for float in [table.f32_type(), table.f64_type()] { + for count in 1..=5 { + let inner = table.struct_type( + &format!("Test.Float{float:?}.{count}"), + &vec![float.clone(); count], + ); + let nested = table.struct_type( + &format!("Test.Nested{float:?}.{count}"), + std::slice::from_ref(&inner), + ); + for typ in [inner, nested] { + let layout = pod_layout(&typ, 0).unwrap(); + assert_eq!(layout.homogeneous.is_some(), count <= 4); + let arm = + CollectionElementPlan::for_target(&typ, true, CollectionTarget::Arm64); + assert_eq!(arm.is_ok(), count == 5); + } + } + } + let mixed = table.struct_type("Test.Mixed", &[table.f32_type(), table.i32_type()]); + assert!(pod_layout(&mixed, 0).unwrap().homogeneous.is_none()); + assert_eq!( + CollectionElementPlan::for_target(&mixed, false, CollectionTarget::Arm64) + .unwrap() + .storage, + CollectionStorage::Word(8) + ); + } + + #[test] + fn rejects_recursive_ownership_and_incomplete_element_kinds() { + let table = MetadataTable::new(); + for (index, field) in [ + table.hstring(), + table.object(), + table.interface(windows_core::GUID::zeroed()), + ] + .into_iter() + .enumerate() + { + let direct = table.struct_type(&format!("Test.Owned{index}"), &[field]); + let nested = table.struct_type( + &format!("Test.NestedOwned{index}"), + std::slice::from_ref(&direct), + ); + for typ in [direct, nested] { + for target in [ + CollectionTarget::X86, + CollectionTarget::X64, + CollectionTarget::Arm64, + ] { + assert!(CollectionElementPlan::for_target(&typ, true, target).is_err()); + } + assert!(create_vector_from_values(&[], &typ, table.vector_iids(&typ)).is_err()); + assert!( + create_map_from_values( + &[], + &typ, + &table.i32_type(), + table.map_iids(&typ, &table.i32_type()) + ) + .is_err() + ); + assert!( + create_map_from_values( + &[], + &table.i32_type(), + &typ, + table.map_iids(&table.i32_type(), &typ) + ) + .is_err() + ); + } + } + for typ in [ + table.f32_type(), + table.f64_type(), + table.guid_type(), + table.struct_type("Test.Empty", &[]), + ] { + assert!(CollectionElementPlan::new(&typ, true).is_err()); + } + for kind in [ + TypeKind::ArrayOfIUnknown, + TypeKind::Generic { + piid: windows_core::GUID::zeroed(), + arity: 1, + }, + ] { + assert!(CollectionElementPlan::new(&table.make(kind), true).is_err()); + } + } + + #[test] + fn exact_struct_identity_precedes_byte_copy() { + let table = MetadataTable::new(); + let expected = table.struct_type("Test.Expected", &[table.u16_type(), table.u16_type()]); + let plan = CollectionElementPlan::new(&expected, false).unwrap(); + let other_table = MetadataTable::new(); + for actual in [ + table.struct_type("Test.Other", &[table.u16_type(), table.u16_type()]), + table.struct_type("Test.Smaller", &[table.u8_type()]), + other_table.struct_type( + "Test.Expected", + &[other_table.u16_type(), other_table.u16_type()], + ), + ] { + let value = WinRTValue::Struct(actual.default_value()); + assert!(plan.prepare(&value).is_err()); + assert!( + create_vector_from_values( + std::slice::from_ref(&value), + &expected, + table.vector_iids(&expected) + ) + .is_err() + ); + assert!( + create_map_from_values( + &[(WinRTValue::I32(1), value)], + &table.i32_type(), + &expected, + table.map_iids(&table.i32_type(), &expected) + ) + .is_err() + ); + } + assert!(plan.prepare(&WinRTValue::I32(0)).is_err()); + assert!( + plan.prepare(&WinRTValue::Struct(expected.default_value())) + .is_ok() + ); + assert!( + CollectionElementPlan::new(&table.i32_type(), false) + .unwrap() + .prepare(&WinRTValue::Struct(expected.default_value())) + .is_err() + ); + } + + #[test] + fn checked_scalar_aliases_do_not_silently_narrow() { + let table = MetadataTable::new(); + for (typ, good, bad) in [ + (table.i8_type(), -128, 128), + (table.u8_type(), 255, 257), + (table.char16_type(), 65535, 65536), + ] { + let plan = CollectionElementPlan::new(&typ, false).unwrap(); + assert!(plan.prepare(&WinRTValue::I32(good)).is_ok()); + assert!(plan.prepare(&WinRTValue::I32(bad)).is_err()); + if typ.kind() != TypeKind::I8 { + assert!(plan.prepare(&WinRTValue::I32(-1)).is_err()); + } + } + assert!( + CollectionElementPlan::new(&table.char16_type(), false) + .unwrap() + .prepare(&WinRTValue::U16(65)) + .is_ok() + ); + assert!( + CollectionElementPlan::new(&table.u16_type(), false) + .unwrap() + .prepare(&WinRTValue::I32(1)) + .is_err() + ); + assert!( + CollectionElementPlan::new(&table.bool_type(), false) + .unwrap() + .prepare(&WinRTValue::I32(1)) + .is_err() + ); + let expected = table.enum_type("Test.Enum", vec![]); + let other = table.enum_type("Test.OtherEnum", vec![]); + let plan = CollectionElementPlan::new(&expected, false).unwrap(); + assert!(plan.prepare(&WinRTValue::I32(i32::MAX)).is_ok()); + assert!( + plan.prepare(&WinRTValue::Enum { + value: 7, + type_handle: expected + }) + .is_ok() + ); + assert!( + plan.prepare(&WinRTValue::Enum { + value: 7, + type_handle: other + }) + .is_err() + ); + } +} diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index fd270211..c81668eb 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -5,6 +5,7 @@ use windows::core::*; mod abi; mod call; +mod collection_element; pub mod com; mod composition; mod ibuffer; diff --git a/crates/dynwinrt/src/map.rs b/crates/dynwinrt/src/map.rs index 9bab2f2a..b83fb7aa 100644 --- a/crates/dynwinrt/src/map.rs +++ b/crates/dynwinrt/src/map.rs @@ -11,14 +11,13 @@ use core::ffi::c_void; use std::sync::Mutex; use windows_core::{GUID, HRESULT, IUnknown, Interface}; +use crate::collection_element::{CollectionElementPlan, CollectionStorage}; use crate::com_helpers::{E_BOUNDS, E_FAIL, IInspectableVtbl, S_OK}; #[allow(unused_imports)] use crate::com_helpers::{dual_vtable_com, inspectable_stubs, lock_or, single_vtable_com}; use crate::vector::SingleThreadedIterator; use crate::vector::{ - CollectionStorage, clone_stored_item, collection_storage, pack_validated_collection_item, - release_stored_item, store_abi_item, stored_items_equal, validate_collection_item, - write_item_out, + clone_stored_item, release_stored_item, store_abi_item, stored_items_equal, write_item_out, }; // ====================================================================== @@ -26,7 +25,7 @@ use crate::vector::{ // ====================================================================== /// All IIDs needed for an IMap collection. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct MapIids { pub iterable: GUID, // IIterable> pub map: GUID, // IMap @@ -87,8 +86,8 @@ unsafe fn find_key_index( storage: CollectionStorage, ) -> Option { let key = key as usize; - if !storage.is_hstring - && !storage.is_value_type + if !storage.is_hstring() + && !storage.is_value_type() && let Some(search) = boxed_hstring(key) { return entries @@ -111,11 +110,7 @@ unsafe fn boxed_hstring(raw: usize) -> Option { } const fn object_storage() -> CollectionStorage { - CollectionStorage { - is_value_type: false, - is_hstring: false, - elem_size: std::mem::size_of::<*mut c_void>(), - } + CollectionStorage::Object } // ====================================================================== @@ -558,49 +553,57 @@ impl Drop for SingleThreadedKeyValuePair { /// /// The returned IUnknown supports QI for IMap, IIterable>, /// IMapView (via GetView), IKeyValuePair (via iteration), and IIterator (via First). -pub fn create_map(entries: Vec<(IUnknown, IUnknown)>, iids: MapIids) -> IUnknown { +/// +/// Prefer [`create_map_from_values`] for checked construction. +/// +/// # Safety +/// +/// All IIDs must form one coherent collection set whose key and value types +/// both have COM-reference ABI and ownership, never HSTRING/scalar/struct types. +/// Each key/value pointer must already be adjusted to its declared element +/// interface (IInspectable for Object). Owned references are transferred. +pub unsafe fn create_map(entries: Vec<(IUnknown, IUnknown)>, iids: MapIids) -> IUnknown { let entries = entries .into_iter() .map(|(key, value)| (key.into_raw() as usize, value.into_raw() as usize)) .collect(); - let storage = CollectionStorage { - is_value_type: false, - is_hstring: false, - elem_size: std::mem::size_of::<*mut c_void>(), - }; + let storage = CollectionStorage::Object; new_map(entries, storage, storage, iids) } +/// Create a checked map, validating element types, layouts, ownership and all IIDs. +/// +/// Keys and values must use the same metadata table. Large values are unsupported +/// even in an empty map; reference values are queried for the declared interface. pub fn create_map_from_values( entries: &[(crate::WinRTValue, crate::WinRTValue)], key_type: &crate::TypeHandle, value_type: &crate::TypeHandle, iids: MapIids, ) -> crate::Result { - let key_storage = collection_storage(key_type)?; - let value_storage = collection_storage(value_type)?; - if key_storage.is_large_value_type() { - return Err(crate::Error::UnsupportedCollectionElement(key_type.kind())); - } - if value_storage.is_large_value_type() { - return Err(crate::Error::UnsupportedCollectionElement( - value_type.kind(), + let key_plan = CollectionElementPlan::new(key_type, false)?; + let value_plan = CollectionElementPlan::new(value_type, false)?; + 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", )); } - for (key, value) in entries { - validate_collection_item(key, key_storage)?; - validate_collection_item(value, value_storage)?; + if iids != key_type.table().map_iids(key_type, value_type) { + return Err(crate::Error::InvalidCollectionValue( + "collection IIDs matching the declared key and value types", + )); } - let entries = entries + let prepared = entries .iter() - .map(|(key, value)| { - ( - pack_validated_collection_item(key, key_storage), - pack_validated_collection_item(value, value_storage), - ) + .map(|(key, value)| -> crate::Result<_> { + Ok((key_plan.prepare(key)?, value_plan.prepare(value)?)) }) + .collect::>>()?; + let entries = prepared + .into_iter() + .map(|(key, value)| (key.into_raw(), value.into_raw())) .collect(); - Ok(new_map(entries, key_storage, value_storage, iids)) + Ok(new_map(entries, key_plan.storage, value_plan.storage, iids)) } fn new_map( @@ -640,7 +643,8 @@ mod tests { let iids = table.map_iids(&table.hstring(), &table.object()); // Create empty map - let map = create_map(Vec::new(), iids.clone()); + let map = + create_map_from_values(&[], &table.hstring(), &table.object(), iids.clone()).unwrap(); // QI to IMap let mut map_ptr = std::ptr::null_mut(); @@ -700,8 +704,8 @@ mod tests { let table = MetadataTable::new(); let iids = table.map_iids(&table.hstring(), &table.object()); - let key_storage = collection_storage(&table.hstring()).unwrap(); - let value_storage = collection_storage(&table.object()).unwrap(); + let key_storage = CollectionStorage::HString; + let value_storage = CollectionStorage::Object; let uri = windows::Foundation::Uri::CreateUri(windows_core::h!("https://example.com")).unwrap(); diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 8455d225..d21bbbae 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -1078,7 +1078,7 @@ fn expected_object_iid(typ: &TypeHandle) -> Option { } } -fn coerce_input_object( +pub(crate) fn coerce_input_object( expected: &TypeHandle, value: &WinRTValue, ) -> windows_core::Result> { diff --git a/crates/dynwinrt/src/vector.rs b/crates/dynwinrt/src/vector.rs index ddb2d8c1..fcd5669b 100644 --- a/crates/dynwinrt/src/vector.rs +++ b/crates/dynwinrt/src/vector.rs @@ -15,6 +15,7 @@ use std::sync::{ }; use windows_core::{GUID, HRESULT, HSTRING, IUnknown, Interface}; +use crate::collection_element::{CollectionElementPlan, CollectionStorage, PreparedCollectionItem}; use crate::com_helpers::{ E_BOUNDS, E_FAIL, E_NOTIMPL, IInspectableVtbl, S_OK, com_to_usize, com_usize_addref_out, com_usize_release, @@ -27,7 +28,7 @@ use crate::com_helpers::{dual_vtable_com, inspectable_stubs, lock_or, single_vta // ====================================================================== /// All IIDs needed for an IVector collection. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct VectorIids { pub iterable: GUID, pub vector: GUID, @@ -171,59 +172,6 @@ impl VectorChangedEventArgs { } } -#[derive(Clone, Copy, Debug)] -pub(crate) struct CollectionStorage { - pub(crate) is_value_type: bool, - pub(crate) is_hstring: bool, - pub(crate) elem_size: usize, -} - -impl CollectionStorage { - pub(crate) fn is_large_value_type(self) -> bool { - self.is_value_type && self.elem_size > std::mem::size_of::() - } - - fn array_stride(self) -> usize { - if self.is_value_type { - self.elem_size - } else { - std::mem::size_of::<*mut c_void>() - } - } -} - -pub(crate) fn collection_storage( - element_type: &crate::TypeHandle, -) -> crate::Result { - use crate::TypeKind; - - let kind = element_type.kind(); - let elem_size = element_type.size_of(); - if matches!(kind, TypeKind::F32 | TypeKind::F64 | TypeKind::Guid) { - return Err(crate::Error::UnsupportedCollectionElement(kind)); - } - Ok(CollectionStorage { - is_hstring: kind == TypeKind::HString, - is_value_type: matches!( - kind, - TypeKind::Bool - | TypeKind::I8 - | TypeKind::U8 - | TypeKind::I16 - | TypeKind::U16 - | TypeKind::Char16 - | TypeKind::I32 - | TypeKind::U32 - | TypeKind::I64 - | TypeKind::U64 - | TypeKind::Enum(_) - | TypeKind::HResult - | TypeKind::Struct(_) - ), - elem_size, - }) -} - /// Write a raw usize item to an output pointer, AddRef'ing if it's a COM reference type. /// For value types, only writes `elem_size` bytes to avoid overwriting adjacent memory. #[inline(always)] @@ -232,11 +180,11 @@ pub(crate) unsafe fn write_item_out( raw: usize, result: *mut *mut c_void, ) { - if storage.is_hstring { + if storage.is_hstring() { *result = clone_hstring_raw(raw) as *mut c_void; - } else if storage.is_value_type { - // Write only elem_size bytes, clamped to usize width for safety. - let write_size = storage.elem_size.min(std::mem::size_of::()); + } else if storage.is_value_type() { + let write_size = storage.element_size(); + debug_assert!(!storage.is_empty_only()); unsafe { std::ptr::copy_nonoverlapping( &raw as *const usize as *const u8, @@ -265,12 +213,13 @@ unsafe fn store_array_item( index: usize, ) -> usize { let slot = values.cast::().add(index * storage.array_stride()); - let raw = if storage.is_value_type { + let raw = if storage.is_value_type() { + debug_assert!(!storage.is_empty_only()); let mut word = 0usize; std::ptr::copy_nonoverlapping( slot, (&mut word as *mut usize).cast::(), - storage.elem_size, + storage.element_size(), ); word as *mut c_void } else { @@ -296,9 +245,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 storage.is_hstring() { clone_hstring_raw(raw) - } else if storage.is_value_type { + } else if storage.is_value_type() { raw } else { com_to_usize(raw as *mut c_void) @@ -306,19 +255,19 @@ pub(crate) unsafe fn clone_stored_item(storage: CollectionStorage, raw: usize) - } pub(crate) unsafe fn store_abi_item(storage: CollectionStorage, raw: *mut c_void) -> usize { - if storage.is_hstring { + if storage.is_hstring() { clone_hstring_raw(raw as usize) - } else if storage.is_value_type { - normalize_value_word(raw as usize, storage.elem_size) + } else if storage.is_value_type() { + normalize_value_word(raw as usize, storage.element_size()) } else { com_to_usize(raw) } } pub(crate) unsafe fn release_stored_item(storage: CollectionStorage, raw: usize) { - if storage.is_hstring { + if storage.is_hstring() { release_hstring_raw(raw); - } else if !storage.is_value_type { + } else if !storage.is_value_type() { com_usize_release(raw); } } @@ -328,10 +277,10 @@ pub(crate) unsafe fn stored_items_equal( left: usize, right: usize, ) -> bool { - if !storage.is_hstring { - return if storage.is_value_type { - normalize_value_word(left, storage.elem_size) - == normalize_value_word(right, storage.elem_size) + if !storage.is_hstring() { + return if storage.is_value_type() { + normalize_value_word(left, storage.element_size()) + == normalize_value_word(right, storage.element_size()) } else { left == right }; @@ -596,10 +545,8 @@ impl SingleThreadedVector { found: *mut bool, ) -> HRESULT { let me = Self::from_vector_ptr(this); - // Large structs use a wider by-value ABI on ARM64, so the arguments - // following `value` do not match this pointer-sized vtable thunk. - // Only inspect `this` before returning. - if me.storage.is_large_value_type() { + // Empty-only aggregates lower to one pointer, but have no value storage. + if me.storage.is_empty_only() { return E_NOTIMPL; } let items = lock_or!(me.items, E_FAIL); @@ -623,7 +570,7 @@ impl SingleThreadedVector { if (index as usize) >= items.len() { return E_BOUNDS; } - if me.storage.is_large_value_type() { + if me.storage.is_empty_only() { return E_NOTIMPL; } let old = items[index as usize]; @@ -644,7 +591,7 @@ impl SingleThreadedVector { if (index as usize) > items.len() { return E_BOUNDS; } - if me.storage.is_large_value_type() { + if me.storage.is_empty_only() { return E_NOTIMPL; } let val = store_abi_item(me.storage, value); @@ -668,7 +615,7 @@ impl SingleThreadedVector { unsafe extern "system" fn append(this: *mut c_void, value: *mut c_void) -> HRESULT { let me = Self::from_vector_ptr(this); - if me.storage.is_large_value_type() { + if me.storage.is_empty_only() { return E_NOTIMPL; } let val = store_abi_item(me.storage, value); @@ -734,7 +681,7 @@ impl SingleThreadedVector { values: *const *mut c_void, ) -> HRESULT { let me = Self::from_vector_ptr(this); - if count > 0 && me.storage.is_large_value_type() { + if count > 0 && me.storage.is_empty_only() { return E_NOTIMPL; } let old_items: Vec = lock_or!(me.items, E_FAIL).drain(..).collect(); @@ -781,7 +728,7 @@ impl SingleThreadedVector { found: *mut bool, ) -> HRESULT { let me = Self::from_view_ptr(this); - if me.storage.is_large_value_type() { + if me.storage.is_empty_only() { return E_NOTIMPL; } let items = lock_or!(me.items, E_FAIL); @@ -938,7 +885,7 @@ impl SingleThreadedVectorView { found: *mut bool, ) -> HRESULT { let me = Self::from_view_ptr(this); - if me.storage.is_large_value_type() { + if me.storage.is_empty_only() { return E_NOTIMPL; } let needle = value as usize; @@ -1100,147 +1047,75 @@ impl Drop for SingleThreadedIterator { /// Create an IVector COM object from WinRTValue items. /// -/// Automatically handles both reference types (COM objects → AddRef/Release) -/// and value types (structs ≤ pointer size → raw bytes, no refcounting). +/// 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. pub fn create_vector_from_values( items: &[crate::WinRTValue], element_type: &crate::TypeHandle, iids: VectorIids, ) -> crate::Result { - let storage = collection_storage(element_type)?; - if !items.is_empty() && storage.is_large_value_type() { - return Err(crate::Error::UnsupportedCollectionElement( - element_type.kind(), + let plan = CollectionElementPlan::new(element_type, items.is_empty())?; + if iids != element_type.table().vector_iids(element_type) { + return Err(crate::Error::InvalidCollectionValue( + "collection IIDs matching the declared element type", )); } - for item in items { - validate_collection_item(item, storage)?; - } - let packed = items + let prepared = items .iter() - .map(|item| pack_validated_collection_item(item, storage)) + .map(|item| plan.prepare(item)) + .collect::>>()?; + let packed = prepared + .into_iter() + .map(PreparedCollectionItem::into_raw) .collect(); - Ok(new_vector(packed, storage, iids)) -} - -pub(crate) fn validate_collection_item( - item: &crate::WinRTValue, - storage: CollectionStorage, -) -> crate::Result<()> { - let valid = if storage.is_hstring { - matches!(item, crate::WinRTValue::HString(_)) - } else if !storage.is_value_type { - matches!( - item, - crate::WinRTValue::Object(_) | crate::WinRTValue::Async(_) | crate::WinRTValue::Null - ) - } else { - matches!( - item, - crate::WinRTValue::Bool(_) - | crate::WinRTValue::I8(_) - | crate::WinRTValue::U8(_) - | crate::WinRTValue::I16(_) - | crate::WinRTValue::U16(_) - | crate::WinRTValue::I32(_) - | crate::WinRTValue::U32(_) - | crate::WinRTValue::I64(_) - | crate::WinRTValue::U64(_) - | crate::WinRTValue::Enum { .. } - | crate::WinRTValue::HResult(_) - | crate::WinRTValue::Struct(_) - ) - }; - if valid { - Ok(()) - } else { - let expected = if storage.is_hstring { - "HSTRING" - } else if storage.is_value_type { - "a pointer-sized scalar or struct" - } else { - "a COM object or null" - }; - Err(crate::Error::InvalidCollectionValue(expected)) - } -} - -pub(crate) fn pack_validated_collection_item( - item: &crate::WinRTValue, - storage: CollectionStorage, -) -> usize { - if storage.is_hstring { - return match item { - crate::WinRTValue::HString(value) => { - let cloned: *mut c_void = unsafe { std::mem::transmute(value.clone()) }; - cloned as usize - } - _ => unreachable!("collection item was validated"), - }; - } - if !storage.is_value_type { - return match item { - crate::WinRTValue::Null => 0, - _ => { - let object = item.as_object().expect("collection item was validated"); - unsafe { com_to_usize(object.as_raw()) } - } - }; - } - - match item { - crate::WinRTValue::Bool(value) => usize::from(*value), - crate::WinRTValue::I8(value) => *value as usize, - crate::WinRTValue::U8(value) => *value as usize, - crate::WinRTValue::I16(value) => *value as usize, - crate::WinRTValue::U16(value) => *value as usize, - crate::WinRTValue::I32(value) => *value as usize, - crate::WinRTValue::U32(value) => *value as usize, - crate::WinRTValue::I64(value) => *value as usize, - crate::WinRTValue::U64(value) => *value as usize, - crate::WinRTValue::Enum { value, .. } => *value as usize, - crate::WinRTValue::HResult(value) => value.0 as usize, - crate::WinRTValue::Struct(data) => { - let mut value = 0usize; - unsafe { - std::ptr::copy_nonoverlapping( - data.as_ptr(), - &mut value as *mut usize as *mut u8, - storage.elem_size, - ); - } - value - } - _ => unreachable!("collection item was validated"), - } + Ok(new_vector(packed, plan.storage, iids)) } /// Create an IVector COM object from a Vec of IUnknown items (reference types). -pub fn create_vector(items: Vec, iids: VectorIids) -> IUnknown { +/// +/// Prefer [`create_vector_from_values`] for checked construction. +/// +/// # Safety +/// +/// All IIDs must be the complete collection IID set for the same COM-reference +/// element type, never a scalar, HSTRING, or struct. Each item must already be +/// adjusted to that element's interface (IInspectable for Object). The collection +/// transfers these owned references and returns that same interface view. +pub unsafe fn create_vector(items: Vec, iids: VectorIids) -> IUnknown { let raw_items: Vec = items .into_iter() .map(|obj| obj.into_raw() as usize) .collect(); - new_vector( - raw_items, - CollectionStorage { - is_value_type: false, - is_hstring: false, - elem_size: std::mem::size_of::<*mut c_void>(), - }, - iids, - ) + new_vector(raw_items, CollectionStorage::Object, iids) } -/// Create an IVector COM object for value types (structs ≤ pointer size). -pub fn create_value_vector(items: Vec>, elem_size: usize, iids: VectorIids) -> IUnknown { - if !items.is_empty() { - assert!( - elem_size <= std::mem::size_of::(), - "create_value_vector: elem_size {} exceeds pointer size; not yet supported", - elem_size - ); - } +/// Create an IVector COM object from raw POD value bytes. +/// +/// Prefer [`create_vector_from_values`] for checked construction. +/// +/// # Safety +/// +/// All IIDs, `elem_size`, and bytes must describe exactly the same native POD +/// type. Bytes must contain valid initialized values, with no owned fields. +/// By-value arguments must lower to one integer word on this target (never an +/// ARM64 HFA). Empty large values are allowed only when by-value T lowers to a +/// single indirect pointer: x64 aggregates, or ARM64 non-HFA aggregates >16 bytes. +/// No large values may subsequently be stored; their value-taking methods reject. +/// +/// # Panics +/// +/// Panics for unsupported sizes or any item whose length differs from `elem_size`. +pub unsafe fn create_value_vector( + items: Vec>, + elem_size: usize, + iids: VectorIids, +) -> IUnknown { + let storage = CollectionStorage::raw_value(elem_size, items.is_empty()); + assert!( + items.iter().all(|bytes| bytes.len() == elem_size), + "create_value_vector: every item must match the declared element size" + ); let packed: Vec = items .iter() .map(|bytes| { @@ -1249,21 +1124,13 @@ pub fn create_value_vector(items: Vec>, elem_size: usize, iids: VectorIi std::ptr::copy_nonoverlapping( bytes.as_ptr(), &mut val as *mut usize as *mut u8, - bytes.len().min(std::mem::size_of::()), + elem_size, ); } val }) .collect(); - new_vector( - packed, - CollectionStorage { - is_value_type: true, - is_hstring: false, - elem_size, - }, - iids, - ) + new_vector(packed, storage, iids) } fn new_vector(items: Vec, storage: CollectionStorage, iids: VectorIids) -> IUnknown { @@ -1290,10 +1157,22 @@ fn new_vector(items: Vec, storage: CollectionStorage, iids: VectorIids) - #[path = "vector_bulk_tests.rs"] mod bulk_tests; +#[cfg(test)] +#[path = "vector_abi_tests.rs"] +mod abi_tests; + #[cfg(test)] #[allow(unused_must_use)] mod tests { use super::*; + fn checked_object_vector(items: Vec, iids: VectorIids) -> IUnknown { + let table = crate::MetadataTable::new(); + let values = items + .into_iter() + .map(crate::WinRTValue::Object) + .collect::>(); + create_vector_from_values(&values, &table.object(), iids).unwrap() + } use crate::metadata_table::MetadataTable; #[test] @@ -1319,7 +1198,7 @@ mod tests { uri3.cast().unwrap(), ]; - let vector = create_vector(items, iids.clone()); + let vector = checked_object_vector(items, iids.clone()); // Test QI for IVector let mut vec_ptr = std::ptr::null_mut(); @@ -1371,7 +1250,7 @@ mod tests { let table = MetadataTable::new(); let object_type = table.object(); let iids = table.vector_iids(&object_type); - let vector = create_vector(Vec::new(), iids.clone()); + let vector = checked_object_vector(Vec::new(), iids.clone()); let changes = Arc::new(Mutex::new(Vec::<(i32, u32)>::new())); let callback_changes = changes.clone(); let args_type = table.interface(IID_IVECTOR_CHANGED_EVENT_ARGS); @@ -1498,7 +1377,7 @@ mod tests { let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); - let vector = create_vector(Vec::new(), iids.clone()); + let vector = checked_object_vector(Vec::new(), iids.clone()); let mut observable_ptr = std::ptr::null_mut(); let mut vector_ptr = std::ptr::null_mut(); unsafe { @@ -1600,102 +1479,6 @@ mod tests { )); } - #[test] - fn test_empty_large_struct_vector_is_supported_but_not_mutable() { - #[repr(C)] - #[derive(Clone, Copy)] - struct RectInt32Abi { - x: i32, - y: i32, - width: i32, - height: i32, - } - - let table = MetadataTable::new(); - let rect = table.struct_type( - "Windows.Graphics.RectInt32", - &[ - table.i32_type(), - table.i32_type(), - table.i32_type(), - table.i32_type(), - ], - ); - let iids = table.vector_iids(&rect); - let vector = create_vector_from_values(&[], &rect, iids.clone()).unwrap(); - let mut vector_ptr = std::ptr::null_mut(); - unsafe { vector.query(&iids.vector, &mut vector_ptr) } - .ok() - .unwrap(); - let vtable = unsafe { *(vector_ptr as *const *const VectorVtbl) }; - let mut size = u32::MAX; - - assert_eq!(unsafe { ((*vtable).get_size)(vector_ptr, &mut size) }, S_OK); - assert_eq!(size, 0); - assert_eq!( - unsafe { ((*vtable).append)(vector_ptr, std::ptr::null_mut()) }, - E_NOTIMPL - ); - - let rect = RectInt32Abi { - x: 1, - y: 2, - width: 3, - height: 4, - }; - let vector_index_of: unsafe extern "system" fn( - *mut c_void, - RectInt32Abi, - *mut u32, - *mut bool, - ) -> HRESULT = unsafe { std::mem::transmute((*vtable).index_of) }; - let mut index = u32::MAX; - let mut found = true; - assert_eq!( - unsafe { vector_index_of(vector_ptr, rect, &mut index, &mut found) }, - E_NOTIMPL - ); - assert_eq!(index, u32::MAX); - assert!(found); - - let mut live_view_ptr = std::ptr::null_mut(); - unsafe { vector.query(&iids.vector_view, &mut live_view_ptr) } - .ok() - .unwrap(); - let live_view_vtable = unsafe { *(live_view_ptr as *const *const VectorViewVtbl) }; - let live_view_index_of: unsafe extern "system" fn( - *mut c_void, - RectInt32Abi, - *mut u32, - *mut bool, - ) -> HRESULT = unsafe { std::mem::transmute((*live_view_vtable).index_of) }; - assert_eq!( - unsafe { live_view_index_of(live_view_ptr, rect, &mut index, &mut found) }, - E_NOTIMPL - ); - - let mut snapshot_view_ptr = std::ptr::null_mut(); - assert_eq!( - unsafe { ((*vtable).get_view)(vector_ptr, &mut snapshot_view_ptr) }, - S_OK - ); - let snapshot_view_vtable = unsafe { *(snapshot_view_ptr as *const *const VectorViewVtbl) }; - let snapshot_view_index_of: unsafe extern "system" fn( - *mut c_void, - RectInt32Abi, - *mut u32, - *mut bool, - ) -> HRESULT = unsafe { std::mem::transmute((*snapshot_view_vtable).index_of) }; - assert_eq!( - unsafe { snapshot_view_index_of(snapshot_view_ptr, rect, &mut index, &mut found) }, - E_NOTIMPL - ); - - drop(unsafe { IUnknown::from_raw(snapshot_view_ptr) }); - drop(unsafe { IUnknown::from_raw(live_view_ptr) }); - drop(unsafe { IUnknown::from_raw(vector_ptr) }); - } - #[test] fn test_nonempty_large_struct_vector_remains_unsupported() { let table = MetadataTable::new(); @@ -1757,7 +1540,7 @@ mod tests { let iids = table.vector_iids(&table.object()); // Start with empty vector - let vector = create_vector(Vec::new(), iids.clone()); + let vector = checked_object_vector(Vec::new(), iids.clone()); // QI to IVector let mut vec_ptr = std::ptr::null_mut(); @@ -1805,7 +1588,7 @@ mod tests { let items: Vec = vec![uri1.cast().unwrap(), uri2.cast().unwrap()]; - let vector = create_vector(items, iids.clone()); + let vector = checked_object_vector(items, iids.clone()); // QI to IIterable let mut iter_iface_ptr = std::ptr::null_mut(); @@ -1850,7 +1633,7 @@ mod tests { let uri = windows::Foundation::Uri::CreateUri(windows_core::h!("https://example.com")).unwrap(); let items: Vec = vec![uri.cast().unwrap()]; - let vector = create_vector(items, iids.clone()); + let vector = checked_object_vector(items, iids.clone()); // QI for IVectorView should succeed let mut view_ptr = std::ptr::null_mut(); @@ -1889,7 +1672,7 @@ mod tests { let uri = windows::Foundation::Uri::CreateUri(windows_core::h!("https://example.com")).unwrap(); let items: Vec = vec![uri.cast().unwrap()]; - let vector = create_vector(items, iids.clone()); + let vector = checked_object_vector(items, iids.clone()); // QI to IVector to call get_view let mut vec_ptr = std::ptr::null_mut(); @@ -1933,7 +1716,7 @@ mod tests { let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); - let vector = create_vector(Vec::new(), iids.clone()); + let vector = checked_object_vector(Vec::new(), iids.clone()); let mut vec_ptr = std::ptr::null_mut(); unsafe { vector.query(&iids.vector, &mut vec_ptr) } @@ -1979,7 +1762,8 @@ mod tests { // Pack i32 values into usize slots let items: Vec> = vec![42i32.to_ne_bytes().to_vec(), 99i32.to_ne_bytes().to_vec()]; - let vector = create_value_vector(items, 4, iids.clone()); + // Initialized i32 bytes and the complete matching IID set have word ABI on all targets. + let vector = unsafe { create_value_vector(items, 4, iids.clone()) }; // QI to IVector let mut vec_ptr = std::ptr::null_mut(); @@ -2028,7 +1812,7 @@ mod tests { let uri = windows::Foundation::Uri::CreateUri(windows_core::h!("https://example.com")).unwrap(); let items: Vec = vec![uri.cast().unwrap()]; - let vector = create_vector(items, iids.clone()); + let vector = checked_object_vector(items, iids.clone()); // QI to IVector from main thread let mut vec_ptr = std::ptr::null_mut(); diff --git a/crates/dynwinrt/src/vector_abi_tests.rs b/crates/dynwinrt/src/vector_abi_tests.rs new file mode 100644 index 00000000..4a90e37e --- /dev/null +++ b/crates/dynwinrt/src/vector_abi_tests.rs @@ -0,0 +1,632 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +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_collections::{IVector, IVectorView}; + +macro_rules! exercise_vector { + ($native:ty, $element:expr, $item:expr, $values:expr) => {{ + let element = $element; + assert_eq!(element.size_of(), size_of::<$native>()); + let values: [$native; 3] = $values; + let object = + create_vector_from_values(&[$item], &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(); + assert_eq!(vector.GetAt(0).unwrap(), values[0]); + let mut index = u32::MAX; + assert!(vector.IndexOf(values[0], &mut index).unwrap()); + assert_eq!(index, 0); + vector.Append(values[1]).unwrap(); + vector.SetAt(0, values[2]).unwrap(); + vector.InsertAt(1, values[0]).unwrap(); + assert_eq!(live.GetAt(0).unwrap(), values[2]); + assert_eq!(vector.GetAt(1).unwrap(), values[0]); + assert_eq!(snapshot.GetAt(0).unwrap(), values[0]); + assert!(live.IndexOf(values[0], &mut index).unwrap()); + assert_eq!(index, if values[2] == values[0] { 0 } else { 1 }); + assert!(snapshot.IndexOf(values[0], &mut index).unwrap()); + assert_eq!(index, 0); + vector.ReplaceAll(&values).unwrap(); + let mut output = [values[2]; 4]; + assert_eq!(vector.GetMany(0, &mut output[..3]).unwrap(), 3); + assert_eq!(&output[..3], &values); + assert_eq!(output[3], values[2]); + let iterator = vector.First().unwrap(); + vector.Clear().unwrap(); + assert_eq!(iterator.GetMany(&mut output[..3]).unwrap(), 3); + assert_eq!(&output[..3], &values); + }}; +} + +macro_rules! exercise_empty { + ($native:ty, $element:expr, $value:expr, $supported: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 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!(out, [value; 2]); + assert_eq!(iterator.Current().unwrap_err().code(), E_BOUNDS); + vector.Clear().unwrap(); + } else { + assert!(matches!( + result, + Err(crate::Error::UnsupportedCollectionElement(_)) + )); + } + }}; +} + +fn pair(typ: &TypeHandle, x: i32, y: i32) -> WinRTValue { + let mut value = typ.default_value(); + value.set_field(0, x); + value.set_field(1, y); + WinRTValue::Struct(value) +} + +#[test] +fn typed_scalar_and_enum_vector_operations() { + let table = MetadataTable::new(); + exercise_vector!( + bool, + table.bool_type(), + WinRTValue::Bool(false), + [false, true, false] + ); + exercise_vector!(i8, table.i8_type(), WinRTValue::I32(-8), [-8, 7, -1]); + exercise_vector!(u8, table.u8_type(), WinRTValue::I32(255), [255, 7, 1]); + exercise_vector!(i16, table.i16_type(), WinRTValue::I16(-8), [-8, 7, -1]); + exercise_vector!(u16, table.u16_type(), WinRTValue::U16(65535), [65535, 7, 1]); + exercise_vector!(i32, table.i32_type(), WinRTValue::I32(-8), [-8, 7, -1]); + exercise_vector!( + i32, + table.hresult(), + WinRTValue::HResult(HRESULT(-8)), + [-8, 7, -1] + ); + exercise_vector!( + u32, + table.u32_type(), + WinRTValue::U32(u32::MAX), + [u32::MAX, 7, 1] + ); + if cfg!(target_pointer_width = "64") { + exercise_vector!( + i64, + table.i64_type(), + WinRTValue::I64(i64::MIN), + [i64::MIN, i64::MAX, -1] + ); + exercise_vector!( + u64, + table.u64_type(), + WinRTValue::U64(u64::MAX), + [u64::MAX, 7, 1] + ); + } else { + for element in [table.i64_type(), table.u64_type()] { + assert!(create_vector_from_values(&[], &element, table.vector_iids(&element)).is_err()); + } + } + use windows_future::AsyncStatus; + exercise_vector!( + AsyncStatus, + table.enum_type("Windows.Foundation.AsyncStatus", vec![]), + WinRTValue::I32(1), + [AsyncStatus(1), AsyncStatus(2), AsyncStatus(99)] + ); +} + +#[test] +fn typed_point_size_and_integer_pair_boundaries() { + let table = MetadataTable::new(); + let color = table.struct_type("Windows.UI.Color", &vec![table.u8_type(); 4]); + let mut data = color.default_value(); + for index in 0..4 { + data.set_field(index, (index + 1) as u8); + } + exercise_vector!( + windows::UI::Color, + color, + WinRTValue::Struct(data), + [ + windows::UI::Color { + A: 1, + R: 2, + G: 3, + B: 4 + }, + windows::UI::Color { + A: 5, + R: 6, + G: 7, + B: 8 + }, + windows::UI::Color { + A: 9, + R: 10, + G: 11, + B: 12 + } + ] + ); + let point = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + let size = table.struct_type( + "Windows.Foundation.Size", + &[table.f32_type(), table.f32_type()], + ); + let point_int = table.struct_type( + "Windows.Graphics.PointInt32", + &[table.i32_type(), table.i32_type()], + ); + for element in [&point, &size] { + let mut data = element.default_value(); + 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 + } + ] + ); + } + } else { + for values in [vec![], vec![item]] { + assert!( + create_vector_from_values(&values, element, table.vector_iids(element)) + .is_err() + ); + } + } + } + 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()); + } +} + +#[test] +fn typed_empty_only_uses_indirect_argument_abi() { + let table = MetadataTable::new(); + let rect_int = table.struct_type("Windows.Graphics.RectInt32", &vec![table.i32_type(); 4]); + exercise_empty!( + RectInt32, + rect_int, + RectInt32 { + X: 1, + 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!( + Rect, + rect, + Rect { + X: 1.0, + Y: 2.0, + Width: 3.0, + Height: 4.0 + }, + cfg!(target_arch = "x86_64") + ); + let position = table.struct_type( + "Windows.Devices.Geolocation.BasicGeoposition", + &vec![table.f64_type(); 3], + ); + exercise_empty!( + BasicGeoposition, + position, + BasicGeoposition { + Latitude: 1.0, + Longitude: 2.0, + Altitude: 3.0 + }, + cfg!(target_arch = "x86_64") + ); + let point = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + let delta = table.struct_type( + "Windows.UI.Input.ManipulationDelta", + &[point, table.f32_type(), table.f32_type(), table.f32_type()], + ); + exercise_empty!( + ManipulationDelta, + delta, + ManipulationDelta { + Translation: Point { X: 1.0, Y: 2.0 }, + 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()); + } +} + +#[test] +fn raw_byte_constructor_checks_lengths_and_target_sizes() { + let table = MetadataTable::new(); + for bytes in [vec![1], vec![1; 5]] { + let result = std::panic::catch_unwind(|| unsafe { + create_value_vector(vec![bytes], 4, table.vector_iids(&table.i32_type())) + }); + assert!(result.is_err()); + } + + assert!(std::panic::catch_unwind(|| CollectionStorage::raw_value(0, true)).is_err()); + if cfg!(any(target_arch = "x86", target_arch = "aarch64")) { + assert!(std::panic::catch_unwind(|| CollectionStorage::raw_value(16, true)).is_err()); + } +} + +#[windows_core::implement(windows::Foundation::IStringable, windows::Foundation::IClosable)] +struct Tracked(std::sync::Arc); + +impl windows::Foundation::IStringable_Impl for Tracked_Impl { + fn ToString(&self) -> windows_core::Result { + Ok(HSTRING::from("retained")) + } +} + +impl windows::Foundation::IClosable_Impl for Tracked_Impl { + fn Close(&self) -> windows_core::Result<()> { + Ok(()) + } +} + +impl Drop for Tracked { + fn drop(&mut self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +fn tracked_value(dropped: &std::sync::Arc) -> WinRTValue { + let source: windows::Foundation::IClosable = Tracked(dropped.clone()).into(); + // This owns the real IClosable view; collection preparation must QI to IStringable. + WinRTValue::Object(unsafe { IUnknown::from_raw(source.into_raw()) }) +} + +#[test] +fn typed_interface_preparation_adjusts_and_retains_the_expected_view() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + use windows::Foundation::IStringable; + let table = MetadataTable::new(); + let element = table.interface(IStringable::IID); + let dropped = Arc::new(AtomicUsize::new(0)); + let input = tracked_value(&dropped); + let object = create_vector_from_values( + &[input.clone(), WinRTValue::Null], + &element, + table.vector_iids(&element), + ) + .unwrap(); + let vector: IVector = object.cast().unwrap(); + let output = vector.GetAt(0).unwrap(); + drop(input); + vector.Clear().unwrap(); + drop(vector); + drop(object); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + assert_eq!(output.ToString().unwrap(), HSTRING::from("retained")); + drop(output); + assert_eq!(dropped.load(Ordering::SeqCst), 1); +} + +#[test] +fn failed_preparation_releases_earlier_vector_and_map_items() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + use windows::Foundation::IStringable; + let table = MetadataTable::new(); + let element = table.interface(IStringable::IID); + let dropped = Arc::new(AtomicUsize::new(0)); + let input = tracked_value(&dropped); + assert!( + create_vector_from_values( + &[input.clone(), WinRTValue::I32(2)], + &element, + table.vector_iids(&element) + ) + .is_err() + ); + let wrong = table.interface(windows::Devices::Geolocation::IGeopoint::IID); + assert!( + create_vector_from_values( + std::slice::from_ref(&input), + &wrong, + table.vector_iids(&wrong) + ) + .is_err() + ); + assert!( + create_vector_from_values( + &[WinRTValue::RawPtr(std::ptr::null_mut())], + &element, + table.vector_iids(&element) + ) + .is_err() + ); + let key = table.hstring(); + assert!( + crate::map::create_map_from_values( + &[ + (WinRTValue::HString(HSTRING::from("first")), input.clone()), + (WinRTValue::I32(2), input.clone()) + ], + &key, + &element, + table.map_iids(&key, &element), + ) + .is_err() + ); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + drop(input); + assert_eq!(dropped.load(Ordering::SeqCst), 1); +} + +#[test] +fn typed_maps_preserve_hstring_and_interface_outputs() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + use windows::Foundation::IStringable; + use windows_collections::IMap; + let table = MetadataTable::new(); + let key = table.hstring(); + let value = table.interface(IStringable::IID); + let dropped = Arc::new(AtomicUsize::new(0)); + let input = tracked_value(&dropped); + let object = crate::map::create_map_from_values( + &[(WinRTValue::HString(HSTRING::from("key")), input.clone())], + &key, + &value, + table.map_iids(&key, &value), + ) + .unwrap(); + let map: IMap = object.cast().unwrap(); + drop(input); + let view = map.GetView().unwrap(); + let pair = map.First().unwrap().Current().unwrap(); + let output = map.Lookup(windows_core::h!("key")).unwrap(); + assert!(map.HasKey(windows_core::h!("key")).unwrap()); + assert!(map.Insert(windows_core::h!("key"), &output).unwrap()); + map.Remove(windows_core::h!("key")).unwrap(); + assert!(!map.HasKey(windows_core::h!("key")).unwrap()); + drop(map); + drop(object); + assert_eq!(pair.Key().unwrap(), HSTRING::from("key")); + assert_eq!( + pair.Value().unwrap().ToString().unwrap(), + HSTRING::from("retained") + ); + assert_eq!( + view.Lookup(windows_core::h!("key")) + .unwrap() + .ToString() + .unwrap(), + HSTRING::from("retained") + ); + drop(view); + drop(pair); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + drop(output); + assert_eq!(dropped.load(Ordering::SeqCst), 1); +} + +#[test] +fn typed_maps_handle_struct_keys_and_values() { + use windows_collections::IMap; + let table = MetadataTable::new(); + let point = table.struct_type( + "Windows.Graphics.PointInt32", + &[table.i32_type(), table.i32_type()], + ); + if cfg!(target_arch = "x86") { + for (key, value) in [ + (&point, table.i32_type()), + (&table.i32_type(), point.clone()), + ] { + assert!( + crate::map::create_map_from_values(&[], key, &value, table.map_iids(key, &value)) + .is_err() + ); + } + return; + } + let object = crate::map::create_map_from_values( + &[(WinRTValue::I32(7), pair(&point, 1, 2))], + &table.i32_type(), + &point, + table.map_iids(&table.i32_type(), &point), + ) + .unwrap(); + let map: IMap = object.cast().unwrap(); + assert_eq!(map.Lookup(7).unwrap(), PointInt32 { X: 1, Y: 2 }); + assert!(!map.Insert(8, PointInt32 { X: 3, Y: 4 }).unwrap()); + let view = map.GetView().unwrap(); + assert_eq!(view.Lookup(8).unwrap(), PointInt32 { X: 3, Y: 4 }); + assert_eq!( + map.First().unwrap().Current().unwrap().Value().unwrap(), + PointInt32 { X: 1, Y: 2 } + ); + let object = crate::map::create_map_from_values( + &[(pair(&point, 1, 2), WinRTValue::I32(7))], + &point, + &table.i32_type(), + table.map_iids(&point, &table.i32_type()), + ) + .unwrap(); + let map: IMap = object.cast().unwrap(); + let key = PointInt32 { X: 1, Y: 2 }; + assert_eq!(map.Lookup(key).unwrap(), 7); + assert!(map.HasKey(key).unwrap()); + assert!(map.Insert(key, 9).unwrap()); + assert_eq!(map.GetView().unwrap().Lookup(key).unwrap(), 9); + assert_eq!(map.First().unwrap().Current().unwrap().Key().unwrap(), key); + map.Remove(key).unwrap(); + assert!(!map.HasKey(key).unwrap()); +} + +#[test] +fn maps_reject_unsupported_shapes_iid_sets_and_cross_table_handles() { + let table = MetadataTable::new(); + let scalar = table.i32_type(); + let point = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + let large = table.struct_type("Windows.Graphics.RectInt32", &vec![scalar.clone(); 4]); + let odd = table.struct_type("Test.Odd", &vec![table.u8_type(); 3]); + for (element, supported) in [ + (point, cfg!(target_arch = "x86_64")), + (large, false), + (odd, cfg!(not(target_arch = "x86_64"))), + ] { + for (key, value) in [(&element, &scalar), (&scalar, &element)] { + assert_eq!( + crate::map::create_map_from_values(&[], key, value, table.map_iids(key, value)) + .is_ok(), + supported + ); + } + } + let expected = table.map_iids(&scalar, &scalar); + for field in 0..5 { + let mut iids = expected.clone(); + let fields = [ + &mut iids.iterable, + &mut iids.map, + &mut iids.map_view, + &mut iids.kvp, + &mut iids.iterator, + ]; + *fields.into_iter().nth(field).unwrap() = GUID::zeroed(); + assert!(crate::map::create_map_from_values(&[], &scalar, &scalar, iids).is_err()); + } + let other_table = MetadataTable::new(); + assert!( + crate::map::create_map_from_values(&[], &scalar, &other_table.i32_type(), expected) + .is_err() + ); +} diff --git a/crates/dynwinrt/src/vector_bulk_tests.rs b/crates/dynwinrt/src/vector_bulk_tests.rs index 8b652421..308e5156 100644 --- a/crates/dynwinrt/src/vector_bulk_tests.rs +++ b/crates/dynwinrt/src/vector_bulk_tests.rs @@ -2,7 +2,7 @@ // Licensed under the MIT License. use super::*; -use crate::{MetadataTable, TypeHandle, WinRTValue}; +use crate::{MetadataTable, TypeHandle, TypeKind, WinRTValue}; use windows_collections::IVector; use windows_core::IInspectable; @@ -54,7 +54,43 @@ fn iterator(object: &IUnknown, iids: &VectorIids) -> IUnknown { fn check_value_bulk(element: TypeHandle, items: Vec>) { let iids = element.table().vector_iids(&element); - let vector = create_value_vector(items.clone(), element.size_of(), iids.clone()); + let values = items + .iter() + .map(|bytes| { + assert_eq!(bytes.len(), element.size_of()); + match element.kind() { + TypeKind::Bool => WinRTValue::Bool(bytes[0] != 0), + TypeKind::I8 => WinRTValue::I8(bytes[0] as i8), + TypeKind::U8 => WinRTValue::U8(bytes[0]), + TypeKind::I16 => { + WinRTValue::I16(i16::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::U16 | TypeKind::Char16 => { + WinRTValue::U16(u16::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::I32 | TypeKind::Enum(_) | TypeKind::HResult => { + WinRTValue::I32(i32::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::U32 => { + WinRTValue::U32(u32::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::I64 => { + WinRTValue::I64(i64::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::U64 => { + WinRTValue::U64(u64::from_ne_bytes(bytes.as_slice().try_into().unwrap())) + } + TypeKind::Struct(_) => { + let mut data = element.default_value(); + data.set_field(0, bytes[0]); + data.set_field(1, bytes[1]); + WinRTValue::Struct(data) + } + kind => panic!("unexpected bulk test type: {kind:?}"), + } + }) + .collect::>(); + let vector = create_vector_from_values(&values, &element, iids.clone()).unwrap(); let mutable = query(&vector, &iids.vector); let vtable = unsafe { &**(mutable.as_raw() as *const *const VectorVtbl) }; let live = query(&vector, &iids.vector_view); diff --git a/docs/status/TODO.md b/docs/status/TODO.md index 6324fd99..4f3c00be 100644 --- a/docs/status/TODO.md +++ b/docs/status/TODO.md @@ -8,6 +8,21 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy ## P1 — Correctness / quality (near-term) +- [ ] **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) + 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` + require `unsafe`; safe `create_vector_from_values` / `create_map_from_values` + remain the validated typed alternative used by JS/Python. + - [x] **WinRT collection bulk element layout**. `IVector`, live and snapshot `IVectorView`, and `IIterator.GetMany` use the native element stride, not the internal pointer-sized storage stride. `ReplaceAll` reads packed