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
13 changes: 11 additions & 2 deletions src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -972,9 +972,18 @@ public override unsafe IntPtr ConvertToNative(object managed, int dwFlags)
int allocSize = Marshal.SizeOfHelper((RuntimeType)_layoutType, false);
IntPtr pNative = Marshal.AllocCoTaskMem(allocSize);

if (IsIn(dwFlags))
try
{
StubHelpers.LayoutTypeConvertToUnmanaged(managed, (byte*)pNative, ref _cleanupWorkList);
if (IsIn(dwFlags))
{
StubHelpers.LayoutTypeConvertToUnmanaged(managed, (byte*)pNative, ref _cleanupWorkList);
}
}
catch
{
StubHelpers.DestroyCleanupList(ref _cleanupWorkList);
Marshal.FreeCoTaskMem(pNative);
throw;
Comment thread
jkoritzinsky marked this conversation as resolved.
Comment thread
jkoritzinsky marked this conversation as resolved.
}

return pNative;
Expand Down
11 changes: 11 additions & 0 deletions src/tests/Interop/PInvoke/AsAny/AsAnyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ public static int TestEntryPoint()
TestIntPtrArray();
TestUIntPtrArray();
TestLayout();
TestLayoutConvertToNativeExceptionPath();
RunAsAnyFieldTests();
TestUnicodeString();
TestUnicodeStringArray();
Expand Down Expand Up @@ -654,6 +655,16 @@ public static void TestLayout() {
Console.WriteLine("------------------------");
}

private static void TestLayoutConvertToNativeExceptionPath()
{
// AsAnyField contains a field with [MarshalAs(UnmanagedType.AsAny)], which is not
// supported in layout marshaling. When passed via AsAny, LayoutImplementation.ConvertToNative
// allocates a native buffer and then calls LayoutTypeConvertToUnmanaged, which throws
// TypeLoadException. Verify the exception propagates correctly; the fix ensures the
// native buffer is freed on this exception path rather than leaked.
Assert.Throws<TypeLoadException>(() => PassLayout(new AsAnyField()));
}

static void CharArrayInit(char[] unMappableCharArray_In, char[] unMappableCharArray_InOut, char[] unMappableCharArray_Out,
char[] mappableCharArray_In, char[] mappableCharArray_InOut, char[] mappableCharArray_Out,
string unMappableStr, string mappableStr)
Expand Down
Loading