Skip to content
Open
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
184 changes: 184 additions & 0 deletions src/Tests/ObjectLifetimeTests/AgileReferenceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.UI.Xaml;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WindowsRuntime.InteropServices;

namespace ObjectLifetimeTests;

[TestClass]
public sealed unsafe class AgileReferenceTests
{
[DllImport("ole32.dll", ExactSpelling = true)]
private static extern int CoInitializeEx(nint reserved, uint flags);

[DllImport("ole32.dll", ExactSpelling = true)]
private static extern void CoUninitialize();

[TestMethod]
public void CrossContextResolutionReleasesNativeReferences()
{
AsyncQueue queue = new(
((ObjectLifetimeTests.Lifted.App)Application.Current).m_window.DispatcherQueue);
nint pointer = 0;
WindowsRuntimeObjectReference reference = null;
Exception workerError = null;
using ManualResetEvent completed = new(false);

try
{
queue
.CallFromUIThread(() =>
{
pointer = (nint)NativeUnknown.Create();
reference = WindowsRuntimeComWrappersMarshal.CreateObjectReferenceUnsafe(
externalComObject: (void*)pointer,
iid: in NativeUnknown.Iid,
wrapperFlags: out _);
Assert.IsFalse(reference.IsFreeThreaded);
Assert.AreEqual(2, NativeUnknown.GetReferenceCount((void*)pointer));

Thread worker = new(() =>
{
int hresult = CoInitializeEx(0, 0);

try
{
Marshal.ThrowExceptionForHR(hresult);
reference.AddRefUnsafe();

try
{
nint resolved = (nint)reference.GetThisPtrUnsafe();
Assert.AreNotEqual(nint.Zero, resolved);
Assert.AreNotEqual(pointer, resolved);
}
finally
{
reference.ReleaseUnsafe();
}

reference.Dispose();
}
catch (Exception e)
{
workerError = e;
}
finally
{
if (hresult >= 0)
{
CoUninitialize();
}

completed.Set();
}
}) { IsBackground = true };
worker.Start();
})
.WaitForHandle(
handle: completed,
timeoutErrorMessage: "Cross-context resolution did not complete",
timeout: 15000)
.CallFromUIThread(() =>
{
Assert.IsNull(workerError);
reference = null;
})
.CollectUntilTrue(
fn: () => NativeUnknown.GetReferenceCount((void*)pointer) == 1,
timeoutMessage: "Cross-context resolution retained a native reference after collection")
.Run();
}
finally
{
queue.CallFromUIThread(() =>
{
reference?.Dispose();
NativeUnknown.Release((void*)pointer);
}).Run();
}
}

/// <summary>
/// Provides a native, reference-counted <c>IUnknown</c> using standard COM apartment marshalling.
/// </summary>
/// <remarks>
/// The object exposes neither <c>IAgileObject</c> nor <c>IMarshal</c>. Its state is allocated outside the managed
/// heap, so the count measures native ownership rather than managed reachability. The test retains the initial
/// reference until all observations and queued releases complete.
/// </remarks>
private static class NativeUnknown
{
public static readonly Guid Iid = new("00000000-0000-0000-C000-000000000046");

[FixedAddressValueType]
private static readonly IUnknownVftbl Vtable = new()
{
QueryInterface = &QueryInterface,
AddRef = &AddRef,
Release = &ReleaseUnmanaged
};

private struct Instance
{
public IUnknownVftbl* Vtable;
public int ReferenceCount;
}

public static void* Create()
{
Instance* instance = (Instance*)NativeMemory.AllocZeroed((nuint)sizeof(Instance));
instance->Vtable = (IUnknownVftbl*)Unsafe.AsPointer(in Vtable);
instance->ReferenceCount = 1;
return instance;
}

public static int GetReferenceCount(void* pointer) =>
Volatile.Read(ref ((Instance*)pointer)->ReferenceCount);

public static void Release(void* pointer)
{
if (pointer is not null)
{
_ = ReleaseCore((Instance*)pointer);
}
}

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
private static int QueryInterface(void* pointer, Guid* iid, void** result)
{
*result = null;

if (*iid != Iid)
{
return unchecked((int)0x80004002);
}

_ = Interlocked.Increment(ref ((Instance*)pointer)->ReferenceCount);
*result = pointer;
return 0;
}

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
private static uint AddRef(void* pointer) =>
(uint)Interlocked.Increment(ref ((Instance*)pointer)->ReferenceCount);

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvMemberFunction)])]
private static uint ReleaseUnmanaged(void* pointer) => ReleaseCore((Instance*)pointer);

