Fix native memory leak in AsAnyMarshaler.ConvertLayoutToNative on exception#126909
Fix native memory leak in AsAnyMarshaler.ConvertLayoutToNative on exception#126909
Conversation
Agent-Logs-Url: https://github.com/dotnet/runtime/sessions/33ae7353-2afd-4be1-9081-898caba946da Co-authored-by: jkoritzinsky <1571408+jkoritzinsky@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Fixes an exception-path leak in CoreCLR’s AsAnyMarshaler.ConvertLayoutToNative (in System.Private.CoreLib) by ensuring unmanaged memory allocated via Marshal.AllocCoTaskMem is freed if LayoutTypeConvertToUnmanaged throws during layout marshaling.
Changes:
- Wrap
LayoutTypeConvertToUnmanagedintry/catchwithinConvertLayoutToNative. - Free the
CoTaskMembuffer on exception before rethrowing.
There was a problem hiding this comment.
Pull request overview
Fixes an exception-path native memory leak in AsAnyMarshaler.ConvertLayoutToNative within CoreLib interop marshaling by ensuring native allocations (and any accumulated cleanup work) are released when LayoutTypeConvertToUnmanaged throws.
Changes:
- Wraps the
LayoutTypeConvertToUnmanagedcall inConvertLayoutToNativewith atry/catch. - On exception, destroys the
cleanupWorkListand frees theMarshal.AllocCoTaskMembuffer before rethrowing.
|
Tagging subscribers to this area: @dotnet/interop-contrib |
| catch | ||
| { | ||
| StubHelpers.LayoutTypeConvertToUnmanaged(pManagedHome, (byte*)pNativeHome, ref cleanupWorkList); | ||
| StubHelpers.DestroyCleanupList(ref cleanupWorkList); |
There was a problem hiding this comment.
Is the full clean-up always safe here? I'd assume that there are already clean-up places for this. The FreeCoTaskMem makes sense, but do we really need the StubHelpers.DestroyCleanupList() as well?
There was a problem hiding this comment.
We don't technically "need" the cleanup list cleanup as the only entries (SafeHandle instances) will eventually be finalized, but without this, they'd have a mismatched refcount until finalization.
Description
AsAnyMarshaler.ConvertLayoutToNativeleaks theMarshal.AllocCoTaskMem-allocated buffer whenLayoutTypeConvertToUnmanagedthrows — the exception unwinds past thereturn pNativeHomewith no cleanup.Fix
Wrap the conversion call in a
try/catchthat frees on failure, matching the defensive pattern already used in sibling code in the same file:Changes
src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs: Addedtry/catcharoundLayoutTypeConvertToUnmanagedcall inConvertLayoutToNativeto free native memory on exception.Testing
Risk
Low — strictly adds a cleanup path that was previously missing; no behavioral change on the happy path.