This fixes the following issue:
- Thread X holds the typelib cache list CS, and is iterating through the list. - Thread Y calls Release on the typelib interface, reference count hits 0, it's waiting for the cache list CS to remove this typelib. - Thread X finds the typelib in the cache list, returns it, exits the CS. - Thread Y enters now the CS, removes the typelib from the cache list, and proceeds to free all of the resources associated with the typelib. - Thread X tries to use the typelib, use after free.
The method used here to prevent incrementing the reference count is borrowed from MR !2752.
An alternative could be to decouple the actual typelib data from the `ITypeLib2` interface itself, e.g what gets stored into the typelib cache is just the data for the typelib, which would have its own private reference count locked behind the cache list CS. When the public `ITypeLib2` interface's reference count hits 0, it'd lock the typelib cache list CS, decrement the private reference count, and if the private reference count is 0 remove it from the list.
The alternative method would require major restructuring of the code, which is why I'd prefer to use the one in this MR.
-- v3: oleaut32: Lock ITypeLib2 interface reference count behind the typelib cache critical section on Release.
From: Connor McAdams cmcadams@codeweavers.com
This prevents an ITypeLib2 interface being returned from the typelib cache that is in the middle of being destroyed.
Signed-off-by: Connor McAdams cmcadams@codeweavers.com --- dlls/oleaut32/typelib.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/dlls/oleaut32/typelib.c b/dlls/oleaut32/typelib.c index fa512184182..1ff84aaa5fb 100644 --- a/dlls/oleaut32/typelib.c +++ b/dlls/oleaut32/typelib.c @@ -4712,7 +4712,10 @@ static ULONG WINAPI ITypeLib2_fnAddRef( ITypeLib2 *iface) static ULONG WINAPI ITypeLib2_fnRelease( ITypeLib2 *iface) { ITypeLibImpl *This = impl_from_ITypeLib2(iface); - ULONG ref = InterlockedDecrement(&This->ref); + ULONG ref; + + EnterCriticalSection(&cache_section); + ref = InterlockedDecrement(&This->ref);
TRACE("%p, refcount %lu.\n", iface, ref);
@@ -4728,10 +4731,8 @@ static ULONG WINAPI ITypeLib2_fnRelease( ITypeLib2 *iface) if(This->path) { TRACE("removing from cache list\n"); - EnterCriticalSection(&cache_section); if(This->entry.next) list_remove(&This->entry); - LeaveCriticalSection(&cache_section); free(This->path); } TRACE(" destroying ITypeLib(%p)\n",This); @@ -4783,9 +4784,9 @@ static ULONG WINAPI ITypeLib2_fnRelease( ITypeLib2 *iface) } free(This->typeinfos); free(This); - return 0; }
+ LeaveCriticalSection(&cache_section); return ref; }
On Thu Nov 9 13:30:42 2023 +0000, Alexandre Julliard wrote:
Would you prefer using InterlockedIncrement in AddRef instead of using
the CS lock? Yes, it's good practice to always use interlocked functions for COM refcounts.
Cool, I've changed it to use atomics in in the most recent version.