private static uint ReleaseCore(Instance* instance)
{
int count = Interlocked.Decrement(ref instance->ReferenceCount);

if (count == 0)
{
NativeMemory.Free(instance);
}

return (uint)count;
}
}
}
77 changes: 77 additions & 0 deletions src/Tests/ObjectLifetimeTests/ObjectLifetimeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,83 @@ private static void MakeNull<T>(ref T o)
o = null;
}

[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void CommandBarFlyoutCommandsSurviveCollection(bool secondaryCommands)
{
CommandBarFlyout flyout = null;
WeakReference commandsReference = null;
WeakReference separatorReference = null;

_asyncQueue
.CallFromUIThread(() =>
{
flyout = new CommandBarFlyout();
IList<ICommandBarElement> commands = secondaryCommands
? flyout.SecondaryCommands
: flyout.PrimaryCommands;
AppBarSeparator separator = new AppBarSeparator();
commands.Add(separator);
commandsReference = new WeakReference(commands);
separatorReference = new WeakReference(separator);
})
.CollectUntilTrue(
fn: () => !commandsReference.IsAlive,
timeoutMessage: "The commands RCW was not collected")
.CallFromUIThread(() =>
{
Assert.IsInstanceOfType<AppBarSeparator>(separatorReference.Target);
IList<ICommandBarElement> commands = secondaryCommands
? flyout.SecondaryCommands
: flyout.PrimaryCommands;
Assert.AreEqual(1, commands.Count);
Assert.IsInstanceOfType<AppBarSeparator>(commands[0]);
})
.Run();

GC.KeepAlive(flyout);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static (WeakReference Grid, WeakReference Button, WeakReference Handler) CreateImportedEventCycle(
Panel host)
{
Grid grid = (Grid)XamlReader.Load("""
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button />
</Grid>
""");
Button button = (Button)grid.Children[0];
RoutedEventHandler handler = (_, _) => GC.KeepAlive(grid);
button.Click += handler;

// Give the parsed subtree a parent to clear its parser GC-root peg
host.Children.Add(grid);

return (new WeakReference(grid), new WeakReference(button), new WeakReference(handler));
}

[TestMethod]
public void ImportedRuntimeClassEventCycleIsCollected()
{
(WeakReference Grid, WeakReference Button, WeakReference Handler) references = default;

_asyncQueue
.CallFromUIThread(() => references = CreateImportedEventCycle(mainCanvas))
.CallFromUIThread(() => mainCanvas.Children.Remove((UIElement)references.Grid.Target))
.CollectUntilTrue(
fn: () => !references.Grid.IsAlive && !references.Button.IsAlive && !references.Handler.IsAlive,
timeoutMessage: "The imported Grid/Button event cycle was not collected")
.CallFromUIThread(() =>
{
Assert.IsNull(references.Grid.Target);
Assert.IsNull(references.Button.Target);
Assert.IsNull(references.Handler.Target);
})
.Run();
}

[TestMethod]
public void OpaqueDependencyObjectBindingsUseXamlMetadata()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ internal static unsafe class AgileObjectReferenceExtensions
/// <param name="objectReference">The source agile reference (this is expected to be from <see cref="AsAgileUnsafe"/>).</param>
/// <param name="iid">The IID to use to create the resulting non-agile reference.</param>
/// <returns>The resulting non-agile reference resolved from <paramref name="objectReference"/>.</returns>
public static WindowsRuntimeObjectReference FromAgileUnsafe(this WindowsRuntimeObjectReference objectReference, in Guid iid)
/// <remarks>
/// The returned object reference takes ownership of the COM reference produced by <c>IAgileReference.Resolve</c>.
/// </remarks>
public static WindowsRuntimeObjectReference FromAgileUnsafe(
this WindowsRuntimeObjectReference objectReference,
in Guid iid)
{
void* pObjectReference;
HRESULT hresult;
Expand All @@ -92,6 +97,6 @@ public static WindowsRuntimeObjectReference FromAgileUnsafe(this WindowsRuntimeO

// If 'Resolve' succeeded, the resulting object is guaranteed to be not 'null'.
// We don't need to do another 'QueryInterface', as 'Resolve' guarantees things.
return WindowsRuntimeObjectReference.CreateUnsafe(pObjectReference, in iid)!;
return WindowsRuntimeObjectReference.AttachUnsafe(ref pObjectReference, in iid)!;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,11 @@ internal static WindowsRuntimeObjectReference InitializeObjectReference(
/// Unlike <see cref="InitializeObjectReference"/>, this method assumes <paramref name="externalComObject"/> is exactly the
/// right interface pointer for <paramref name="iid"/>, and will therefore skip doing a <c>QueryInterface</c> call on it.
/// </para>
/// <para>
/// For reference-tracked objects, the tracker pointer is borrowed from the same native object and the returned
/// reference is the primary native reference of an RCW registered with <see cref="ComWrappers"/>. That registration owns
/// the primary tracker-source notification and its balancing release; additional queried references are tracked independently.
/// </para>
/// </remarks>
internal static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(
void* externalComObject,
Expand Down Expand Up @@ -405,10 +410,6 @@ internal static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(

if (isReferenceTracker.Succeeded)
{
// If we have a reference tracker, we should report an 'AddRef' on it,
// as we're wrapping the native object in a managed object reference.
_ = IReferenceTrackerVftbl.AddRefFromTrackerSourceUnsafe(referenceTracker);

// We can release the reference tracker, as it's implemented on the same native object,
// meaning it will remain alive anyway as long as the main object is also kept alive.
// This matches the handling of non aggregation scenarios above.
Expand All @@ -423,22 +424,33 @@ internal static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(
// We're going to store the input object, so increment its ref count
_ = IUnknownVftbl.AddRefUnsafe(externalComObject);

// 'ComWrappers' reports the primary RCW reference through 'AddRefFromTrackerSource' and
// balances it when disconnecting. Reporting it here too would hide a native root
// from the tracker's actual-versus-expected reference count comparison.
const CreateObjectReferenceFlags flags = CreateObjectReferenceFlags.PreventReleaseFromTrackerSourceOnDispose;

// Special case for free-threaded object references (see notes above)
if (isFreeThreaded)
{
return new FreeThreadedObjectReference(externalComObject, referenceTracker);
return new FreeThreadedObjectReference(externalComObject, referenceTracker, flags);
}

// Optimize the returned context-aware object reference if 'IInspectable' is requested
return iid == WellKnownWindowsInterfaceIIDs.IID_IInspectable
? new ContextAwareInspectableObjectReference(externalComObject, referenceTracker)
: new ContextAwareInterfaceObjectReference(externalComObject, referenceTracker, in iid);
? new ContextAwareInspectableObjectReference(externalComObject, referenceTracker, flags)
: new ContextAwareInterfaceObjectReference(externalComObject, referenceTracker, in iid, flags);
}

/// <inheritdoc cref="InitializeObjectReferenceUnsafe(void*, in Guid, CreateObjectReferenceMarshalingType)"/>
/// <remarks>
/// <para>
/// This method is equivalent to <see cref="InitializeObjectReferenceUnsafe(void*, in Guid, CreateObjectReferenceMarshalingType)"/>, with
/// the only difference that it takes ownership of <paramref name="externalComObject"/>, so callers don't need to release it on their end.
/// </para>
/// <para>
/// As with <see cref="InitializeObjectReferenceUnsafe(void*, in Guid, CreateObjectReferenceMarshalingType)"/>,
/// <see cref="ComWrappers"/> registration owns the primary tracker-source notification and its balancing release.
/// </para>
/// </remarks>
private static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(
ref void* externalComObject,
Expand Down Expand Up @@ -496,8 +508,6 @@ private static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(
// If we resolved a reference tracker, set it up (see notes above)
if (isReferenceTracker.Succeeded)
{
_ = IReferenceTrackerVftbl.AddRefFromTrackerSourceUnsafe(referenceTracker);

_ = IUnknownVftbl.ReleaseUnsafe(referenceTracker);
}
else
Expand All @@ -506,15 +516,18 @@ private static WindowsRuntimeObjectReference InitializeObjectReferenceUnsafe(
referenceTracker = null;
}

// 'ComWrappers' owns the tracker-source notification for the primary RCW reference
const CreateObjectReferenceFlags flags = CreateObjectReferenceFlags.PreventReleaseFromTrackerSourceOnDispose;

// Special case for free-threaded object references (see notes above)
if (isFreeThreaded)
{
return new FreeThreadedObjectReference(acquiredExternalComObject, referenceTracker);
return new FreeThreadedObjectReference(acquiredExternalComObject, referenceTracker, flags);
}

// Optimize the returned context-aware object reference (see notes above)
return iid == WellKnownWindowsInterfaceIIDs.IID_IInspectable
? new ContextAwareInspectableObjectReference(acquiredExternalComObject, referenceTracker)
: new ContextAwareInterfaceObjectReference(acquiredExternalComObject, referenceTracker, in iid);
? new ContextAwareInspectableObjectReference(acquiredExternalComObject, referenceTracker, flags)
: new ContextAwareInterfaceObjectReference(acquiredExternalComObject, referenceTracker, in iid, flags);
}
}
Loading