From f48fc4b91df9106b207e6cfc17d920ce6e04cbaa Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 11:33:12 +0800 Subject: [PATCH] Fix IBuffer creation across apartment teardown Use a call-local Buffer factory instead of the windows static factory cache, whose vtable can be unloaded by RoUninitialize. Cover isolated STA/MTA lifetimes and preserve byte-copy and owner-release behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/README.md | 15 +++++ bindings/py/tests/test_ibuffer_apartment.py | 74 +++++++++++++++++++++ crates/dynwinrt/src/ibuffer.rs | 15 ++++- crates/dynwinrt/tests/ibuffer_apartment.rs | 56 ++++++++++++++++ 4 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 bindings/py/tests/test_ibuffer_apartment.py create mode 100644 crates/dynwinrt/tests/ibuffer_apartment.rs diff --git a/bindings/py/README.md b/bindings/py/README.md index 4ddc4924..1449550f 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -221,6 +221,21 @@ Both directions copy exactly `Length` bytes. Mutating the input or releasing the WinRT object does not change the returned `bytes`, and no native buffer pointer is exposed. +Byte conversion can be repeated in independent `RoApartment` scopes. Buffer +creation uses a call-local activation factory, so it does not retain a stale +factory across apartment teardown. Release native values before leaving their +apartment, or let `RoApartment` release its tracked owners: + +```python +from dynwinrt import DynWinRTValue, RoApartment + +for _ in range(2): + with RoApartment(): + value = DynWinRTValue.from_bytes(b"abc") + data = value.to_bytes() + value.release() +``` + Exceptions raised by Python event or delegate callbacks are reported through `sys.unraisablehook`. The originating WinRT invocation receives `0xA0EE4005` (`PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION`) instead of unconditional diff --git a/bindings/py/tests/test_ibuffer_apartment.py b/bindings/py/tests/test_ibuffer_apartment.py new file mode 100644 index 00000000..6b3f94e3 --- /dev/null +++ b/bindings/py/tests/test_ibuffer_apartment.py @@ -0,0 +1,74 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Isolate buffer regressions from pytest's process-lifetime COM initialization.""" + +import subprocess +import sys + +import pytest + + +@pytest.mark.parametrize("model", [0, 1]) +@pytest.mark.parametrize("scope", ["single", "separate"]) +@pytest.mark.parametrize("cleanup", ["release", "gc", "apartment"]) +def test_from_bytes_apartment_lifetime(model, scope, cleanup): + script = r""" +import ctypes +import gc +import sys +from dynwinrt import DynWinRTValue, RoApartment + +model, scope, cleanup = int(sys.argv[1]), sys.argv[2], sys.argv[3] +get_apartment = ctypes.WinDLL('combase').CoGetApartmentType +get_apartment.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] +get_apartment.restype = ctypes.c_long +escaped = [] + +def assert_uninitialized(): + apartment, qualifier = ctypes.c_int(), ctypes.c_int() + assert get_apartment(ctypes.byref(apartment), ctypes.byref(qualifier)) == -2147221008 + +def copy_bytes(): + for data in (b'abc', b'', bytearray(b'\x00\x01\xff\x80\x00')): + expected = bytes(data) + value = DynWinRTValue.from_bytes(data) + if isinstance(data, bytearray): + data[:] = b'\x09' * len(data) + copied = value.to_bytes() + if cleanup == 'release': + value.release() + assert value.is_released() + elif cleanup == 'apartment': + escaped.append(value) + del value + gc.collect() + assert copied == expected + +def assert_closed(): + assert_uninitialized() + assert all(value.is_released() for value in escaped) + escaped.clear() + +assert_uninitialized() +if scope == 'single': + with RoApartment(model): + for _ in range(3): + copy_bytes() + assert_closed() +else: + for _ in range(3): + with RoApartment(model): + copy_bytes() + assert_closed() +print('buffer-apartment-clean-exit', flush=True) +""" + result = subprocess.run( + [sys.executable, "-X", "faulthandler", "-c", script, str(model), scope, cleanup], + capture_output=True, + text=True, + timeout=45, + check=False, + ) + assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) + assert "buffer-apartment-clean-exit" in result.stdout diff --git a/crates/dynwinrt/src/ibuffer.rs b/crates/dynwinrt/src/ibuffer.rs index c28e1036..656d7d60 100644 --- a/crates/dynwinrt/src/ibuffer.rs +++ b/crates/dynwinrt/src/ibuffer.rs @@ -3,7 +3,7 @@ use std::ffi::c_void; -use windows::Storage::Streams::{Buffer, IBuffer}; +use windows::Storage::Streams::{Buffer, IBuffer, IBufferFactory}; use windows_core::{HRESULT, IUnknown, Interface}; use crate::{Error, Result, WinRTValue}; @@ -77,7 +77,18 @@ pub fn copy_from_ibuffer(value: &WinRTValue) -> Result> { pub fn copy_to_ibuffer(bytes: &[u8]) -> Result { let length = u32::try_from(bytes.len()).map_err(|_| Error::IBufferInputTooLarge(bytes.len()))?; - let buffer = Buffer::Create(length).map_err(Error::WindowsError)?; + // Buffer::Create caches a factory whose DLL can unload at RoUninitialize. + // Use the same activation loader, but keep the factory local to this call. + let buffer: Buffer = { + let factory = + windows_core::factory::().map_err(Error::WindowsError)?; + let mut result = std::ptr::null_mut(); + unsafe { + (factory.vtable().Create)(factory.as_raw(), length, &mut result) + .and_then(|| windows_core::Type::from_abi(result)) + } + .map_err(Error::WindowsError)? + }; let ibuffer: IBuffer = buffer.cast().map_err(Error::WindowsError)?; let (_access, destination) = query_byte_pointer(&ibuffer)?; diff --git a/crates/dynwinrt/tests/ibuffer_apartment.rs b/crates/dynwinrt/tests/ibuffer_apartment.rs new file mode 100644 index 00000000..e6ade9fe --- /dev/null +++ b/crates/dynwinrt/tests/ibuffer_apartment.rs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt::{copy_from_ibuffer, copy_to_ibuffer}; +use windows::Storage::Streams::IBuffer; +use windows::Win32::Foundation::CO_E_NOTINITIALIZED; +use windows::Win32::System::Com::{APTTYPE, APTTYPEQUALIFIER, CoGetApartmentType}; +use windows::Win32::System::WinRT::{ + RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, RoInitialize, RoUninitialize, +}; +use windows_core::Interface; + +struct Apartment; + +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { RoUninitialize() }; + } +} + +fn assert_uninitialized() { + let mut apartment = APTTYPE::default(); + let mut qualifier = APTTYPEQUALIFIER::default(); + let error = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); + assert_eq!(error.code(), CO_E_NOTINITIALIZED); +} + +// This executable must not share the unit tests' process-lifetime MTA. +#[test] +fn copied_buffers_survive_complete_apartment_teardown() -> dynwinrt::Result<()> { + assert_uninitialized(); + for model in [ + RO_INIT_MULTITHREADED, + RO_INIT_MULTITHREADED, + RO_INIT_SINGLETHREADED, + RO_INIT_SINGLETHREADED, + RO_INIT_MULTITHREADED, + ] { + { + unsafe { RoInitialize(model) }?; + let _apartment = Apartment; + for bytes in [b"abc".as_slice(), &[], &[0, 1, 0xff, 0x80, 0]] { + let value = copy_to_ibuffer(bytes)?; + let buffer: IBuffer = value.as_object().unwrap().cast()?; + assert_eq!(buffer.Length()?, bytes.len() as u32); + assert_eq!(buffer.Capacity()?, bytes.len() as u32); + let copied = copy_from_ibuffer(&value)?; + drop(buffer); + drop(value); + assert_eq!(copied, bytes); + } + } + assert_uninitialized(); + } + Ok(()) +}