From 9fbae2968e91c8350ce5a194d2613e1ecf29ed37 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 Oct 2023 17:11:36 +0200 Subject: [PATCH] Fix a bug in ComPtr.CopyTo when targeting same object --- src/TerraFX.Interop.Windows/ComPtr`1.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/TerraFX.Interop.Windows/ComPtr`1.cs b/src/TerraFX.Interop.Windows/ComPtr`1.cs index 58582622..4f1a3273 100644 --- a/src/TerraFX.Interop.Windows/ComPtr`1.cs +++ b/src/TerraFX.Interop.Windows/ComPtr`1.cs @@ -52,13 +52,25 @@ internal unsafe struct ComPtr : IDisposable } /// - /// Copies a given COM object into a target destination. + /// Copies a given COM object into a target destination, incrementing reference counts where needed. /// /// The input COM object to copy. /// The target destination for the COM object. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(T* obj, ref T* other) { + // We specifically need to increment the reference count on the source object before releasing the + // target object, to avoid issues in case source and destination were pointers to the same object + // (which can be the case even if the two pointers are not identical). To double check, a full check + // through an IUnknown* cast would be needed, but to avoid the extra QueryInterface call on both objects, + // we can just always do one AddRef call which avoids issues in all cases as well. The situation we need + // to avoid is that without a temporary copy, releasing the target object might actually destroy the + // object, causing the following AddRef call to AV. + if (obj is not null) + { + _ = ((IUnknown*)obj)->AddRef(); + } + T* pointer = other; if (pointer is not null) @@ -66,13 +78,11 @@ internal unsafe struct ComPtr : IDisposable _ = ((IUnknown*)pointer)->Release(); } - _ = ((IUnknown*)obj)->AddRef(); - other = obj; } /// - /// Writes a given COM object into a target (assumed uninitialized) destination. + /// Writes a given COM object into a target (assumed uninitialized) destination, incrementing reference counts where needed. /// /// The input COM object to copy. /// The target destination for the COM object.