From 27d9ac9cd8a266753c1717fd6bc5d255ed5ff152 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 16 Sep 2026 15:21:16 +0800 Subject: [PATCH 1/2] Fix Python WinUI module lifetime during teardown Retain validated WinUI implementation module ownership for Python until process termination, deduplicate activation fallback references, and preserve normal COM object and apartment cleanup. Add targeted native ownership, MTA, and Tokio teardown regressions without changing public Python or JavaScript APIs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/Cargo.toml | 3 + bindings/py/README.md | 50 ++ bindings/py/src/async_runtime.rs | 17 +- bindings/py/src/lib.rs | 17 + bindings/py/src/runtime.rs | 9 +- bindings/py/src/winui_test_hooks.rs | 73 +++ bindings/py/tests/test_winui_lifetime.py | 158 ++++++ crates/dynwinrt/src/lib.rs | 2 + crates/dynwinrt/src/roapi.rs | 59 +- crates/dynwinrt/src/winui_module.rs | 629 +++++++++++++++++++++ crates/dynwinrt/src/xaml_application.rs | 15 +- samples/python/winui-hello-world/README.md | 8 + tests/e2e/fixtures/winui_activation.cpp | 51 ++ tests/e2e/runners/py_winui_lifetime.py | 278 +++++++++ 14 files changed, 1356 insertions(+), 13 deletions(-) create mode 100644 bindings/py/src/winui_test_hooks.rs create mode 100644 bindings/py/tests/test_winui_lifetime.py create mode 100644 crates/dynwinrt/src/winui_module.rs create mode 100644 tests/e2e/fixtures/winui_activation.cpp create mode 100644 tests/e2e/runners/py_winui_lifetime.py diff --git a/bindings/py/Cargo.toml b/bindings/py/Cargo.toml index 2adb0c25..9637ceab 100644 --- a/bindings/py/Cargo.toml +++ b/bindings/py/Cargo.toml @@ -10,6 +10,9 @@ authors = ["Microsoft"] name = "dynwinrt" crate-type = ["cdylib"] +[features] +test-hooks = ["dynwinrt/test-hooks"] + [dependencies] dynwinrt = { path = "../../crates/dynwinrt" } pyo3 = "0.29.0" diff --git a/bindings/py/README.md b/bindings/py/README.md index 35befec9..1238b64b 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -323,6 +323,36 @@ When the required WinUI metadata is generated, `Application.create()` installs `Application.create_with_metadata_provider(...)` is available when the application supplies its own provider. +Python retains the validated WinUI implementation DLL after its first actual +WinUI activation until the process terminates. One named native owner keeps +one ordinary loader reference to `Microsoft.UI.Xaml.dll`; repeated activation +does not accumulate references. If WinUI activation requires the DLL-probing +fallback, its successful loader reference is transferred to the same owner +(one reference per required implementation DLL), rather than leaked per call. +Imports, ordinary WinRT activation, and COM apartment initialization do not +load or retain WinUI or CoreMessaging. +When a WinUI metadata provider loads Controls before XAML, the runtime resolves +the actual `Application` activation factory to establish this lifetime before +returning the provider's factory; it does not create an Application or start +its message loop. + +This is a process-lifetime module policy, not an object cache. Continue to +close windows, unsubscribe events, release projected/native objects, and +balance COM initialization on each thread as shown below. WinUI module-level +static state can remain after those application-owned resources are released. +The retained XAML mapping keeps its code valid when Controls static destruction +runs during COM cleanup, even when another MTA exits after the UI STA. + +No new context manager or async executor is required. The Python runtime does +not release the published module reference from `RoApartment.close()`, Python +`atexit`, or wrapper finalizers: the operating system reclaims it at process +termination. Consequently, in-process unloading/hot replacement of that WinUI +implementation is not supported. This does not prohibit WinUI's documented +thread-level XAML/DispatcherQueue shutdown, guarantee repeated +`Application.start()` in one process, or imply that all SDK static resources +are gone when a window closes. The JavaScript and independent WinRT/COM +lifetime policies are unchanged. + Python subclasses of public composable controls preserve one COM identity for inherited properties and methods. Metadata-supported `measure_override`, `arrange_override`, and `on_apply_template` callbacks run @@ -411,6 +441,26 @@ python -m maturin develop python -m pytest ``` +The focused WinUI lifetime regressions are in `tests\test_winui_lifetime.py`. +Without optional inputs they check ordinary WinRT imports and cleanup. Set +`DYNWINRT_WINUI_SAMPLE_ROOT` to a prepared Hello World directory (unchanged +`app.py`, `generated`, and `.runtime`) to exercise real STA, managed/external +MTA, exception, and default-async process teardown. Run each case in its own +process; process exit status is part of the assertion. + +For native ownership inspection and the test-only shutdownable Tokio fixture, +build a separate test environment with `maturin develop --features test-hooks`. +This adds private test helpers only, not a production executor or public API. +`DYNWINRT_WINUI_REQUIRE_OWNER_HOOK=1` additionally checks the retained owner. +From a matching-architecture Visual Studio developer shell, build +`tests\e2e\fixtures\winui_activation.cpp` with +`cl /LD /EHsc /std:c++17 winui_activation.cpp /link runtimeobject.lib /OUT:Microsoft.UI.Xaml.dll` +in a private output directory and set `DYNWINRT_WINUI_FIXTURE_DIR` to it. +That SDK-typed factory tests actual loader-reference transfer, concurrent +fallback activation, failed/null factories, identity mismatch, and retry +without requiring WinUI installation. Do not use this fixture DLL in the real +sample directory. + ## Release process The release tag supplies one unified npm/Cargo version. For example, diff --git a/bindings/py/src/async_runtime.rs b/bindings/py/src/async_runtime.rs index c2943997..24a1de57 100644 --- a/bindings/py/src/async_runtime.rs +++ b/bindings/py/src/async_runtime.rs @@ -23,20 +23,35 @@ thread_local! { static TOKIO_RO_INITIALIZED: Cell = const { Cell::new(false) }; } +#[cfg(feature = "test-hooks")] +pub(crate) static MTA_THREAD_EVENTS: Mutex> = Mutex::new(Vec::new()); + pub(crate) fn init_async_runtime() { + pyo3_async_runtimes::tokio::init(runtime_builder()); +} + +pub(crate) fn runtime_builder() -> tokio::runtime::Builder { let mut builder = tokio::runtime::Builder::new_multi_thread(); builder.enable_all(); builder.on_thread_start(|| { unsafe { RoInitialize(RO_INIT_MULTITHREADED) } .expect("failed to initialize a dynwinrt asyncio worker as MTA"); TOKIO_RO_INITIALIZED.set(true); + #[cfg(feature = "test-hooks")] + MTA_THREAD_EVENTS.lock().unwrap().push((true, unsafe { + windows::Win32::System::Threading::GetCurrentThreadId() + })); }); builder.on_thread_stop(|| { if TOKIO_RO_INITIALIZED.replace(false) { unsafe { RoUninitialize() }; + #[cfg(feature = "test-hooks")] + MTA_THREAD_EVENTS.lock().unwrap().push((false, unsafe { + windows::Win32::System::Threading::GetCurrentThreadId() + })); } }); - pyo3_async_runtimes::tokio::init(builder); + builder } fn ensure_async(value: &dynwinrt::WinRTValue) -> PyResult<()> { diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 99ebb131..f5bf9fcf 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -9,6 +9,8 @@ mod errors; mod implementation; mod runtime; mod values; +#[cfg(feature = "test-hooks")] +mod winui_test_hooks; #[pymodule] mod dynwinrt { @@ -594,6 +596,21 @@ _Coroutine.register(_DynWinRTAsyncWithProgress) m )?)?; m.add_function(wrap_pyfunction!(super::runtime::get_computer_name, m)?)?; + #[cfg(feature = "test-hooks")] + { + m.add_function(wrap_pyfunction!( + super::winui_test_hooks::_test_winui_owned_references, + m + )?)?; + m.add_function(wrap_pyfunction!( + super::winui_test_hooks::_test_winui_module_paths, + m + )?)?; + m.add_function(wrap_pyfunction!( + super::winui_test_hooks::_test_winui_with_mta_runtime, + m + )?)?; + } m.py().run( c" __all__ = [name for name in __all__ if not name.startswith('_')] diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 7da7608e..5fb3fd8b 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -15,6 +15,9 @@ use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_win static TABLE: std::sync::LazyLock> = std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new()); +pub(crate) static WINUI_MODULES: dynwinrt::WinUiProcessModules = + dynwinrt::WinUiProcessModules::new(); + pub(crate) fn wrap_python_callback_context( py: Python<'_>, callback: Py, @@ -1181,7 +1184,8 @@ pub struct DynWinRTValue(pub(crate) dynwinrt::WinRTValue); impl DynWinRTValue { #[staticmethod] fn activation_factory(name: String) -> PyResult { - dynwinrt::ro_get_activation_factory_2(&HSTRING::from(name)) + WINUI_MODULES + .activation_factory(&HSTRING::from(name)) .map(DynWinRTValue) .map_err(map_dynwinrt_error) } @@ -1225,7 +1229,8 @@ impl DynWinRTValue { }) }) .transpose()?; - dynwinrt::create_xaml_application(&provider, callback.as_ref()) + WINUI_MODULES + .create_xaml_application(&provider, callback.as_ref()) .map(DynWinRTValue) .map_err(map_dynwinrt_error) } diff --git a/bindings/py/src/winui_test_hooks.rs b/bindings/py/src/winui_test_hooks.rs new file mode 100644 index 00000000..a7c0642d --- /dev/null +++ b/bindings/py/src/winui_test_hooks.rs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use pyo3::{exceptions::PyRuntimeError, prelude::*}; +use windows::core::HSTRING; + +use crate::errors::map_windows_error; + +#[pyfunction] +pub(crate) fn _test_winui_owned_references() -> usize { + crate::runtime::WINUI_MODULES.owned_reference_count() +} + +#[pyfunction] +pub(crate) fn _test_winui_module_paths() -> PyResult> { + crate::runtime::WINUI_MODULES + .retained_module_paths() + .map(|paths| { + paths + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect() + }) + .map_err(map_windows_error) +} + +#[pyfunction] +pub(crate) fn _test_winui_with_mta_runtime( + py: Python<'_>, + callback: Py, +) -> PyResult> { + let start = crate::async_runtime::MTA_THREAD_EVENTS + .lock() + .unwrap() + .len(); + let runtime = crate::async_runtime::runtime_builder() + .worker_threads(2) + .build() + .map_err(|error| { + PyRuntimeError::new_err(format!("test runtime creation failed: {error}")) + })?; + + fn use_winrt() -> windows::core::Result { + let uri = windows::Foundation::Uri::CreateUri(&HSTRING::from("https://example.com/"))?; + Ok(uri.Host()? == "example.com") + } + + let async_job = runtime.spawn(async { use_winrt() }); + let blocking_job = runtime.spawn_blocking(use_winrt); + let prepared = py.detach(|| { + runtime.block_on(async { + let async_result = async_job.await; + let blocking_result = blocking_job.await; + for result in [async_result, blocking_result] { + if !result + .map_err(|error| PyRuntimeError::new_err(format!("test job failed: {error}")))? + .map_err(map_windows_error)? + { + return Err(PyRuntimeError::new_err( + "test worker returned an invalid URI", + )); + } + } + Ok(()) + }) + }); + let result = prepared.and_then(|()| callback.call0(py)); + // Use the production apartment hooks but a fixture-owned runtime so its + // actual async and blocking threads can all be stopped, not timeout-leaked. + py.detach(|| drop(runtime)); + result?; + Ok(crate::async_runtime::MTA_THREAD_EVENTS.lock().unwrap()[start..].to_vec()) +} diff --git a/bindings/py/tests/test_winui_lifetime.py b/bindings/py/tests/test_winui_lifetime.py new file mode 100644 index 00000000..b4db1b88 --- /dev/null +++ b/bindings/py/tests/test_winui_lifetime.py @@ -0,0 +1,158 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""WinUI ownership regressions; live cases require explicitly prepared inputs.""" + +import os +from pathlib import Path +import subprocess +import sys +import textwrap + +import pytest + + +def run_child(code, *, cwd=None, env=None): + environment = os.environ.copy() + environment.update( + PYTHONUNBUFFERED="1", + PYTHONFAULTHANDLER="1", + PYTHONDONTWRITEBYTECODE="1", + ) + if env: + environment.update(env) + result = subprocess.run( + [sys.executable, "-B", "-c", textwrap.dedent(code)], + cwd=cwd, + env=environment, + capture_output=True, + text=True, + timeout=90, + ) + assert result.returncode == 0, ( + f"native exit 0x{result.returncode & 0xFFFFFFFF:08X}\n" + f"{result.stdout}\n{result.stderr}" + ) + return result.stdout + + +def test_plain_winrt_keeps_optional_modules_unloaded(): + run_child(""" + import ctypes + import dynwinrt as dw + from types import SimpleNamespace + from dynwinrt.dynwinrt import _dynwinrt_track_projected + + kernel = ctypes.WinDLL("kernel32") + kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] + kernel.GetModuleHandleW.restype = ctypes.c_void_p + def check(): + for name in ("Microsoft.UI.Xaml.dll", "Microsoft.UI.Xaml.Controls.dll", "CoreMessaging.dll"): + assert not kernel.GetModuleHandleW(name), name + check() + for _ in range(2): + with dw.RoApartment(0), dw.projected_lifetime_scope(): + factory = dw.DynWinRTValue.activation_factory("Windows.Foundation.Uri") + _dynwinrt_track_projected(SimpleNamespace(_obj=factory)) + with dw.RoApartment(0): + assert not factory.is_null() + assert factory.is_null() + check() + assert not hasattr(dw, "WinUIHost") + """) + + +@pytest.mark.parametrize("failure", ["fail", "null", "forward"]) +def test_winui_fallback_failure_retry_and_deduplicated_ownership(failure): + fixture_dir = os.environ.get("DYNWINRT_WINUI_FIXTURE_DIR") + if not fixture_dir: + pytest.skip("requires the SDK-ABI WinUI activation DLL fixture") + assert (Path(fixture_dir) / "Microsoft.UI.Xaml.dll").is_file() + run_child(""" + import ctypes + import os + import threading + import dynwinrt as dw + from dynwinrt.dynwinrt import _test_winui_module_paths, _test_winui_owned_references + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.SetDllDirectoryW.argtypes = [ctypes.c_wchar_p] + kernel.SetDllDirectoryW.restype = ctypes.c_int + kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] + kernel.GetModuleHandleW.restype = ctypes.c_void_p + kernel.GetProcAddress.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + kernel.GetProcAddress.restype = ctypes.c_void_p + assert kernel.SetDllDirectoryW(os.getcwd()) + name = "Microsoft.UI.Xaml.DynWinRTFixture" + assert _test_winui_module_paths() == [] + assert _test_winui_owned_references() == 0 + with dw.RoApartment(1): + try: + dw.DynWinRTValue.activation_factory(name) + except OSError as error: + expected = { + "fail": -2147024891, + "null": -2147467261, + "forward": -2147418113, + } + assert error.winerror == expected[os.environ["DYNWINRT_WINUI_FIXTURE_MODE"]] + else: + raise AssertionError("invalid factory was accepted") + assert _test_winui_module_paths() == [] + assert _test_winui_owned_references() == 0 + assert not kernel.GetModuleHandleW("Microsoft.UI.Xaml.dll") + os.environ.pop("DYNWINRT_WINUI_FIXTURE_MODE") + failures = [] + barrier = threading.Barrier(8) + def activate(): + try: + with dw.RoApartment(1): + barrier.wait(10) + for _ in range(10): + factory = dw.DynWinRTValue.activation_factory(name) + factory.release() + factory.release() + except BaseException as error: + failures.append(error) + workers = [threading.Thread(target=activate) for _ in range(8)] + for worker in workers: + worker.start() + for worker in workers: + worker.join(20) + assert not worker.is_alive() + assert not failures, failures + assert len(_test_winui_module_paths()) == 1 + assert _test_winui_owned_references() == 1 + handle = kernel.GetModuleHandleW("Microsoft.UI.Xaml.dll") + assert handle + address = kernel.GetProcAddress(handle, b"FixtureObjectCount") + assert address + count = ctypes.WINFUNCTYPE(ctypes.c_ulong)(address) + assert count() == 0 + assert kernel.GetModuleHandleW("Microsoft.UI.Xaml.dll") + assert len(_test_winui_module_paths()) == 1 + assert _test_winui_owned_references() == 1 + assert kernel.SetDllDirectoryW(None) + """, cwd=fixture_dir, env={"DYNWINRT_WINUI_FIXTURE_MODE": failure}) + + +@pytest.mark.parametrize( + "mode", ["plain", "managed", "external", "tokio", "default-async", "body-error", "provider-error"] +) +def test_real_winui_teardown(mode): + sample_root = os.environ.get("DYNWINRT_WINUI_SAMPLE_ROOT") + if not sample_root: + pytest.skip("requires generated Hello World and its restored WinUI runtime") + runner = Path(__file__).resolve().parents[3] / "tests" / "e2e" / "runners" / "py_winui_lifetime.py" + command = [ + sys.executable, "-B", str(runner), "--sample-root", sample_root, "--mode", mode, + ] + if mode == "tokio" or os.environ.get("DYNWINRT_WINUI_REQUIRE_OWNER_HOOK") == "1": + command.append("--require-owner-hook") + environment = os.environ.copy() + environment.update(PYTHONUNBUFFERED="1", PYTHONFAULTHANDLER="1", PYTHONDONTWRITEBYTECODE="1") + result = subprocess.run(command, env=environment, capture_output=True, text=True, timeout=90) + assert result.returncode == 0, ( + f"native exit 0x{result.returncode & 0xFFFFFFFF:08X}\n{result.stdout}\n{result.stderr}" + ) + assert '"event": "winui-lifetime-ok"' in result.stdout diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 8c0ef736..fd270211 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -19,6 +19,7 @@ mod value; pub mod win32; mod winapp; mod winrt_implementation; +mod winui_module; mod xaml_application; mod array; @@ -65,6 +66,7 @@ pub use crate::winrt_implementation::{ WinRtImplementation, WinRtImplementationCallback, WinRtImplementationPlan, WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, }; +pub use crate::winui_module::WinUiProcessModules; pub use crate::xaml_application::{ XamlRuntimeClassActivator, XamlRuntimeClassRegistration, create_xaml_application, register_xaml_runtime_class, diff --git a/crates/dynwinrt/src/roapi.rs b/crates/dynwinrt/src/roapi.rs index e3c41d50..35c77dba 100644 --- a/crates/dynwinrt/src/roapi.rs +++ b/crates/dynwinrt/src/roapi.rs @@ -6,15 +6,26 @@ use windows::Win32::System::WinRT::{IActivationFactory, RoGetActivationFactory}; use windows_core::{HRESULT, HSTRING, IUnknown, Interface, PCSTR}; use crate::value::WinRTValue; +use crate::winui_module::{ModuleReference, WinUiProcessModules}; #[allow(dead_code)] pub fn ro_get_activation_factory(class_name: &HSTRING) -> windows_core::Result { unsafe { RoGetActivationFactory::(class_name) } } pub fn ro_get_activation_factory_2(class_name: &HSTRING) -> crate::result::Result { + activation_factory_with_modules(class_name, None) +} + +pub(crate) fn activation_factory_with_modules( + class_name: &HSTRING, + modules: Option<&'static WinUiProcessModules>, +) -> crate::result::Result { let r = unsafe { RoGetActivationFactory::(class_name) }; match r { Ok(factory) => { + if let Some(modules) = modules { + modules.retain_factory(class_name, &factory, &mut None)?; + } let ukn = unsafe { IUnknown::from_raw(factory.as_raw()) }; std::mem::forget(factory); Ok(WinRTValue::Object(ukn)) @@ -23,13 +34,16 @@ pub fn ro_get_activation_factory_2(class_name: &HSTRING) -> crate::result::Resul // Fallback: C++/WinRT-style DLL probing. // For class "A.B.C.ClassName", try loading "A.B.C.dll", "A.B.dll", "A.dll" // and call DllGetActivationFactory to obtain the factory. - if let Some(val) = dll_get_activation_factory_fallback(class_name) { + if let Some(val) = dll_get_activation_factory_fallback(class_name, modules)? { return Ok(val); } // If fallback also failed, return the original error let r2 = unsafe { RoGetActivationFactory::(class_name) }; match r2 { Ok(factory) => { + if let Some(modules) = modules { + modules.retain_factory(class_name, &factory, &mut None)?; + } let ukn = unsafe { IUnknown::from_raw(factory.as_raw()) }; std::mem::forget(factory); Ok(WinRTValue::Object(ukn)) @@ -47,7 +61,10 @@ pub fn ro_get_activation_factory_2(class_name: &HSTRING) -> crate::result::Resul /// Mirrors the logic in C++/WinRT base.h `get_runtime_activation_factory_impl` /// (lines 6116-6156): for class "A.B.C.Name", tries loading "A.B.C.dll", /// "A.B.dll", "A.dll" in order and calls DllGetActivationFactory on each. -fn dll_get_activation_factory_fallback(class_name: &HSTRING) -> Option { +fn dll_get_activation_factory_fallback( + class_name: &HSTRING, + modules: Option<&'static WinUiProcessModules>, +) -> crate::result::Result> { use windows::Win32::Foundation::FreeLibrary; type DllGetActivationFactoryFn = unsafe extern "system" fn( @@ -65,6 +82,7 @@ fn dll_get_activation_factory_fallback(class_name: &HSTRING) -> Option m, Err(_) => continue, }; + let mut owned_module = modules.map(|_| unsafe { ModuleReference::adopt(module) }); let proc = unsafe { GetProcAddress( @@ -73,8 +91,10 @@ fn dll_get_activation_factory_fallback(class_name: &HSTRING) -> Option Option, +} + +impl Default for WinUiProcessModules { + fn default() -> Self { + Self::new() + } +} + +impl WinUiProcessModules { + pub const fn new() -> Self { + Self { + modules: Mutex::new(Modules { + xaml: None, + controls: None, + }), + } + } + + /// Resolve a factory, retaining WinUI's implementation when actually used. + /// Other classes keep the ordinary activation and fallback policy. + pub fn activation_factory(&'static self, name: &HSTRING) -> Result { + crate::roapi::activation_factory_with_modules(name, is_winui_class(name).then_some(self)) + } + + /// Compose an Application using this same activation lifetime policy. + pub fn create_xaml_application( + &'static self, + metadata_provider: &IUnknown, + launched_callback: Option<&IUnknown>, + ) -> Result { + crate::xaml_application::create_xaml_application_with_factory( + metadata_provider, + launched_callback, + |name| self.activation_factory(name), + ) + } + + pub(crate) fn retain_factory( + &'static self, + class_name: &HSTRING, + factory: &IActivationFactory, + fallback: &mut Option, + ) -> Result<()> { + // A COM object's address is heap storage, not an address in its DLL. + // The typed factory vtable remains valid while the factory is alive. + let implementation = VerifiedModule::from_reference(ModuleReference::from_address( + std::ptr::from_ref(factory.vtable()).cast(), + )?)?; + validate_fallback(&implementation, fallback)?; + let xaml = match implementation.identity.kind { + ModuleKind::Xaml => None, + ModuleKind::Controls => { + if class_name == "Microsoft.UI.Xaml.Application" { + return Err(invalid_module( + "WinUI Application factory is not implemented by Microsoft.UI.Xaml.dll", + ) + .into()); + } + let path = implementation + .identity + .path + .with_file_name(ModuleKind::Xaml.name()); + let reference = match ModuleReference::from_path(&path) { + Ok(reference) => reference, + Err(error) + if error.code() + == windows_core::HRESULT::from_win32(ERROR_MOD_NOT_FOUND.0) => + { + // A metadata provider can load Controls before XAML. + // Resolve the real Application factory through the same + // activation policy, not an arbitrary DLL search path. + self.activation_factory(&HSTRING::from("Microsoft.UI.Xaml.Application"))?; + ModuleReference::from_path(&path)? + } + Err(error) => return Err(error.into()), + }; + let module = VerifiedModule::from_reference(reference)?; + if module.identity.kind != ModuleKind::Xaml || module.identity.path != path { + return Err(invalid_module( + "WinUI's loaded XAML dependency has a different path", + ) + .into()); + } + Some(module) + } + }; + self.publish(implementation, xaml, fallback) + .map_err(Into::into) + } + + fn publish( + &self, + implementation: VerifiedModule, + xaml: Option, + fallback: &mut Option, + ) -> windows_core::Result<()> { + validate_fallback(&implementation, fallback)?; + + let required = xaml.as_ref().unwrap_or(&implementation); + let mut modules = self + .modules + .lock() + .map_err(|_| invalid_module("WinUI module ownership lock was poisoned"))?; + modules.validate(required)?; + if fallback.is_some() { + modules.validate(&implementation)?; + } + + let mut redundant = Vec::new(); + // Validate the entire transaction before taking the fallback's only + // loader reference. On error it must outlive the caller's factory. + if let Some(reference) = fallback.take() { + redundant.push(modules.insert(VerifiedModule { + identity: implementation.identity.clone(), + reference, + })); + } + if let Some(xaml) = xaml { + redundant.push(modules.insert(xaml)); + } else { + redundant.push(modules.insert(implementation)); + } + drop(modules); + drop(redundant); + Ok(()) + } + + #[cfg(any(test, feature = "test-hooks"))] + pub fn retained_module_paths(&self) -> windows_core::Result> { + let modules = self + .modules + .lock() + .map_err(|_| invalid_module("WinUI module ownership lock was poisoned"))?; + Ok([&modules.xaml, &modules.controls] + .into_iter() + .flatten() + .map(|module| module.identity.path.clone()) + .collect()) + } + + #[cfg(feature = "test-hooks")] + pub fn owned_reference_count(&self) -> usize { + OWNED_REFERENCES.load(std::sync::atomic::Ordering::SeqCst) + } +} + +fn validate_fallback( + implementation: &VerifiedModule, + fallback: &Option, +) -> windows_core::Result<()> { + if fallback + .as_ref() + .is_some_and(|module| module.handle != implementation.reference.handle) + { + Err(invalid_module( + "WinUI fallback factory is not implemented by the DLL that returned it", + )) + } else { + Ok(()) + } +} + +fn is_winui_class(name: &HSTRING) -> bool { + let name = name.to_string(); + name.strip_prefix("Microsoft.UI.Xaml.") + .is_some_and(|suffix| !suffix.is_empty() && !suffix.contains('\0')) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ModuleKind { + Xaml, + Controls, +} + +impl ModuleKind { + fn name(self) -> &'static str { + match self { + Self::Xaml => "Microsoft.UI.Xaml.dll", + Self::Controls => "Microsoft.UI.Xaml.Controls.dll", + } + } + + fn from_path(path: &Path) -> windows_core::Result { + let name = path.file_name().and_then(|name| name.to_str()); + [Self::Xaml, Self::Controls] + .into_iter() + .find(|kind| name.is_some_and(|name| name.eq_ignore_ascii_case(kind.name()))) + .filter(|_| path.is_absolute()) + .ok_or_else(|| { + invalid_module(format!( + "WinUI activation factory has an unrecognized implementation module: {}", + path.display() + )) + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ModuleIdentity { + kind: ModuleKind, + path: PathBuf, +} + +struct VerifiedModule { + identity: ModuleIdentity, + reference: ModuleReference, +} + +impl VerifiedModule { + fn from_reference(reference: ModuleReference) -> windows_core::Result { + let path = reference.path()?; + Ok(Self { + identity: ModuleIdentity { + kind: ModuleKind::from_path(&path)?, + path, + }, + reference, + }) + } +} + +struct Modules { + controls: Option, + xaml: Option, +} + +impl Modules { + fn slot(&mut self, kind: ModuleKind) -> &mut Option { + match kind { + ModuleKind::Xaml => &mut self.xaml, + ModuleKind::Controls => &mut self.controls, + } + } + + fn validate(&mut self, candidate: &VerifiedModule) -> windows_core::Result<()> { + if let Some(existing) = self.slot(candidate.identity.kind) { + if existing.identity != candidate.identity + || existing.reference.handle != candidate.reference.handle + { + return Err(invalid_module(format!( + "WinUI implementation cannot change within a process: {} -> {}", + existing.identity.path.display(), + candidate.identity.path.display() + ))); + } + } + Ok(()) + } + + fn insert(&mut self, candidate: VerifiedModule) -> Option { + let slot = self.slot(candidate.identity.kind); + if slot.is_some() { + Some(candidate) + } else { + *slot = Some(candidate); + None + } + } +} + +pub(crate) struct ModuleReference { + handle: HMODULE, + #[cfg(test)] + released: Option>, +} + +// A loader reference has no apartment affinity. Publication only shares the +// immutable handle; COM factories are never stored in this owner. +unsafe impl Send for ModuleReference {} +unsafe impl Sync for ModuleReference {} + +impl ModuleReference { + /// Adopt exactly one successful LoadLibrary/GetModuleHandleEx reference. + pub(crate) unsafe fn adopt(handle: HMODULE) -> Self { + #[cfg(feature = "test-hooks")] + OWNED_REFERENCES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Self { + handle, + #[cfg(test)] + released: None, + } + } + + fn from_address(address: *const std::ffi::c_void) -> windows_core::Result { + let mut handle = HMODULE::default(); + unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + PCWSTR(address.cast()), + &mut handle, + ) + } + .map_err(|error| { + Error::new( + error.code(), + format!("Cannot retain WinUI factory implementation: {error}"), + ) + })?; + Ok(unsafe { Self::adopt(handle) }) + } + + fn from_path(path: &Path) -> windows_core::Result { + let mut handle = HMODULE::default(); + unsafe { GetModuleHandleExW(0, &HSTRING::from(path.as_os_str()), &mut handle) }.map_err( + |error| { + Error::new( + error.code(), + format!( + "Cannot retain WinUI's already-loaded dependency {}: {error}", + path.display() + ), + ) + }, + )?; + Ok(unsafe { Self::adopt(handle) }) + } + + fn path(&self) -> windows_core::Result { + let mut buffer = vec![0; 260]; + loop { + let length = unsafe { GetModuleFileNameW(Some(self.handle), &mut buffer) } as usize; + if length == 0 { + return Err(Error::from_thread()); + } + if length < buffer.len() { + return Ok(PathBuf::from(OsString::from_wide(&buffer[..length]))); + } + if buffer.len() >= 32768 { + return Err(invalid_module( + "WinUI implementation module path is too long", + )); + } + buffer.resize((buffer.len() * 2).min(32768), 0); + } + } +} + +impl Drop for ModuleReference { + fn drop(&mut self) { + #[cfg(test)] + if let Some(released) = &self.released { + released.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + return; + } + if let Err(error) = unsafe { FreeLibrary(self.handle) } { + eprintln!("[dynwinrt] WinUI module candidate cleanup failed: {error}"); + } else { + #[cfg(feature = "test-hooks")] + OWNED_REFERENCES.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } + } +} + +fn invalid_module(message: impl AsRef) -> Error { + Error::new(E_UNEXPECTED, message.as_ref()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Arc, Barrier, + atomic::{AtomicUsize, Ordering}, + }; + + fn reference(handle: usize, released: &Arc) -> ModuleReference { + ModuleReference { + handle: HMODULE(handle as *mut std::ffi::c_void), + released: Some(Arc::clone(released)), + } + } + + fn module(kind: ModuleKind, released: &Arc) -> VerifiedModule { + VerifiedModule { + identity: ModuleIdentity { + kind, + path: Path::new(r"C:\runtime").join(kind.name()), + }, + reference: reference( + match kind { + ModuleKind::Xaml => 1, + ModuleKind::Controls => 2, + }, + released, + ), + } + } + + #[test] + fn policy_requires_an_actual_winui_class_name() { + for name in [ + "Windows.Foundation.Uri", + "Microsoft.UI.Dispatching.DispatcherQueue", + "Microsoft.UI.Xaml", + "Microsoft.UI.Xaml.", + "Microsoft.UI.XamlFake.Application", + "Microsoft.UI.Xaml.Application\0bad", + ] { + assert!(!is_winui_class(&HSTRING::from(name)), "{name}"); + } + for name in [ + "Microsoft.UI.Xaml.Application", + "Microsoft.UI.Xaml.Controls.Button", + "Microsoft.UI.Xaml.XamlTypeInfo.XamlControlsXamlMetaDataProvider", + ] { + assert!(is_winui_class(&HSTRING::from(name)), "{name}"); + } + } + + #[test] + fn identity_requires_recognized_absolute_module_path() { + assert_eq!( + ModuleKind::from_path(Path::new(r"C:\runtime\microsoft.ui.xaml.DLL")).unwrap(), + ModuleKind::Xaml + ); + for path in [ + r"Microsoft.UI.Xaml.dll", + r"C:\runtime\Microsoft.UI.Xaml.dll.fake", + r"C:\runtime\combase.dll", + r"C:\runtime\Microsoft.UI.Xaml.Resources.dll", + ] { + assert!(ModuleKind::from_path(Path::new(path)).is_err()); + } + } + + #[test] + fn acquisition_rejects_heap_addresses_and_missing_loaded_dependencies() { + let heap = Box::new(0usize); + assert!(ModuleReference::from_address(std::ptr::from_ref(heap.as_ref()).cast()).is_err()); + assert!( + ModuleReference::from_path(Path::new(r"C:\dynwinrt-not-loaded\Microsoft.UI.Xaml.dll")) + .is_err() + ); + } + + #[test] + fn plain_activation_never_publishes_winui_modules() { + fn require_send_sync() {} + require_send_sync::(); + static OWNER: WinUiProcessModules = WinUiProcessModules::new(); + std::thread::spawn(|| { + use windows::Win32::System::WinRT::{ + RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize, + }; + unsafe { RoInitialize(RO_INIT_MULTITHREADED) }.unwrap(); + let result = OWNER.activation_factory(&HSTRING::from("Windows.Foundation.Uri")); + assert!(OWNER.retained_module_paths().unwrap().is_empty()); + drop(result.unwrap()); + unsafe { RoUninitialize() }; + }) + .join() + .unwrap(); + } + + #[test] + fn repeated_factories_retain_one_reference_not_com_objects() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + for _ in 0..8 { + owner + .publish(module(ModuleKind::Xaml, &released), None, &mut None) + .unwrap(); + } + assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + assert_eq!(released.load(Ordering::SeqCst), 7); + drop(owner); + assert_eq!(released.load(Ordering::SeqCst), 8); + } + + #[test] + fn fallback_reference_is_transferred_and_duplicate_loads_are_released() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + for _ in 0..8 { + let mut fallback = Some(reference(1, &released)); + owner + .publish(module(ModuleKind::Xaml, &released), None, &mut fallback) + .unwrap(); + assert!(fallback.is_none()); + } + assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + assert_eq!(released.load(Ordering::SeqCst), 15); + drop(owner); + assert_eq!(released.load(Ordering::SeqCst), 16); + } + + #[test] + fn normal_controls_factory_does_not_retain_controls() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + owner + .publish( + module(ModuleKind::Controls, &released), + Some(module(ModuleKind::Xaml, &released)), + &mut None, + ) + .unwrap(); + assert_eq!( + owner.retained_module_paths().unwrap(), + [PathBuf::from(r"C:\runtime\Microsoft.UI.Xaml.dll")] + ); + assert_eq!(released.load(Ordering::SeqCst), 1); + } + + #[test] + fn controls_fallback_retains_one_reference_per_required_module() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + for _ in 0..4 { + let mut fallback = Some(reference(2, &released)); + owner + .publish( + module(ModuleKind::Controls, &released), + Some(module(ModuleKind::Xaml, &released)), + &mut fallback, + ) + .unwrap(); + assert!(fallback.is_none()); + } + assert_eq!(owner.retained_module_paths().unwrap().len(), 2); + assert_eq!(released.load(Ordering::SeqCst), 10); + drop(owner); + assert_eq!(released.load(Ordering::SeqCst), 12); + } + + #[test] + fn identity_mismatch_keeps_fallback_alive_and_does_not_poison_retry() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + let mut fallback = Some(reference(3, &released)); + assert!( + owner + .publish(module(ModuleKind::Xaml, &released), None, &mut fallback) + .is_err() + ); + assert!(fallback.is_some()); + assert!(owner.retained_module_paths().unwrap().is_empty()); + assert_eq!(released.load(Ordering::SeqCst), 1); + drop(fallback.take()); + fallback = Some(reference(1, &released)); + owner + .publish(module(ModuleKind::Xaml, &released), None, &mut fallback) + .unwrap(); + assert!(fallback.is_none()); + assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + } + + #[test] + fn module_replacement_fails_without_partially_publishing_fallback() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + owner + .publish(module(ModuleKind::Xaml, &released), None, &mut None) + .unwrap(); + let mut replacement = module(ModuleKind::Xaml, &released); + replacement.identity.path = PathBuf::from(r"C:\other\Microsoft.UI.Xaml.dll"); + let mut fallback = Some(reference(2, &released)); + assert!( + owner + .publish( + module(ModuleKind::Controls, &released), + Some(replacement), + &mut fallback + ) + .is_err() + ); + assert!(fallback.is_some()); + assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + } + + #[test] + fn concurrent_publish_keeps_only_one_owned_reference() { + let owner = Arc::new(WinUiProcessModules::new()); + let released = Arc::new(AtomicUsize::new(0)); + let ready = Arc::new(Barrier::new(8)); + let threads = (0..8) + .map(|_| { + let owner = Arc::clone(&owner); + let released = Arc::clone(&released); + let ready = Arc::clone(&ready); + std::thread::spawn(move || { + let candidate = module(ModuleKind::Xaml, &released); + ready.wait(); + owner.publish(candidate, None, &mut None).unwrap(); + }) + }) + .collect::>(); + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + assert_eq!(released.load(Ordering::SeqCst), 7); + drop(owner); + assert_eq!(released.load(Ordering::SeqCst), 8); + } +} diff --git a/crates/dynwinrt/src/xaml_application.rs b/crates/dynwinrt/src/xaml_application.rs index 7a176c65..407ebe88 100644 --- a/crates/dynwinrt/src/xaml_application.rs +++ b/crates/dynwinrt/src/xaml_application.rs @@ -1231,11 +1231,22 @@ fn compose_xaml_application( pub fn create_xaml_application( metadata_provider: &IUnknown, launched_callback: Option<&IUnknown>, +) -> Result { + create_xaml_application_with_factory( + metadata_provider, + launched_callback, + crate::ro_get_activation_factory_2, + ) +} + +pub(crate) fn create_xaml_application_with_factory( + metadata_provider: &IUnknown, + launched_callback: Option<&IUnknown>, + activation_factory: impl FnOnce(&HSTRING) -> Result, ) -> Result { enable_per_monitor_v2()?; let provider = query_interface(metadata_provider, &IID_IXAML_METADATA_PROVIDER)?; - let activation_factory = - crate::ro_get_activation_factory_2(&HSTRING::from("Microsoft.UI.Xaml.Application"))?; + let activation_factory = activation_factory(&HSTRING::from("Microsoft.UI.Xaml.Application"))?; let factory = activation_factory .as_object() .expect("activation factory must be an object"); diff --git a/samples/python/winui-hello-world/README.md b/samples/python/winui-hello-world/README.md index 44bb4101..d2b38bff 100644 --- a/samples/python/winui-hello-world/README.md +++ b/samples/python/winui-hello-world/README.md @@ -41,3 +41,11 @@ installed runtime. Use `-Smoke` to create the window and controls, update the text once, print `python-winui-hello-ok`, and exit automatically. + +The runtime keeps a single owned reference to the WinUI XAML implementation +DLL from its first use until process termination, including cleanup on MTA +threads that outlive the UI apartment. This does not replace the sample's +event unsubscription, projected object release, or balanced `RoApartment`. +The DLL and its module-level static state are not unloaded when the window +closes; in-process WinUI module unloading/hot replacement is not supported. +See [Python WinUI lifetime policy](../../../bindings/py/README.md#experimental-winui-support). diff --git a/tests/e2e/fixtures/winui_activation.cpp b/tests/e2e/fixtures/winui_activation.cpp new file mode 100644 index 00000000..191582bd --- /dev/null +++ b/tests/e2e/fixtures/winui_activation.cpp @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#include +#include +#include +#include +#include +#include + +using namespace Microsoft::WRL; +using Microsoft::WRL::Wrappers::HStringReference; + +class Factory final : public ActivationFactory<> +{ +public: + HRESULT STDMETHODCALLTYPE ActivateInstance(IInspectable** result) override + { + if (!result) + return E_POINTER; + *result = nullptr; + return E_NOTIMPL; + } +}; + +extern "C" __declspec(dllexport) HRESULT WINAPI DllGetActivationFactory( + HSTRING name, IActivationFactory** result) +{ + if (!result) + return E_POINTER; + *result = nullptr; + if (wcscmp(WindowsGetStringRawBuffer(name, nullptr), L"Microsoft.UI.Xaml.DynWinRTFixture")) + return CLASS_E_CLASSNOTAVAILABLE; + + wchar_t mode[32]{}; + GetEnvironmentVariableW(L"DYNWINRT_WINUI_FIXTURE_MODE", mode, ARRAYSIZE(mode)); + if (!wcscmp(mode, L"fail")) + return E_ACCESSDENIED; + if (!wcscmp(mode, L"null")) + return S_OK; + if (!wcscmp(mode, L"forward")) + return RoGetActivationFactory( + HStringReference(L"Windows.Foundation.Uri").Get(), IID_PPV_ARGS(result)); + auto factory = Make(); + return factory ? factory.CopyTo(result) : E_OUTOFMEMORY; +} + +extern "C" __declspec(dllexport) unsigned long WINAPI FixtureObjectCount() +{ + return Module::GetModule().GetObjectCount(); +} diff --git a/tests/e2e/runners/py_winui_lifetime.py b/tests/e2e/runners/py_winui_lifetime.py new file mode 100644 index 00000000..7791711b --- /dev/null +++ b/tests/e2e/runners/py_winui_lifetime.py @@ -0,0 +1,278 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Run the unchanged Hello World with observable native lifetime boundaries.""" + +import argparse +import asyncio +import ctypes +import hashlib +import importlib.util +import json +from pathlib import Path +import sys +import threading + + +def run(sample_root, mode, require_owner_hook): + sys.path.insert(0, str(sample_root)) + import dynwinrt as dw + from dynwinrt import dynwinrt as native + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] + kernel.GetModuleHandleW.restype = ctypes.c_void_p + kernel.GetModuleFileNameW.argtypes = [ + ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint32 + ] + kernel.GetModuleFileNameW.restype = ctypes.c_uint32 + kernel.GetProcAddress.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + kernel.GetProcAddress.restype = ctypes.c_void_p + owner_paths = getattr(native, "_test_winui_module_paths", None) + if require_owner_hook and owner_paths is None: + raise RuntimeError("This case requires a test-hooks wheel") + + def record(event, **values): + print(json.dumps({"event": event, "thread": threading.get_native_id(), **values}), flush=True) + + def snapshot(phase): + state = { + "xaml_loaded": bool(kernel.GetModuleHandleW("Microsoft.UI.Xaml.dll")), + "controls_loaded": bool(kernel.GetModuleHandleW("Microsoft.UI.Xaml.Controls.dll")), + } + if owner_paths is not None: + state["owned_modules"] = owner_paths() + state["owned_loader_references"] = native._test_winui_owned_references() + assert state["owned_loader_references"] == len(state["owned_modules"]) + record("modules", phase=phase, **state) + return state + + assert not snapshot("import")["xaml_loaded"] + if owner_paths is not None: + assert owner_paths() == [] + app_path = sample_root / "app.py" + record( + "inputs", mode=mode, python=sys.version, executable=sys.executable, + app_sha256=hashlib.sha256(app_path.read_bytes()).hexdigest(), + pyd_sha256=hashlib.sha256(Path(native.__file__).read_bytes()).hexdigest(), + ) + spec = importlib.util.spec_from_file_location("hello_lifetime", app_path) + if spec is None or spec.loader is None: + raise RuntimeError(f"Cannot load {app_path}") + app = importlib.util.module_from_spec(spec) + spec.loader.exec_module(app) + + if mode == "provider-error": + context = dw.init_winappsdk(2, 3) + try: + with dw.RoApartment(0), dw.projected_lifetime_scope() as scope: + factory = dw.DynWinRTValue.activation_factory( + "Microsoft.UI.Xaml.XamlTypeInfo.XamlControlsXamlMetaDataProvider" + ) + try: + provider = scope.track(factory.activate()) + assert not provider.is_null() + state = snapshot("provider-before-application") + assert state["xaml_loaded"] + raise ValueError("intentional provider setup failure") + finally: + factory.release() + except ValueError as error: + assert str(error) == "intentional provider setup failure" + assert provider.is_null() + finally: + del context + state = snapshot("provider-error-cleanup-finished") + assert state["xaml_loaded"] and not state["controls_loaded"] + if owner_paths is not None: + assert len(owner_paths()) == 1 + record("winui-lifetime-ok", mode=mode) + return + + if mode == "default-async": + def use_default_async(): + with dw.RoApartment(1): + async def read_file(): + file_type = dw.DynWinRTType.runtime_class( + "Windows.Storage.StorageFile", + dw.DynWinRTType.interface(dw.WinGUID.parse( + "FA3F6186-4214-428C-A64C-14C9AC7315EA" + )), + ) + iid = dw.WinGUID.parse("5984C710-DAF2-43C8-8BB4-A4D3EACFD03F") + statics = dw.DynWinRTType.register_interface("IStorageFileStatics", iid) + statics.add_method( + "GetFileFromPathAsync", + dw.DynWinRTMethodSig().add_in(dw.DynWinRTType.hstring()).add_out( + dw.DynWinRTType.i_async_operation(file_type) + ), + ) + factory = dw.DynWinRTValue.activation_factory("Windows.Storage.StorageFile") + factory_view = factory.cast(iid) + try: + raw = statics.method(6).invoke(factory_view, [ + dw.DynWinRTValue.from_hstring(str(app_path)) + ]) + operation = native._DynWinRTAsync(raw, lambda value: value) + raw.release() + try: + result = await operation + assert not result.is_null() + result.release() + finally: + operation.release() + finally: + factory_view.release() + factory.release() + asyncio.run(read_file()) + record("default-async-completed", runtime_joined=False) + use_default_async() + + apartment = app.RoApartment + scope = app.projected_lifetime_scope + start = app.Application.start + observed = {"scope": False, "sta": False} + + class ApartmentTrace: + def __init__(self, apartment_type): + self.inner = apartment(apartment_type) + + def __enter__(self): + return self.inner.__enter__() + + def __exit__(self, *exception): + assert observed["scope"] + record("sta-uninitialize-begin") + result = self.inner.__exit__(*exception) + observed["sta"] = True + record("sta-uninitialize-end") + snapshot("sta-finished") + return result + + class ScopeTrace: + def __init__(self): + self.inner = scope() + + def __enter__(self): + return self.inner.__enter__() + + def __exit__(self, *exception): + count = len(self.inner._registry) + record("projected-release-begin", count=count) + result = self.inner.__exit__(*exception) + assert self.inner.disposed and not self.inner._registry + assert count > 0 + observed["scope"] = True + record("projected-release-end", count=count, remaining=0) + return result + + def traced_start(callback): + for _ in range(5): + factory = dw.DynWinRTValue.activation_factory("Microsoft.UI.Xaml.Application") + factory.release() + state = snapshot("before-start") + assert state["xaml_loaded"] + if owner_paths is not None: + assert len(owner_paths()) == 1 + result = start(callback) + record("application-start-returned") + if mode == "body-error": + raise ValueError("intentional post-start body error") + return result + + app.RoApartment = ApartmentTrace + app.projected_lifetime_scope = ScopeTrace + app.Application.start = staticmethod(traced_start) + + def hello(): + try: + app.run(True, 2, 3) + except ValueError as error: + if mode != "body-error" or str(error) != "intentional post-start body error": + raise + record("expected-body-error") + assert observed == {"scope": True, "sta": True} + + if mode in ("managed", "external"): + ready, finish = threading.Event(), threading.Event() + errors = [] + + def hold_mta(): + record("mta-initialized", owner=mode) + ready.set() + if not finish.wait(60): + raise TimeoutError("STA did not finish") + assert observed["sta"] + record("mta-uninitialize-begin", owner=mode) + + def worker(): + try: + if mode == "managed": + with dw.RoApartment(1): + hold_mta() + else: + com = ctypes.WinDLL("combase") + com.RoInitialize.argtypes = [ctypes.c_uint32] + com.RoInitialize.restype = ctypes.c_long + com.RoUninitialize.argtypes = [] + com.RoUninitialize.restype = None + hr = com.RoInitialize(1) + assert hr >= 0, hr + try: + hold_mta() + finally: + com.RoUninitialize() + record("mta-uninitialize-end", owner=mode) + except BaseException as error: + errors.append(error) + ready.set() + + thread = threading.Thread(target=worker) + thread.start() + try: + assert ready.wait(10) + if errors: + raise errors[0] + hello() + finally: + finish.set() + thread.join(60) + assert not thread.is_alive() + if errors: + raise errors[0] + record("mta-joined") + elif mode == "tokio": + events = native._test_winui_with_mta_runtime(hello) + started = sorted(thread for started, thread in events if started) + stopped = sorted(thread for started, thread in events if not started) + assert len(started) >= 3 and started == stopped, events + record("tokio-stopped-and-joined", started=started, stopped=stopped) + else: + hello() + + state = snapshot("all-explicit-cleanup-finished") + assert state["xaml_loaded"] + if mode != "default-async": + assert not state["controls_loaded"] + if owner_paths is not None: + assert len(owner_paths()) == 1 + xaml = kernel.GetModuleHandleW("Microsoft.UI.Xaml.dll") + can_unload = kernel.GetProcAddress(xaml, b"DllCanUnloadNow") + assert can_unload + hr = ctypes.WINFUNCTYPE(ctypes.c_long)(can_unload)() + assert hr in (0, 1), hr + record("xaml-code-call-after-cleanup", hresult=hr) + record("winui-lifetime-ok", mode=mode) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--sample-root", type=Path, required=True) + parser.add_argument( + "--mode", + choices=("plain", "managed", "external", "tokio", "default-async", "body-error", "provider-error"), + default="plain", + ) + parser.add_argument("--require-owner-hook", action="store_true") + args = parser.parse_args() + run(args.sample_root.resolve(), args.mode, args.require_owner_hook) From 221f947bd90dd564b79df1f3a200bcba16517452 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 16 Sep 2026 16:10:36 +0800 Subject: [PATCH 2/2] Use native module identity for WinUI path aliases Let the Windows loader resolve the full dependency path and compare retained HMODULE values instead of case-sensitive path spellings. Keep rejecting distinct runtime modules and add real loader regressions for filename and directory casing. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 6 +- bindings/py/tests/test_winui_lifetime.py | 73 ++++++++++++++++++++++ crates/dynwinrt/src/winui_module.rs | 77 ++++++++++++++++++------ tests/e2e/fixtures/winui_activation.cpp | 4 +- 4 files changed, 138 insertions(+), 22 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index 1238b64b..cb6476cc 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -326,7 +326,9 @@ application supplies its own provider. Python retains the validated WinUI implementation DLL after its first actual WinUI activation until the process terminates. One named native owner keeps one ordinary loader reference to `Microsoft.UI.Xaml.dll`; repeated activation -does not accumulate references. If WinUI activation requires the DLL-probing +does not accumulate references. Retained native module handles determine +identity, so legal differences in path spelling or casing do not imply a +different runtime. If WinUI activation requires the DLL-probing fallback, its successful loader reference is transferred to the same owner (one reference per required implementation DLL), rather than leaked per call. Imports, ordinary WinRT activation, and COM apartment initialization do not @@ -456,6 +458,8 @@ From a matching-architecture Visual Studio developer shell, build `tests\e2e\fixtures\winui_activation.cpp` with `cl /LD /EHsc /std:c++17 winui_activation.cpp /link runtimeobject.lib /OUT:Microsoft.UI.Xaml.dll` in a private output directory and set `DYNWINRT_WINUI_FIXTURE_DIR` to it. +Copy that fixture DLL as `Microsoft.UI.Xaml.Controls.dll` in the same directory +for the dependency path-spelling regressions. That SDK-typed factory tests actual loader-reference transfer, concurrent fallback activation, failed/null factories, identity mismatch, and retry without requiring WinUI installation. Do not use this fixture DLL in the real diff --git a/bindings/py/tests/test_winui_lifetime.py b/bindings/py/tests/test_winui_lifetime.py index b4db1b88..b2999868 100644 --- a/bindings/py/tests/test_winui_lifetime.py +++ b/bindings/py/tests/test_winui_lifetime.py @@ -136,6 +136,79 @@ def activate(): """, cwd=fixture_dir, env={"DYNWINRT_WINUI_FIXTURE_MODE": failure}) +@pytest.mark.parametrize("spelling", ["canonical", "lowercase", "uppercase", "directory-case"]) +def test_controls_factory_accepts_same_xaml_module_path_spelling(spelling): + fixture_dir = os.environ.get("DYNWINRT_WINUI_FIXTURE_DIR") + if not fixture_dir: + pytest.skip("requires the SDK-ABI WinUI activation DLL fixture") + for name in ("Microsoft.UI.Xaml.dll", "Microsoft.UI.Xaml.Controls.dll"): + assert (Path(fixture_dir) / name).is_file() + run_child(""" + import ctypes + import os + from pathlib import Path + import dynwinrt as dw + from dynwinrt.dynwinrt import _test_winui_module_paths, _test_winui_owned_references + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.LoadLibraryW.argtypes = [ctypes.c_wchar_p] + kernel.LoadLibraryW.restype = ctypes.c_void_p + kernel.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel.FreeLibrary.restype = ctypes.c_int + kernel.SetDllDirectoryW.argtypes = [ctypes.c_wchar_p] + kernel.SetDllDirectoryW.restype = ctypes.c_int + kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] + kernel.GetModuleHandleW.restype = ctypes.c_void_p + kernel.GetModuleFileNameW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint32] + kernel.GetModuleFileNameW.restype = ctypes.c_uint32 + kernel.GetProcAddress.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + kernel.GetProcAddress.restype = ctypes.c_void_p + + canonical = Path.cwd() / "Microsoft.UI.Xaml.dll" + spelling = os.environ["DYNWINRT_WINUI_PATH_SPELLING"] + path = { + "canonical": str(canonical), + "lowercase": str(canonical.with_name("microsoft.ui.xaml.dll")), + "uppercase": str(canonical.with_name("MICROSOFT.UI.XAML.DLL")), + "directory-case": str(canonical.parent).swapcase() + "\\\\" + canonical.name, + }[spelling] + assert kernel.SetDllDirectoryW(os.getcwd()) + xaml = kernel.LoadLibraryW(path) + assert xaml, ctypes.WinError(ctypes.get_last_error()) + try: + assert kernel.GetModuleHandleW(str(canonical)) == xaml + reported = ctypes.create_unicode_buffer(32768) + assert kernel.GetModuleFileNameW(xaml, reported, len(reported)) + assert reported.value == path + assert _test_winui_owned_references() == 0 + with dw.RoApartment(1): + factory = dw.DynWinRTValue.activation_factory("Microsoft.UI.Xaml.DynWinRTFixture") + factory.release() + assert _test_winui_owned_references() == 1 + assert _test_winui_module_paths() == [reported.value] + for _ in range(4): + factory = dw.DynWinRTValue.activation_factory( + "Microsoft.UI.Xaml.Controls.DynWinRTFixture" + ) + factory.release() + assert kernel.GetModuleHandleW(str(canonical)) == xaml + assert _test_winui_owned_references() == 2 + paths = _test_winui_module_paths() + assert len(paths) == 2 and paths[0] == reported.value + for name in ("Microsoft.UI.Xaml.dll", "Microsoft.UI.Xaml.Controls.dll"): + handle = kernel.GetModuleHandleW(name) + assert handle + address = kernel.GetProcAddress(handle, b"FixtureObjectCount") + assert address + assert ctypes.WINFUNCTYPE(ctypes.c_ulong)(address)() == 0 + finally: + assert kernel.FreeLibrary(xaml) + assert kernel.SetDllDirectoryW(None) + assert kernel.GetModuleHandleW(str(canonical)) == xaml + assert _test_winui_owned_references() == 2 + """, cwd=fixture_dir, env={"DYNWINRT_WINUI_PATH_SPELLING": spelling}) + + @pytest.mark.parametrize( "mode", ["plain", "managed", "external", "tokio", "default-async", "body-error", "provider-error"] ) diff --git a/crates/dynwinrt/src/winui_module.rs b/crates/dynwinrt/src/winui_module.rs index 84a04c38..80b6e347 100644 --- a/crates/dynwinrt/src/winui_module.rs +++ b/crates/dynwinrt/src/winui_module.rs @@ -108,9 +108,11 @@ impl WinUiProcessModules { Err(error) => return Err(error.into()), }; let module = VerifiedModule::from_reference(reference)?; - if module.identity.kind != ModuleKind::Xaml || module.identity.path != path { + // The loader resolved the full sibling path; its reported + // spelling need not match the spelling used for lookup. + if module.identity.kind != ModuleKind::Xaml { return Err(invalid_module( - "WinUI's loaded XAML dependency has a different path", + "WinUI's loaded dependency is not Microsoft.UI.Xaml.dll", ) .into()); } @@ -228,7 +230,7 @@ impl ModuleKind { } } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug)] struct ModuleIdentity { kind: ModuleKind, path: PathBuf, @@ -267,9 +269,9 @@ impl Modules { fn validate(&mut self, candidate: &VerifiedModule) -> windows_core::Result<()> { if let Some(existing) = self.slot(candidate.identity.kind) { - if existing.identity != candidate.identity - || existing.reference.handle != candidate.reference.handle - { + // Owned references prevent HMODULE reuse. Paths are diagnostic, + // not identity: the same module can have different path spellings. + if existing.reference.handle != candidate.reference.handle { return Err(invalid_module(format!( "WinUI implementation cannot change within a process: {} -> {}", existing.identity.path.display(), @@ -500,6 +502,28 @@ mod tests { assert_eq!(released.load(Ordering::SeqCst), 8); } + #[test] + fn same_module_path_spellings_keep_one_reference() { + let released = Arc::new(AtomicUsize::new(0)); + let owner = WinUiProcessModules::new(); + for path in [ + r"C:\runtime\Microsoft.UI.Xaml.dll", + r"c:\RUNTIME\microsoft.ui.xaml.dll", + r"\\?\C:\runtime\Microsoft.UI.Xaml.dll", + ] { + let mut candidate = module(ModuleKind::Xaml, &released); + candidate.identity.path = PathBuf::from(path); + owner.publish(candidate, None, &mut None).unwrap(); + } + assert_eq!( + owner.retained_module_paths().unwrap(), + [PathBuf::from(r"C:\runtime\Microsoft.UI.Xaml.dll")] + ); + assert_eq!(released.load(Ordering::SeqCst), 2); + drop(owner); + assert_eq!(released.load(Ordering::SeqCst), 3); + } + #[test] fn fallback_reference_is_transferred_and_duplicate_loads_are_released() { let released = Arc::new(AtomicUsize::new(0)); @@ -585,20 +609,33 @@ mod tests { owner .publish(module(ModuleKind::Xaml, &released), None, &mut None) .unwrap(); - let mut replacement = module(ModuleKind::Xaml, &released); - replacement.identity.path = PathBuf::from(r"C:\other\Microsoft.UI.Xaml.dll"); - let mut fallback = Some(reference(2, &released)); - assert!( - owner - .publish( - module(ModuleKind::Controls, &released), - Some(replacement), - &mut fallback - ) - .is_err() - ); - assert!(fallback.is_some()); - assert_eq!(owner.retained_module_paths().unwrap().len(), 1); + for path in [ + r"C:\runtime\Microsoft.UI.Xaml.dll", + r"C:\other\microsoft.ui.xaml.dll", + ] { + let replacement = VerifiedModule { + identity: ModuleIdentity { + kind: ModuleKind::Xaml, + path: PathBuf::from(path), + }, + reference: reference(3, &released), + }; + let mut fallback = Some(reference(2, &released)); + assert!( + owner + .publish( + module(ModuleKind::Controls, &released), + Some(replacement), + &mut fallback + ) + .is_err() + ); + assert!(fallback.is_some()); + assert_eq!( + owner.retained_module_paths().unwrap(), + [PathBuf::from(r"C:\runtime\Microsoft.UI.Xaml.dll")] + ); + } } #[test] diff --git a/tests/e2e/fixtures/winui_activation.cpp b/tests/e2e/fixtures/winui_activation.cpp index 191582bd..d4c18c96 100644 --- a/tests/e2e/fixtures/winui_activation.cpp +++ b/tests/e2e/fixtures/winui_activation.cpp @@ -29,7 +29,9 @@ extern "C" __declspec(dllexport) HRESULT WINAPI DllGetActivationFactory( if (!result) return E_POINTER; *result = nullptr; - if (wcscmp(WindowsGetStringRawBuffer(name, nullptr), L"Microsoft.UI.Xaml.DynWinRTFixture")) + const auto className = WindowsGetStringRawBuffer(name, nullptr); + if (wcscmp(className, L"Microsoft.UI.Xaml.DynWinRTFixture") && + wcscmp(className, L"Microsoft.UI.Xaml.Controls.DynWinRTFixture")) return CLASS_E_CLASSNOTAVAILABLE; wchar_t mode[32]{};