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
15 changes: 15 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
74 changes: 74 additions & 0 deletions bindings/py/tests/test_ibuffer_apartment.py
Original file line number Diff line number Diff line change
@@ -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
15 changes: 13 additions & 2 deletions crates/dynwinrt/src/ibuffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -77,7 +77,18 @@ pub fn copy_from_ibuffer(value: &WinRTValue) -> Result<Vec<u8>> {
pub fn copy_to_ibuffer(bytes: &[u8]) -> Result<WinRTValue> {
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::<Buffer, IBufferFactory>().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)?;

Expand Down
56 changes: 56 additions & 0 deletions crates/dynwinrt/tests/ibuffer_apartment.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
Loading