From f64ef4e811c78b4770a52f1330bedfe38bb3857d Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sun, 20 Sep 2026 11:34:01 +0800 Subject: [PATCH] Fix duplicate WinRT map keys with last-value-wins construction Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- .../js/__test__/collection-factories.e2e.mjs | 42 ++ bindings/py/tests/test_basic.py | 26 ++ crates/dynwinrt/src/collection_element.rs | 9 + crates/dynwinrt/src/map.rs | 43 +- crates/dynwinrt/src/map_constructor_tests.rs | 394 ++++++++++++++++++ .../javascript-binding-internals.md | 6 + 6 files changed, 511 insertions(+), 9 deletions(-) create mode 100644 crates/dynwinrt/src/map_constructor_tests.rs diff --git a/bindings/js/__test__/collection-factories.e2e.mjs b/bindings/js/__test__/collection-factories.e2e.mjs index 0566e1d3..d362ecb2 100644 --- a/bindings/js/__test__/collection-factories.e2e.mjs +++ b/bindings/js/__test__/collection-factories.e2e.mjs @@ -97,6 +97,47 @@ test('generated string map factory converts both keys and values', (t) => { assert.throws(() => generated.IMap_String_String.create(['mismatch'], []), /same length/) }) +test('generated map factory keeps the last duplicate value and first key order', (t) => { + const keep = own(t) + const duplicate = keep(generated.IMap_String_String.create(['same', 'same'], ['first', 'second'])) + assert.equal(duplicate.size, 1) + assert.equal(duplicate.lookup('same'), 'second') + duplicate.remove('same') + assert.equal(duplicate.size, 0) + assert.equal(duplicate.hasKey('same'), false) + + const map = keep(generated.IMap_String_String.create(['A', 'B', 'A'], ['first', 'middle', 'last'])) + const control = keep(generated.IMap_String_String.create([], [])) + assert.equal(control.insert('A', 'first'), false) + assert.equal(control.insert('B', 'middle'), false) + assert.equal(control.insert('A', 'last'), true) + const view = keep(map.getView()) + const iterableNames = Object.keys(generated).filter((name) => + name.startsWith('IIterable_WindowsFoundationCollectionsIKeyValuePair_String_String_'), + ) + assert.equal(iterableNames.length, 1) + assert.equal(map.size, 2) + for (const source of [map, control, view]) { + assert.equal(source.lookup('A'), 'last') + assert.equal(source.lookup('B'), 'middle') + const iterable = keep(new generated[iterableNames[0]](source._obj)) + const iterator = keep(iterable.first()) + const entries = [] + while (iterator.hasCurrent) { + const pair = keep(iterator.current) + entries.push([pair.key, pair.value]) + iterator.moveNext() + } + assert.deepEqual(entries, [ + ['A', 'last'], + ['B', 'middle'], + ]) + } + map.clear() + assert.equal(view.size, 2) + assert.equal(view.lookup('A'), 'last') +}) + test('typed empty factories still support append and insert', (t) => { const keep = own(t) const vector = keep(generated.IVector_String.create([])) @@ -202,6 +243,7 @@ test('collection-valued map factories preserve managed nulls without weakening n const uri = keep(generated.Uri.createUri('https://example.invalid/wrong-collection')) for (const invalid of [uri, uri._obj, {}, { isNull: () => true }, null, undefined]) { assert.throws(() => Map.create(['invalid'], [invalid]), /QueryInterface|cast/) + assert.throws(() => Map.create(['duplicate', 'duplicate'], [nil, invalid]), /QueryInterface|cast/) } let reads = 0 const wrappedNull = { diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index fdd5f57b..8a75574b 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -124,6 +124,32 @@ def test_create_map_round_trips_values_and_validates_lengths(): ) +def test_create_map_duplicate_keys_keep_the_last_value(): + key_type = DynWinRTType.hstring() + value_type = DynWinRTType.i32_type() + reader = _collection_map_reader(key_type, value_type) + keys = [DynWinRTValue.from_hstring(key) for key in ["A", "B", "A"]] + values = [DynWinRTValue.from_i32(value) for value in [1, 2, 3]] + mapping = DynWinRTValue.create_map(keys, values, key_type, value_type) + try: + assert _invoke_collection_reader(reader, mapping, 7, []).to_u32() == 2 + for key, expected in [("A", 3), ("B", 2)]: + assert _invoke_collection_reader( + reader, mapping, 6, [DynWinRTValue.from_hstring(key)] + ).to_int() == expected + assert keys[0].to_string() == "A" + assert values[0].to_int() == 1 + with pytest.raises(OSError): + DynWinRTValue.create_map( + [keys[0], keys[0]], + [values[0], DynWinRTValue.from_hstring("invalid later duplicate")], + key_type, + value_type, + ) + finally: + mapping.release() + + def test_guid_parse(): """WinGUID.parse should parse valid GUIDs.""" guid = WinGUID.parse("9e365e57-48b2-4160-956f-c7385120bbfc") diff --git a/crates/dynwinrt/src/collection_element.rs b/crates/dynwinrt/src/collection_element.rs index d0271aa7..95212b37 100644 --- a/crates/dynwinrt/src/collection_element.rs +++ b/crates/dynwinrt/src/collection_element.rs @@ -320,6 +320,15 @@ pub(crate) enum PreparedCollectionItem { } impl PreparedCollectionItem { + /// Borrow the ABI word without transferring ownership. + pub(crate) fn as_raw(&self) -> usize { + match self { + Self::Word(word) => *word, + Self::HString(value) => unsafe { std::mem::transmute_copy::(value) }, + Self::Object(object) => object.as_ref().map_or(0, |object| object.as_raw() as usize), + } + } + pub(crate) fn into_raw(self) -> usize { match self { Self::Word(word) => word, diff --git a/crates/dynwinrt/src/map.rs b/crates/dynwinrt/src/map.rs index b83fb7aa..df7224b6 100644 --- a/crates/dynwinrt/src/map.rs +++ b/crates/dynwinrt/src/map.rs @@ -11,7 +11,7 @@ use core::ffi::c_void; use std::sync::Mutex; use windows_core::{GUID, HRESULT, IUnknown, Interface}; -use crate::collection_element::{CollectionElementPlan, CollectionStorage}; +use crate::collection_element::{CollectionElementPlan, CollectionStorage, PreparedCollectionItem}; 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}; @@ -85,18 +85,21 @@ unsafe fn find_key_index( key: *mut c_void, storage: CollectionStorage, ) -> Option { - let key = key as usize; + find_key_position(entries.iter().map(|(key, _)| *key), key as usize, storage) +} + +unsafe fn find_key_position( + mut keys: impl Iterator, + key: usize, + storage: CollectionStorage, +) -> Option { if !storage.is_hstring() && !storage.is_value_type() && let Some(search) = boxed_hstring(key) { - return entries - .iter() - .position(|(stored, _)| boxed_hstring(*stored).is_some_and(|value| value == search)); + return keys.position(|stored| boxed_hstring(stored).is_some_and(|value| value == search)); } - entries - .iter() - .position(|(stored, _)| stored_items_equal(storage, *stored, key)) + keys.position(|stored| stored_items_equal(storage, stored, key)) } unsafe fn boxed_hstring(raw: usize) -> Option { @@ -575,6 +578,8 @@ pub unsafe fn create_map(entries: Vec<(IUnknown, IUnknown)>, iids: MapIids) -> I /// /// 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. +/// Duplicate keys use the same equality as `Insert`: the last value wins while +/// retaining the first key and its position. Every input pair is validated. pub fn create_map_from_values( entries: &[(crate::WinRTValue, crate::WinRTValue)], key_type: &crate::TypeHandle, @@ -599,7 +604,23 @@ pub fn create_map_from_values( Ok((key_plan.prepare(key)?, value_plan.prepare(value)?)) }) .collect::>>()?; - let entries = prepared + let mut unique: Vec<(PreparedCollectionItem, PreparedCollectionItem)> = + Vec::with_capacity(prepared.len()); + for (key, value) in prepared { + let index = unsafe { + find_key_position( + unique.iter().map(|(key, _)| key.as_raw()), + key.as_raw(), + key_plan.storage, + ) + }; + if let Some(index) = index { + unique[index].1 = value; + } else { + unique.push((key, value)); + } + } + let entries = unique .into_iter() .map(|(key, value)| (key.into_raw(), value.into_raw())) .collect(); @@ -628,6 +649,10 @@ fn new_map( // Tests // ====================================================================== +#[cfg(test)] +#[path = "map_constructor_tests.rs"] +mod constructor_tests; + #[cfg(test)] #[allow(unused_must_use)] mod tests { diff --git a/crates/dynwinrt/src/map_constructor_tests.rs b/crates/dynwinrt/src/map_constructor_tests.rs new file mode 100644 index 00000000..71f7b97b --- /dev/null +++ b/crates/dynwinrt/src/map_constructor_tests.rs @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use super::*; +use crate::{MetadataTable, TypeHandle, WinRTValue}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; +use windows::Foundation::{IClosable, IStringable, PropertyValue}; +use windows_collections::IMap; +use windows_core::{HSTRING, IInspectable}; + +fn checked_map( + entries: &[(WinRTValue, WinRTValue)], + key: &TypeHandle, + value: &TypeHandle, +) -> crate::Result { + create_map_from_values(entries, key, value, key.table().map_iids(key, value)) +} + +fn text(value: &str) -> WinRTValue { + WinRTValue::HString(HSTRING::from(value)) +} + +#[test] +fn duplicate_constructor_strings_match_insert_and_preserve_order() { + let table = MetadataTable::new(); + let typ = table.hstring(); + for (keys, expected) in [ + (vec![], vec![]), + (vec!["A", "B"], vec![("A", "0"), ("B", "1")]), + (vec!["same", "same"], vec![("same", "1")]), + (vec!["A", "B", "A"], vec![("A", "2"), ("B", "1")]), + ( + vec!["same", "Same", "same\0tail", "", "same\0tail", "", "same"], + vec![("same", "6"), ("Same", "1"), ("same\0tail", "4"), ("", "5")], + ), + ] { + let entries: Vec<_> = keys + .iter() + .enumerate() + .map(|(index, key)| (text(key), text(&index.to_string()))) + .collect(); + let map: IMap = + checked_map(&entries, &typ, &typ).unwrap().cast().unwrap(); + let control: IMap = checked_map(&[], &typ, &typ).unwrap().cast().unwrap(); + for (index, key) in keys.iter().enumerate() { + assert_eq!( + control + .Insert(&HSTRING::from(*key), &HSTRING::from(index.to_string())) + .unwrap(), + keys[..index].contains(key) + ); + } + assert_eq!(map.Size().unwrap(), expected.len() as u32); + assert_eq!(map.Size().unwrap(), control.Size().unwrap()); + let view = map.GetView().unwrap(); + let iterator = map.First().unwrap(); + let control_iterator = control.First().unwrap(); + for (key, value) in &expected { + let key = HSTRING::from(*key); + let value = HSTRING::from(*value); + assert_eq!(map.Lookup(&key).unwrap(), value); + assert_eq!(control.Lookup(&key).unwrap(), value); + assert_eq!(view.Lookup(&key).unwrap(), value); + for iterator in [&iterator, &control_iterator] { + let pair = iterator.Current().unwrap(); + assert_eq!(pair.Key().unwrap(), key); + assert_eq!(pair.Value().unwrap(), value); + iterator.MoveNext().unwrap(); + } + map.Remove(&key).unwrap(); + assert!(!map.HasKey(&key).unwrap()); + assert_eq!(map.Lookup(&key).unwrap_err().code(), E_BOUNDS); + } + assert!(!iterator.HasCurrent().unwrap()); + assert!(!control_iterator.HasCurrent().unwrap()); + assert_eq!(map.Size().unwrap(), 0); + assert_eq!(view.Size().unwrap(), expected.len() as u32); + assert_eq!( + view.First().unwrap().HasCurrent().unwrap(), + !expected.is_empty() + ); + } +} + +#[test] +fn duplicate_constructor_normalizes_scalar_and_enum_aliases() { + let table = MetadataTable::new(); + macro_rules! check { + ($native:ty, $typ:expr, $first:expr, $alias:expr, $key:expr) => {{ + let typ = $typ; + let map: IMap<$native, i32> = checked_map( + &[($first, WinRTValue::I32(1)), ($alias, WinRTValue::I32(2))], + &typ, + &table.i32_type(), + ) + .unwrap() + .cast() + .unwrap(); + assert_eq!(map.Size().unwrap(), 1); + assert_eq!(map.Lookup($key).unwrap(), 2); + assert!(map.Insert($key, 3).unwrap()); + assert_eq!(map.Size().unwrap(), 1); + assert_eq!(map.Lookup($key).unwrap(), 3); + map.Remove($key).unwrap(); + assert!(!map.HasKey($key).unwrap()); + }}; + } + check!( + bool, + table.bool_type(), + WinRTValue::Bool(true), + WinRTValue::Bool(true), + true + ); + check!( + i8, + table.i8_type(), + WinRTValue::I8(-1), + WinRTValue::I32(-1), + -1 + ); + check!( + u8, + table.u8_type(), + WinRTValue::U8(255), + WinRTValue::I32(255), + 255 + ); + check!( + i16, + table.i16_type(), + WinRTValue::I16(-1), + WinRTValue::I16(-1), + -1 + ); + check!( + u16, + table.u16_type(), + WinRTValue::U16(65535), + WinRTValue::U16(65535), + 65535 + ); + check!( + i32, + table.i32_type(), + WinRTValue::I32(-1), + WinRTValue::I32(-1), + -1 + ); + check!( + u32, + table.u32_type(), + WinRTValue::U32(u32::MAX), + WinRTValue::U32(u32::MAX), + u32::MAX + ); + check!( + i32, + table.hresult(), + WinRTValue::HResult(HRESULT(-1)), + WinRTValue::I32(-1), + -1 + ); + if cfg!(target_pointer_width = "64") { + check!( + i64, + table.i64_type(), + WinRTValue::I64(i64::MIN), + WinRTValue::I64(i64::MIN), + i64::MIN + ); + check!( + u64, + table.u64_type(), + WinRTValue::U64(u64::MAX), + WinRTValue::U64(u64::MAX), + u64::MAX + ); + } + let typ = table.enum_type("Windows.Foundation.AsyncStatus", vec![]); + check!( + windows_future::AsyncStatus, + typ.clone(), + WinRTValue::Enum { + value: 1, + type_handle: typ.clone() + }, + WinRTValue::I32(1), + windows_future::AsyncStatus(1) + ); +} + +#[windows_core::implement(IStringable, IClosable)] +struct Tracked(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, Ordering::SeqCst); + } +} + +fn tracked(dropped: &Arc) -> WinRTValue { + let source: IClosable = Tracked(dropped.clone()).into(); + // Preparation must adjust this IClosable pointer to the declared interface. + WinRTValue::Object(unsafe { IUnknown::from_raw(source.into_raw()) }) +} + +fn stringable(value: &WinRTValue) -> IStringable { + let WinRTValue::Object(object) = value else { + panic!("expected an object"); + }; + object.cast().unwrap() +} + +#[test] +fn duplicate_constructor_retains_typed_keys_and_only_the_latest_value() { + let table = MetadataTable::new(); + let typ = table.interface(IStringable::IID); + let key_drops = Arc::new(AtomicUsize::new(0)); + let old_drops = Arc::new(AtomicUsize::new(0)); + let latest_drops = Arc::new(AtomicUsize::new(0)); + let key = tracked(&key_drops); + let old = tracked(&old_drops); + let latest = tracked(&latest_drops); + let expected_key = stringable(&key); + let alias = WinRTValue::Object(unsafe { IUnknown::from_raw(expected_key.clone().into_raw()) }); + let entries = [(key.clone(), old.clone()), (alias, latest.clone())]; + let map: IMap = + checked_map(&entries, &typ, &typ).unwrap().cast().unwrap(); + assert_eq!(map.Size().unwrap(), 1); + assert_eq!(map.Lookup(&expected_key).unwrap(), stringable(&latest)); + drop(entries); + assert_eq!(old_drops.load(Ordering::SeqCst), 0); + assert_eq!( + stringable(&old).ToString().unwrap(), + HSTRING::from("retained") + ); + drop(old); + assert_eq!(old_drops.load(Ordering::SeqCst), 1); + drop(key); + drop(latest); + let view = map.GetView().unwrap(); + let iterator = map.First().unwrap(); + map.Remove(&expected_key).unwrap(); + assert_eq!(map.Size().unwrap(), 0); + assert!(!map.HasKey(&expected_key).unwrap()); + drop(map); + assert_eq!(view.Size().unwrap(), 1); + let pair = iterator.Current().unwrap(); + assert_eq!(pair.Key().unwrap(), expected_key); + assert_eq!( + pair.Value().unwrap().ToString().unwrap(), + HSTRING::from("retained") + ); + assert!(!iterator.MoveNext().unwrap()); + drop(expected_key); + drop(view); + drop(iterator); + assert_eq!(key_drops.load(Ordering::SeqCst), 0); + assert_eq!(latest_drops.load(Ordering::SeqCst), 0); + drop(pair); + assert_eq!(key_drops.load(Ordering::SeqCst), 1); + assert_eq!(latest_drops.load(Ordering::SeqCst), 1); +} + +#[test] +fn duplicate_constructor_preserves_first_boxed_string_key_identity() { + let table = MetadataTable::new(); + let first = PropertyValue::CreateString(windows_core::h!("same")).unwrap(); + let second = PropertyValue::CreateString(windows_core::h!("same")).unwrap(); + assert_ne!(first, second); + let map: IMap = checked_map( + &[ + ( + WinRTValue::Object(first.cast().unwrap()), + WinRTValue::I32(1), + ), + ( + WinRTValue::Object(second.cast().unwrap()), + WinRTValue::I32(2), + ), + ], + &table.object(), + &table.i32_type(), + ) + .unwrap() + .cast() + .unwrap(); + let control: IMap = checked_map(&[], &table.object(), &table.i32_type()) + .unwrap() + .cast() + .unwrap(); + assert!(!control.Insert(&first, 1).unwrap()); + assert!(control.Insert(&second, 2).unwrap()); + for map in [map, control] { + assert_eq!(map.Size().unwrap(), 1); + assert_eq!(map.Lookup(&second).unwrap(), 2); + assert_eq!( + map.First().unwrap().Current().unwrap().Key().unwrap(), + first + ); + map.Remove(&second).unwrap(); + assert!(!map.HasKey(&first).unwrap()); + } +} + +#[test] +fn duplicate_constructor_coalesces_managed_null_keys_and_values() { + let table = MetadataTable::new(); + let typ = table.interface(IStringable::IID); + let dropped = Arc::new(AtomicUsize::new(0)); + let input = tracked(&dropped); + let map: IMap = checked_map( + &[ + (WinRTValue::Null, input.clone()), + (WinRTValue::Null, WinRTValue::Null), + ], + &typ, + &typ, + ) + .unwrap() + .cast() + .unwrap(); + assert_eq!(map.Size().unwrap(), 1); + drop(input); + assert_eq!(dropped.load(Ordering::SeqCst), 1); + assert!(map.HasKey(None).unwrap()); + assert!(map.Insert(None, None).unwrap()); + map.Remove(None).unwrap(); + assert!(!map.HasKey(None).unwrap()); +} + +#[test] +fn duplicate_constructor_validates_every_value_and_releases_failed_staging() { + let table = MetadataTable::new(); + let typ = table.interface(IStringable::IID); + for wrong_iid in [false, true] { + let key_drops = Arc::new(AtomicUsize::new(0)); + let value_drops = Arc::new(AtomicUsize::new(0)); + let key = tracked(&key_drops); + let value = tracked(&value_drops); + let invalid = if wrong_iid { + WinRTValue::Object( + PropertyValue::CreateString(windows_core::h!("not IStringable")) + .unwrap() + .cast() + .unwrap(), + ) + } else { + WinRTValue::I32(7) + }; + // An invalid value cannot be hidden by either an earlier or a later duplicate. + for entries in [ + vec![(key.clone(), value.clone()), (key.clone(), invalid.clone())], + vec![(key.clone(), invalid.clone()), (key.clone(), value.clone())], + vec![ + (key.clone(), value.clone()), + (key.clone(), value.clone()), + (invalid.clone(), value.clone()), + ], + ] { + assert!(checked_map(&entries, &typ, &typ).is_err()); + } + assert_eq!(key_drops.load(Ordering::SeqCst), 0); + assert_eq!(value_drops.load(Ordering::SeqCst), 0); + assert_eq!( + stringable(&key).ToString().unwrap(), + HSTRING::from("retained") + ); + assert_eq!( + stringable(&value).ToString().unwrap(), + HSTRING::from("retained") + ); + drop(key); + drop(value); + assert_eq!(key_drops.load(Ordering::SeqCst), 1); + assert_eq!(value_drops.load(Ordering::SeqCst), 1); + } +} diff --git a/docs/architecture/javascript-binding-internals.md b/docs/architecture/javascript-binding-internals.md index 0ea1498f..c6689c30 100644 --- a/docs/architecture/javascript-binding-internals.md +++ b/docs/architecture/javascript-binding-internals.md @@ -47,6 +47,12 @@ Runtime-class and collection-reference conversions preserve managed null carriers without querying an interface; non-null carriers still query the declared interface before being passed to native code. +Typed map construction uses the same key equality as `Insert`. For duplicate +keys, the last value wins while the first key and its insertion position are +retained. All keys and values are validated before publishing the map, including +values that will be replaced. This policy is shared by the Rust, JavaScript and +Python typed constructors. + With the JS addon built, run `npm run test:collection-factories` from `bindings/js` for generated SDK factory roundtrips. `DYNWINRT_CODEGEN` selects a prebuilt generator, `DYNWINRT_JS_PACKAGE` selects a built runtime package,