Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/dynwinrt/src/metadata_table/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl MetadataTable {
// Interface method table writes
// -----------------------------------------------------------------------

/// Create an interface method table. Called only when dedup already checked by caller.
/// Atomically get or create an interface method table, deduplicated by IID.
pub(super) fn create_interface_method_table(&self, iid: GUID) {
self.interface_methods
.write()
Expand Down Expand Up @@ -149,7 +149,7 @@ impl MetadataTable {
}

// -----------------------------------------------------------------------
// Named type index (unified dedup for struct, enum, runtime_class, interface)
// Named type index (struct, enum, runtime_class; interfaces use IID identity)
// -----------------------------------------------------------------------

pub(super) fn get_named_type(&self, name: &str) -> Option<TypeKind> {
Expand Down
18 changes: 9 additions & 9 deletions crates/dynwinrt/src/metadata_table/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ mod append_only_arena;
mod arena;
mod iid;
mod method_handle;
#[cfg(test)]
mod registration_tests;
mod type_handle;
mod type_kind;
mod value_data;
Expand Down Expand Up @@ -279,16 +281,14 @@ impl MetadataTable {
// Registration API (single entry point for each type)
// -----------------------------------------------------------------------

/// Register a named interface. Creates an IID → method table.
/// Returns a TypeHandle for chaining `.add_method()`.
pub fn register_interface(self: &Arc<Self>, name: &str, iid: GUID) -> TypeHandle {
if let Some(kind) = self.get_named_type(name) {
return self.make(kind);
}
/// Register an interface by IID, returning a handle for chaining `.add_method()`.
///
/// The name is descriptive and retained for API compatibility, not used as
/// an identity or entered into the struct/enum/runtime-class name index.
/// Different IIDs may share a name; aliases for one IID share its method table.
pub fn register_interface(self: &Arc<Self>, _name: &str, iid: GUID) -> TypeHandle {
self.create_interface_method_table(iid);
let kind = TypeKind::Interface(iid);
self.insert_named_type(name, kind);
self.make(kind)
self.interface(iid)
}

/// Register a named struct with dedup. If already registered, returns
Expand Down
152 changes: 152 additions & 0 deletions crates/dynwinrt/src/metadata_table/registration_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use super::*;
use std::sync::Barrier;

const ISTRINGABLE: GUID = GUID::from_u128(0x96369f54_8eb6_48f0_abce_c1b211e627c3);
const ICLOSABLE: GUID = GUID::from_u128(0x30d5a829_7fa4_4026_83bb_d75bae4ea99e);

fn register_stringable(table: &Arc<MetadataTable>, name: &str) -> TypeHandle {
table.register_interface(name, ISTRINGABLE).add_method(
"ToString",
MethodSignature::new(table).add_out(table.hstring()),
)
}

fn register_closable(table: &Arc<MetadataTable>, name: &str) -> TypeHandle {
table
.register_interface(name, ICLOSABLE)
.add_method("Close", MethodSignature::new(table))
}

#[test]
fn same_name_different_iids_keep_independent_methods_in_both_orders() {
for reverse in [false, true] {
let table = MetadataTable::new();
let (stringable, closable) = if reverse {
let closable = register_closable(&table, "SharedInterface");
(register_stringable(&table, "SharedInterface"), closable)
} else {
let stringable = register_stringable(&table, "SharedInterface");
(stringable, register_closable(&table, "SharedInterface"))
};
assert_eq!(stringable, table.interface(ISTRINGABLE));
assert_eq!(closable, table.interface(ICLOSABLE));
assert!(stringable.method_by_name("Close").is_none());
assert!(closable.method_by_name("ToString").is_none());
assert_ne!(
stringable.method(6).unwrap().index,
closable.method(6).unwrap().index
);
assert!(stringable.method(7).is_none());
assert!(closable.method(7).is_none());
}
}

#[test]
fn same_iid_aliases_and_repeated_methods_preserve_published_method() {
let table = MetadataTable::new();
let first = register_stringable(&table, "IStringable");
let original = first.method(6).unwrap();
let original_ptr = table.method_ptr(original.index);
for name in [
"IStringable",
"Windows.Foundation.IStringable",
"AnotherPackage.IStringable",
] {
let repeated = register_stringable(&table, name);
assert_eq!(repeated, first);
assert_eq!(
repeated.method_by_name("ToString").unwrap().index,
original.index
);
assert_eq!(
table.method_ptr(repeated.method(6).unwrap().index),
original_ptr
);
assert!(repeated.method(7).is_none());
}
assert_eq!(table.interface_methods.read().unwrap().len(), 1);
}

#[test]
fn interface_names_do_not_alias_or_replace_other_named_types() {
for interface_first in [false, true] {
for category in 0..3 {
let table = MetadataTable::new();
let name = "SharedName";
let register_named = || match category {
0 => table.struct_type(name, &[table.i32_type()]),
1 => table.enum_type(name, vec![("Value".into(), 1)]),
2 => table.runtime_class(name.into(), &table.interface(ISTRINGABLE)),
_ => unreachable!(),
};
let (interface, named) = if interface_first {
(table.register_interface(name, ICLOSABLE), register_named())
} else {
let named = register_named();
(table.register_interface(name, ICLOSABLE), named)
};
assert_eq!(interface, table.interface(ICLOSABLE));
assert!(matches!(
(category, named.kind()),
(0, TypeKind::Struct(_)) | (1, TypeKind::Enum(_)) | (2, TypeKind::RuntimeClass(_))
));
assert_eq!(table.get_named_type(name), Some(named.kind()));
assert_eq!(register_named(), named);
assert_eq!(register_closable(&table, name), interface);
assert_eq!(table.get_named_type(name), Some(named.kind()));
}
}
}

#[test]
fn concurrent_registration_deduplicates_only_by_iid() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<MetadataTable>();
assert_send_sync::<TypeHandle>();
assert_send_sync::<MethodHandle>();

let table = MetadataTable::new();
let barrier = Arc::new(Barrier::new(16));
let threads: Vec<_> = (0..16)
.map(|index| {
let table = Arc::clone(&table);
let barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
let name = if index % 4 < 2 {
"SharedInterface"
} else {
"Alias"
};
let interface = if index % 2 == 0 {
register_stringable(&table, name)
} else {
register_closable(&table, name)
};
let expected = if index % 2 == 0 {
ISTRINGABLE
} else {
ICLOSABLE
};
assert_eq!(interface.iid(), Some(expected));
assert!(interface.method(7).is_none());
(expected, interface.method(6).unwrap().index)
})
})
.collect();
let results: Vec<_> = threads.into_iter().map(|thread| thread.join()).collect();
for result in results {
let (iid, index) = result.unwrap();
assert_eq!(table.interface(iid).method(6).unwrap().index, index);
}
let methods = table.interface_methods.read().unwrap();
assert_eq!(methods.len(), 2);
assert!(
methods
.values()
.all(|entry| entry.method_indices.len() == 1)
);
}
34 changes: 34 additions & 0 deletions docs/architecture/winrt-interface-implementations.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ Private scalar-validation, array-element identity rules, and native callback
storage are shared where their contracts are identical. The WinRT host never
registers its methods in the Classic COM registry.

Outbound WinRT `MetadataTable::register_interface` uses the IID as its identity,
not the supplied display name. Independently generated packages can register
interfaces with the same short name and different IIDs without sharing method
tables. Different names for the same IID share the existing table; repeated
method registration retains the originally published method and its slot.
Callers must still supply the same metadata contract in vtable order for a
given IID. Interface names are not inserted into the private name index used
for structs, enums, and runtime classes, so an interface cannot alias or replace
one of those named types. JavaScript and Python use this same core registry;
generated public names and the separate Classic COM registry are unchanged.

## Native object model

The canonical identity is an IInspectable-rooted allocation. Every interface
Expand Down Expand Up @@ -203,3 +214,26 @@ CLSID activation, COM server hosting, package identity/deployment, and task
registration are separate concerns and are not performed by this facility.

See [the Node.js and Python usage guide](../guides/windows/winrt-interface-implementations.md).

## Independent-package registration regression

`tests\e2e\registration_identity_test.ps1` separately generates
`Windows.UI.Xaml.Data.INotifyPropertyChanged` and
`Microsoft.UI.Xaml.Data.INotifyPropertyChanged` in JavaScript and Python.
It runs each package alone and both package orders in fresh processes. Each
case creates a generated implementation, subscribes and unsubscribes through
the native interface, and deterministically releases the retained delegate
view and implementation owner. No XAML activation or bootstrap DLL is needed.

Run it against built bindings and codegen, with an installed Python runtime
and an existing WinAppSDK metadata reference list (one absolute path per line):

```powershell
.\tests\e2e\registration_identity_test.ps1 `
-WinuiWinmd <path-to-Microsoft.UI.Xaml.winmd> -RefList <winmd-list.txt> `
-Python <python-with-dynwinrt.exe>
```

`-Codegen` and `-JsRuntime` select alternate built artifacts. The script never
restores metadata or installs tools; generated packages and a JSON process
report remain under `tests\e2e\e2e_generated\registration_identity`.
89 changes: 89 additions & 0 deletions tests/e2e/registration_identity_test.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env pwsh
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

param(
[Parameter(Mandatory)]
[string]$WinuiWinmd,
[Parameter(Mandatory)]
[string]$RefList,
[string]$WindowsWinmd = "C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd",
[string]$Python = "python",
[string]$Codegen,
[string]$JsRuntime,
[ValidateSet("py", "js")]
[string[]]$Lang = @("py", "js")
)

$ErrorActionPreference = "Stop"
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$out = Join-Path $PSScriptRoot "e2e_generated\registration_identity"
if (-not $Codegen) { $Codegen = Join-Path $root "target\release\dynwinrt-codegen.exe" }
if (-not $JsRuntime) { $JsRuntime = Join-Path $root "bindings\js\dist\winrt.js" }
$Codegen = (Resolve-Path -LiteralPath $Codegen).Path
$WinuiWinmd = (Resolve-Path -LiteralPath $WinuiWinmd).Path
$WindowsWinmd = (Resolve-Path -LiteralPath $WindowsWinmd).Path
$RefList = (Resolve-Path -LiteralPath $RefList).Path
if ("js" -in $Lang) { $JsRuntime = (Resolve-Path -LiteralPath $JsRuntime).Path }
New-Item -ItemType Directory -Path $out -Force | Out-Null

function Invoke-Case([string]$Executable, [string[]]$Arguments) {
$start = [System.Diagnostics.ProcessStartInfo]::new((Get-Command $Executable).Source)
$start.UseShellExecute = $false
$start.RedirectStandardOutput = $true
$start.RedirectStandardError = $true
$start.StandardOutputEncoding = [System.Text.Encoding]::UTF8
$start.StandardErrorEncoding = [System.Text.Encoding]::UTF8
$start.Environment["PYTHONIOENCODING"] = "utf-8"
foreach ($argument in $Arguments) { $start.ArgumentList.Add($argument) }
$process = [System.Diagnostics.Process]::Start($start)
try {
$stdout = $process.StandardOutput.ReadToEndAsync()
$stderr = $process.StandardError.ReadToEndAsync()
$timedOut = -not $process.WaitForExit(30000)
if ($timedOut) {
Stop-Process -Id $process.Id -Force
$process.WaitForExit()
}
return @{
exitCode = $process.ExitCode
timedOut = $timedOut
stdout = $stdout.GetAwaiter().GetResult()
stderr = $stderr.GetAwaiter().GetResult()
}
} finally {
$process.Dispose()
}
}

$results = @()
foreach ($language in $Lang) {
foreach ($name in @("windows", "winui")) {
$directory = Join-Path $out "${name}_$language"
$namespace = if ($name -eq "windows") { "Windows.UI.Xaml.Data" } else { "Microsoft.UI.Xaml.Data" }
$winmd = if ($name -eq "windows") { $WindowsWinmd } else { $WinuiWinmd }
$extra = @()
if ($language -eq "js") {
$extra = @("--import-name", [IO.Path]::GetRelativePath($directory, $JsRuntime).Replace("\", "/"))
}
& $Codegen generate --winmd $winmd --ref-list $RefList --namespace $namespace `
--class-name INotifyPropertyChanged --lang $language --output $directory @extra
if ($LASTEXITCODE -ne 0) { throw "Generation failed for $namespace ($language)" }
}
foreach ($order in @("windows", "winui", "windows,winui", "winui,windows")) {
$result = if ($language -eq "js") {
Invoke-Case "node" @((Join-Path $PSScriptRoot "runners\registration_identity_js.cjs"), $out, $JsRuntime, $order)
} else {
Invoke-Case $Python @((Join-Path $PSScriptRoot "runners\registration_identity_py.py"), $out, $order)
}
$result.language = $language
$result.order = $order
$result.pass = -not $result.timedOut -and $result.exitCode -eq 0
$results += $result
Write-Host "$language $order : $(if ($result.pass) { 'PASS' } else { 'FAIL' })"
if (-not $result.pass) { Write-Host $result.stderr }
}
}
$results | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $out "results.json") -Encoding utf8
if ($results.Where({ -not $_.pass }).Count) { exit 1 }
exit 0
43 changes: 43 additions & 0 deletions tests/e2e/runners/registration_identity_js.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

const assert = require('node:assert/strict');
const path = require('node:path');

const [generated, runtimePath, order] = process.argv.slice(2);
const runtime = require(path.resolve(runtimePath));
runtime.roInitialize(1);
const results = [];

for (const name of order.split(',')) {
const g = require(path.join(path.resolve(generated), `${name}_js`));
let added = 0;
let removed = 0;
let retained;
const owner = g.INotifyPropertyChanged.implement({
addPropertyChanged(callback) {
assert.equal(typeof callback, 'function');
retained = callback;
added++;
return { value: 1n };
},
removePropertyChanged(token) {
assert.equal(token.value, 1n);
g.releaseProjected(retained);
retained = undefined;
removed++;
},
});
try {
const unsubscribe = owner.value.onPropertyChanged(() => {});
unsubscribe();
assert.equal(added, 1);
assert.equal(removed, 1);
assert.equal(owner.takeError(), null);
results.push({ name, added, removed });
} finally {
if (retained) g.releaseProjected(retained);
owner.dispose();
}
}
console.log(JSON.stringify({ runtime: require.resolve(path.resolve(runtimePath)), results }));
Loading
Loading