Skip to content

Commit 6634a7c

Browse files
Fix pointer array copying and various array pinning regressions in CoreCLR (#134284)
<!-- --> ## Summary Fix copying and pinning regressions in CoreCLR's built-in array marshalling: - **Incorrect copying:** the array metadata retained the pointee type while using a pointer-sized VARTYPE. The generic marshaler consequently used the pointee's size: a four-element `byte*[]` allocated and copied four bytes instead of 32 on x64. - **Lost pinning:** the pinning predicate required a blittable value-type method table, excluding pointer and function-pointer type descriptors. - **Enum pinning:** evaluate pinning against the enum's underlying primitive instead of the enum's own layout flags. - **Unicode character pinning:** recognize `char[]` when its selected native representation is UTF-16, including explicit `I2`/`U2` element types. ANSI and Boolean conversions continue to use copying. Preserve the actual element `TypeHandle` in the marshalling operands, and select `nint` only as the carrier for generic copying. Managed allocation retains the declared pointer-array type and preserves null native arrays. Eligible forward P/Invokes use the existing pinning path; ref/out and reverse calls continue to copy. Treat pointer elements as opaque native-sized values, including function pointers, struct pointers, and pointer-to-pointer elements. Update the managed compatibility assertions and native layout consumers accordingly. SAFEARRAY pointer support and non-pointer conversion rules are not broadened. ## Regression coverage Added **324 cases** in the existing interop suites: 250 pointer/native-integer cases and 74 enum/character/conversion-control cases. Coverage includes forward P/Invoke and unmanaged-function-pointer delegates, required copying, exact copy-back array types, ref/out parameters, reverse callbacks, fixed-array fields, null/empty and odd-length arrays, and pinning across compacting GC. Pointer coverage includes `float*`, struct pointers, pointer-to-pointer elements, and managed/unmanaged function pointers. The enum cases cover all eight standard underlying integral types. Character cases cover UTF-16, ANSI, and explicit element-type overrides; Boolean controls ensure conversion still occurs. Assertions distinguish passing managed contents directly from copying. Native exports and callback types explicitly use Cdecl for x86. ## Validation The product fixes and full 324-case regression set were validated locally: | Runtime configuration | New cases passed | Total related array cases passed | | --- | ---: | ---: | | Windows x64 Checked | 324 | 344 | | Windows x64 Release | 324 | 344 | | Windows x86 Checked | 324 | 343 | The x86 difference is a 64-bit-only SAFEARRAY element-size mismatch control. Result XML was checked for failures, rather than relying only on the merged runner's exit code. After the final test-only renames and runtime-specific data splits, the x64 Checked managed interop tests were rebuilt and rerun: **344 passed, 0 failed**, including all 324 added cases. The Release and x86 results above precede those test-only changes. Baseline copying, pinning, and function-pointer failures were reproduced. With only the copying repair applied, 80 copy cases passed while all four pinning-direction checks still failed, verifying that pinning does not merely hide a broken copy path. The enum/character additions were also run before their fix: 32 pinning cases failed while all ANSI and Boolean conversion controls passed. All 74 added enum/character/control cases pass with the updated predicate. `IntPtr[]` and `UIntPtr[]` already behaved correctly on this checkout; their product behavior is unchanged and is covered by the new tests. ## Runtime-specific test exclusions CI exposed separate NativeAOT and Mono issues; this PR does **not** change either runtime's implementation. Split theory data into passing and failing partitions and use narrowly scoped `ActiveIssue` attributes: - **NativeAOT:** exclude exactly 27 failing rows: null fixed-array fields, null ref/out arrays, and nonempty reverse-copy cases. Tracked by #134628; the remaining 223 pointer cases stay enabled. - **Compiled Mono:** exclude exactly 17 failing function-pointer rows, tracked by #90308. Null function-pointer rows, ordinary data-pointer rows, and Mono interpreter function-pointer coverage remain enabled. Other method-level Mono exclusions for copying, layout, and character semantics remain. - **WebAssembly:** retain the pointer-test exclusion for the shared test host's missing unmanaged-callback thunks, tracked by #124219. The newly excluded row sets match the recorded CI failures exactly, and the generated merged runner's predicates and skip reporting were checked. NativeAOT and Mono behavior was investigated from CI evidence and source inspection; neither runtime was rerun locally. Linux and ARM64 were not run locally. ## Generated-code comparison Release x64 P/Invoke stubs, with tiering and ReadyToRun disabled: | Direction | Baseline bytes | Fixed bytes | Baseline instructions | Fixed instructions | | --- | ---: | ---: | ---: | ---: | | Default | 294 | 185 | 86 | 58 | | In | 294 | 185 | 86 | 58 | | Out | 303 | 185 | 89 | 58 | | In/Out | 332 | 185 | 97 | 58 | The fixed pinning stubs contain no unmanaged-allocation helper, `Memmove`, or `CoTaskMemFree` calls. These are code-generation measurements, not benchmark timings. For the new enum and UTF-16 declarations, Release x64 stubs shrink from 281-285 bytes (82-83 instructions) to 170 bytes (54 instructions), likewise eliminating allocation/copy/free calls. The ANSI and Boolean control stubs retain their previous code sizes and call paths. Resolves #134174 Resolves #134576 Resolves #134577 Resolves #134575 Resolves #134573 > [!NOTE] > This PR was created with assistance from GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a58d7c5-bde9-4e44-a0bb-320dd6b721df
1 parent a95fccd commit 6634a7c

10 files changed

Lines changed: 1641 additions & 49 deletions

File tree

‎src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,10 +1148,10 @@ private static AsAnyMarshalerImplementation CreateAnsiCharArrayImplementation(bo
11481148
{
11491149
return (IsBestFit(dwFlags), IsThrowOn(dwFlags)) switch
11501150
{
1151-
(true, true) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.EnabledOption, IMarshalerOption.EnabledOption>>(isOut),
1152-
(true, false) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.EnabledOption, IMarshalerOption.DisabledOption>>(isOut),
1153-
(false, true) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.DisabledOption, IMarshalerOption.EnabledOption>>(isOut),
1154-
(false, false) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.DisabledOption, IMarshalerOption.DisabledOption>>(isOut),
1151+
(true, true) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.EnabledOption, IMarshalerOption.EnabledOption, IMarshalerOption.DisabledOption>>(isOut),
1152+
(true, false) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.EnabledOption, IMarshalerOption.DisabledOption, IMarshalerOption.DisabledOption>>(isOut),
1153+
(false, true) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.DisabledOption, IMarshalerOption.EnabledOption, IMarshalerOption.DisabledOption>>(isOut),
1154+
(false, false) => new ArrayImplementation<char, AnsiCharArrayMarshaler<IMarshalerOption.DisabledOption, IMarshalerOption.DisabledOption, IMarshalerOption.DisabledOption>>(isOut),
11551155
};
11561156
}
11571157

@@ -1782,12 +1782,14 @@ public static unsafe void Free(byte* unmanaged)
17821782
static unsafe nuint IArrayElementMarshaler<string?, LPWSTRMarshaler>.UnmanagedSize => (nuint)sizeof(IntPtr);
17831783
}
17841784

1785-
internal sealed class AnsiCharArrayMarshaler<TBestFit, TThrowOnUnmappable> : IArrayMarshaler<char, AnsiCharArrayMarshaler<TBestFit, TThrowOnUnmappable>>
1785+
internal sealed class AnsiCharArrayMarshaler<TBestFit, TThrowOnUnmappable, TFixedBuffer> : IArrayMarshaler<char, AnsiCharArrayMarshaler<TBestFit, TThrowOnUnmappable, TFixedBuffer>>
17861786
where TBestFit : IMarshalerOption
17871787
where TThrowOnUnmappable : IMarshalerOption
1788+
where TFixedBuffer : IMarshalerOption
17881789
{
17891790
public static unsafe void ConvertContentsToUnmanaged(Array managedArray, byte* unmanaged, int length)
17901791
{
1792+
int byteCapacity = GetNativeBufferSize(length);
17911793
fixed (byte* pCharBytes = &MemoryMarshal.GetArrayDataReference(managedArray))
17921794
{
17931795
char* pChars = (char*)pCharBytes;
@@ -1800,7 +1802,7 @@ public static unsafe void ConvertContentsToUnmanaged(Array managedArray, byte* u
18001802
pChars,
18011803
length,
18021804
unmanaged,
1803-
length,
1805+
byteCapacity,
18041806
null,
18051807
TThrowOnUnmappable.Enabled ? &defaultCharUsed : null);
18061808

@@ -1814,14 +1816,15 @@ public static unsafe void ConvertContentsToUnmanaged(Array managedArray, byte* u
18141816
throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char);
18151817
}
18161818
#else
1817-
Encoding.UTF8.GetBytes(pChars, length, unmanaged, length);
1819+
Encoding.UTF8.GetBytes(pChars, length, unmanaged, byteCapacity);
18181820
#endif
18191821
}
18201822

18211823
}
18221824

18231825
public static unsafe void ConvertContentsToManaged(Array managedArray, byte* unmanaged, int length)
18241826
{
1827+
// The native byte count is independent of the maximum allocation size used for multibyte expansion.
18251828
fixed (byte* pCharBytes = &MemoryMarshal.GetArrayDataReference(managedArray))
18261829
{
18271830
char* pChars = (char*)pCharBytes;
@@ -1855,8 +1858,7 @@ public static unsafe void FreeContents(byte* unmanaged, int length)
18551858
return null;
18561859
}
18571860

1858-
// Native layout for ANSI char arrays uses 1 byte per element.
1859-
int allocSize = managedArray.Length;
1861+
int allocSize = GetNativeBufferSize(managedArray.Length);
18601862
byte* pNative = (byte*)Marshal.AllocCoTaskMem(allocSize);
18611863
NativeMemory.Clear(pNative, (nuint)allocSize);
18621864
return pNative;
@@ -1871,6 +1873,9 @@ public static unsafe void FreeContents(byte* unmanaged, int length)
18711873

18721874
return new char[length];
18731875
}
1876+
1877+
private static int GetNativeBufferSize(int length)
1878+
=> TFixedBuffer.Enabled ? length : checked(length * Marshal.SystemMaxDBCSCharSize);
18741879
}
18751880

18761881
internal sealed class LPSTRArrayElementMarshaler<TBestFit, TThrowOnUnmappable> : IArrayElementMarshaler<string?, LPSTRArrayElementMarshaler<TBestFit, TThrowOnUnmappable>>
@@ -2456,21 +2461,29 @@ internal static unsafe void LayoutTypeConvertToManaged(object* obj, byte* pNativ
24562461
}
24572462
}
24582463

2464+
[Conditional("DEBUG")]
2465+
private static void ValidateArrayElementType<T>(Array managed)
2466+
{
2467+
Debug.Assert(managed is not null);
2468+
Type elementType = managed.GetType().GetElementType()!;
2469+
// Pointer and function pointer types cannot be generic arguments, so their marshalers use nint
2470+
// even though their arrays are not assignable to nint[].
2471+
Debug.Assert((typeof(T) == typeof(nint) && (elementType.IsPointer || elementType.IsFunctionPointer))
2472+
|| elementType.MakeArrayType().IsAssignableTo(typeof(T[])),
2473+
$"Managed array type {managed.GetType()} is not compatible with expected element type {typeof(T)}");
2474+
}
2475+
24592476
public static unsafe void ConvertArrayContentsToUnmanaged<T, TMarshaler>(Array managed, byte* pNative, int numElements)
24602477
where TMarshaler : IArrayMarshaler<T, TMarshaler>
24612478
{
2462-
// Assert that the array is actually an array of compatible type.
2463-
Debug.Assert(managed is not null);
2464-
Debug.Assert(managed.GetType().GetElementType()!.MakeArrayType().IsAssignableTo(typeof(T[])), $"Managed array type {managed.GetType()} is not compatible with expected element type {typeof(T)}");
2479+
ValidateArrayElementType<T>(managed);
24652480
TMarshaler.ConvertContentsToUnmanaged(managed, pNative, numElements);
24662481
}
24672482

24682483
public static unsafe void ConvertArrayContentsToManaged<T, TMarshaler>(Array managed, byte* pNative, int numElements)
24692484
where TMarshaler : IArrayMarshaler<T, TMarshaler>
24702485
{
2471-
// Assert that the array is actually an array of compatible type.
2472-
Debug.Assert(managed is not null);
2473-
Debug.Assert(managed.GetType().GetElementType()!.MakeArrayType().IsAssignableTo(typeof(T[])), $"Managed array type {managed.GetType()} is not compatible with expected element type {typeof(T)}");
2486+
ValidateArrayElementType<T>(managed);
24742487
TMarshaler.ConvertContentsToManaged(managed, pNative, numElements);
24752488
}
24762489

‎src/coreclr/vm/corelib.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1263,7 +1263,7 @@ DEFINE_CLASS(COMVARIANT, Marshalling, ComVariant)
12631263
DEFINE_CLASS(VARIANT_BOOL_MARSHALER, StubHelpers, VariantBoolMarshaler)
12641264
DEFINE_CLASS(BOOL_MARSHALER, StubHelpers, BoolMarshaler`1)
12651265
DEFINE_CLASS(LPWSTR_MARSHALER, StubHelpers, LPWSTRMarshaler)
1266-
DEFINE_CLASS(ANSICHAR_ARRAY_ELEMENT_MARSHALER, StubHelpers, AnsiCharArrayMarshaler`2)
1266+
DEFINE_CLASS(ANSICHAR_ARRAY_ELEMENT_MARSHALER, StubHelpers, AnsiCharArrayMarshaler`3)
12671267
DEFINE_CLASS(LPSTR_ARRAY_ELEMENT_MARSHALER, StubHelpers, LPSTRArrayElementMarshaler`2)
12681268
DEFINE_CLASS(BSTR_ARRAY_ELEMENT_MARSHALER, StubHelpers, BSTRArrayElementMarshaler)
12691269
#ifdef FEATURE_COMINTEROP

‎src/coreclr/vm/fieldmarshaler.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ VOID ParseNativeType(Module* pModule,
382382
CREATE_MARSHALER_CARRAY_OPERANDS mops;
383383
mlInfo.GetMops(&mops);
384384

385-
MethodTable *pMT = mops.methodTable;
385+
MethodTable *pMT = mops.elementTypeHandle.GetMethodTable();
386386

387387
if (pMT->IsEnum())
388388
{

‎src/coreclr/vm/ilmarshalers.cpp‎

Lines changed: 61 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3846,8 +3846,7 @@ void ILMngdMarshaler::EmitCallMngdMarshalerMethod(ILCodeStream* pslILEmit, Metho
38463846

38473847
bool ILNativeArrayMarshaler::CanMarshalViaPinning()
38483848
{
3849-
// We can't pin an array if we have a non-default element native type (e.g. ANSICHAR, WINBOOL, CBOOL),
3850-
// if we have a marshaler for the var type, or if we can't get a method-table representing the array.
3849+
// Pin only by-value CLR-to-native arrays whose elements need no conversion.
38513850

38523851
if (!IsCLRToNative(m_dwMarshalFlags) || IsByref(m_dwMarshalFlags))
38533852
{
@@ -3856,9 +3855,9 @@ bool ILNativeArrayMarshaler::CanMarshalViaPinning()
38563855

38573856
CREATE_MARSHALER_CARRAY_OPERANDS mops;
38583857
m_pargs->m_pMarshalInfo->GetMops(&mops);
3859-
if (mops.elementNativeType != NATIVE_TYPE_DEFAULT)
3858+
if (mops.elementNativeType != NATIVE_TYPE_DEFAULT || mops.elementType == VT_CY)
38603859
{
3861-
// This means that we have some sort of custom marshaling logic.
3860+
// Currency and non-default native types require element conversion.
38623861
return false;
38633862
}
38643863

@@ -3867,9 +3866,16 @@ bool ILNativeArrayMarshaler::CanMarshalViaPinning()
38673866
return false;
38683867
}
38693868

3870-
TypeHandle elementTypeHandle = m_pargs->na.m_pArrayMT->GetArrayElementTypeHandle();
3869+
TypeHandle elementTypeHandle = mops.elementTypeHandle;
3870+
if (elementTypeHandle.IsEnum())
3871+
{
3872+
elementTypeHandle = TypeHandle(CoreLibBinder::GetElementType(elementTypeHandle.GetInternalCorElementType()));
3873+
}
38713874

3872-
return elementTypeHandle.IsBlittable() && elementTypeHandle.GetMethodTable()->IsValueType();
3875+
return elementTypeHandle.IsPointer()
3876+
|| elementTypeHandle.IsFnPtrType()
3877+
|| (elementTypeHandle.GetSignatureCorElementType() == ELEMENT_TYPE_CHAR && mops.elementType == VT_UI2)
3878+
|| (elementTypeHandle.IsBlittable() && elementTypeHandle.GetMethodTable()->IsValueType());
38733879
}
38743880

38753881
void ILNativeArrayMarshaler::EmitMarshalViaPinning(ILCodeStream* pslILEmit)
@@ -4128,7 +4134,7 @@ namespace
41284134
{
41294135
// Resolve the managed marshaler MethodTable and the element type it marshals.
41304136
// Both are returned together to guarantee they are consistent.
4131-
void GetMarshalerAndElementTypes(MarshalInfo* pMarshalInfo, MethodTable** ppMarshalerMT, TypeHandle* pElementType)
4137+
void GetMarshalerAndElementTypes(MarshalInfo* pMarshalInfo, MethodTable** ppMarshalerMT, TypeHandle* pElementType, bool fixedNativeBuffer)
41324138
{
41334139
STANDARD_VM_CONTRACT;
41344140

@@ -4138,10 +4144,12 @@ namespace
41384144
bool bestFit = mops.bestfitmapping != 0;
41394145
bool throwOnUnmappable = mops.throwonunmappablechar != 0;
41404146

4141-
// Start from the managed element type - this is the authoritative source.
4142-
MethodTable* pElementMT = mops.methodTable;
4143-
4144-
TypeHandle thElement(pElementMT);
4147+
TypeHandle thElement = mops.elementTypeHandle;
4148+
if (thElement.IsPointer() || thElement.IsFnPtrType())
4149+
{
4150+
// Pointer types cannot be generic arguments, so use nint as the managed marshaler's carrier.
4151+
thElement = TypeHandle(CoreLibBinder::GetClass(CLASS__INTPTR));
4152+
}
41454153

41464154
MethodTable* pEnabledMT = CoreLibBinder::GetClass(CLASS__MARSHALER_OPTION_ENABLED);
41474155
MethodTable* pDisabledMT = CoreLibBinder::GetClass(CLASS__MARSHALER_OPTION_DISABLED);
@@ -4176,9 +4184,9 @@ namespace
41764184
case NATIVE_TYPE_U1:
41774185
{
41784186
_ASSERTE(thElement == TypeHandle(CoreLibBinder::GetClass(CLASS__CHAR)));
4179-
TypeHandle thArgs[2] = { TypeHandle(pBestFitMT), TypeHandle(pThrowOnUnmappableMT) };
4187+
TypeHandle thArgs[3] = { TypeHandle(pBestFitMT), TypeHandle(pThrowOnUnmappableMT), TypeHandle(fixedNativeBuffer ? pEnabledMT : pDisabledMT) };
41804188
*pElementType = thElement;
4181-
*ppMarshalerMT = TypeHandle(CoreLibBinder::GetClass(CLASS__ANSICHAR_ARRAY_ELEMENT_MARSHALER)).Instantiate(Instantiation(thArgs, 2)).AsMethodTable();
4189+
*ppMarshalerMT = TypeHandle(CoreLibBinder::GetClass(CLASS__ANSICHAR_ARRAY_ELEMENT_MARSHALER)).Instantiate(Instantiation(thArgs, 3)).AsMethodTable();
41824190
return;
41834191
}
41844192

@@ -4333,7 +4341,7 @@ namespace
43334341

43344342

43354343
// Instantiate one of the generic StubHelpers array methods with the element type and marshaler type.
4336-
MethodDesc* GetInstantiatedArrayMethod(MarshalInfo* pMarshalInfo, BinderMethodID methodId)
4344+
MethodDesc* GetInstantiatedArrayMethod(MarshalInfo* pMarshalInfo, BinderMethodID methodId, bool fixedNativeBuffer = false)
43374345
{
43384346
STANDARD_VM_CONTRACT;
43394347

@@ -4343,7 +4351,7 @@ namespace
43434351
// to guarantee they are consistent.
43444352
TypeHandle thElementType;
43454353
MethodTable* pMarshalerMT;
4346-
GetMarshalerAndElementTypes(pMarshalInfo, &pMarshalerMT, &thElementType);
4354+
GetMarshalerAndElementTypes(pMarshalInfo, &pMarshalerMT, &thElementType, fixedNativeBuffer);
43474355

43484356
TypeHandle thMarshalerType(pMarshalerMT);
43494357
TypeHandle thArgs[2] = { thElementType, thMarshalerType };
@@ -4371,9 +4379,16 @@ void ILNativeArrayMarshaler::EmitConvertSpaceNativeToCLR(ILCodeStream* pslILEmit
43714379
pslILEmit->EmitSTLOC(m_dwSavedSizeArg);
43724380
}
43734381

4374-
MethodDesc* pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_SPACE_TO_MANAGED);
4382+
CREATE_MARSHALER_CARRAY_OPERANDS mops;
4383+
m_pargs->m_pMarshalInfo->GetMops(&mops);
4384+
bool isPointerArray = mops.elementTypeHandle.IsPointer() || mops.elementTypeHandle.IsFnPtrType();
43754385

4376-
EmitLoadNativeValue(pslILEmit);
4386+
MethodDesc* pMD = nullptr;
4387+
if (!isPointerArray)
4388+
{
4389+
pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_SPACE_TO_MANAGED);
4390+
EmitLoadNativeValue(pslILEmit);
4391+
}
43774392

43784393
// Dynamically calculate element count using SizeParamIndex argument
43794394
EmitLoadElementCount(pslILEmit);
@@ -4386,7 +4401,24 @@ void ILNativeArrayMarshaler::EmitConvertSpaceNativeToCLR(ILCodeStream* pslILEmit
43864401
pslILEmit->EmitLDLOC(m_dwSavedSizeArg);
43874402
}
43884403

4389-
pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 2, 1);
4404+
if (isPointerArray)
4405+
{
4406+
// The copy marshaler uses nint, but the allocated array must retain its declared pointer element type.
4407+
ILCodeLabel* pAllocateArray = pslILEmit->NewCodeLabel();
4408+
ILCodeLabel* pDone = pslILEmit->NewCodeLabel();
4409+
EmitLoadNativeValue(pslILEmit);
4410+
pslILEmit->EmitBRTRUE(pAllocateArray);
4411+
pslILEmit->EmitPOP();
4412+
pslILEmit->EmitLDNULL();
4413+
pslILEmit->EmitBR(pDone);
4414+
pslILEmit->EmitLabel(pAllocateArray);
4415+
pslILEmit->EmitNEWARR(pslILEmit->GetToken(mops.elementTypeHandle));
4416+
pslILEmit->EmitLabel(pDone);
4417+
}
4418+
else
4419+
{
4420+
pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 2, 1);
4421+
}
43904422
EmitStoreManagedValue(pslILEmit);
43914423
}
43924424

@@ -4459,7 +4491,9 @@ void ILNativeArrayMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILE
44594491
EmitLoadManagedValue(pslILEmit);
44604492
pslILEmit->EmitBRFALSE(pSkipLabel);
44614493

4462-
MethodDesc* pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_UNMANAGED);
4494+
// A by-value reverse P/Invoke writes into the caller's buffer, not an allocation we can expand.
4495+
bool fixedNativeBuffer = !IsCLRToNative(m_dwMarshalFlags) && !IsByref(m_dwMarshalFlags);
4496+
MethodDesc* pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_UNMANAGED, fixedNativeBuffer);
44634497

44644498
EmitLoadManagedValue(pslILEmit);
44654499
EmitLoadNativeValue(pslILEmit);
@@ -4558,7 +4592,7 @@ void ILFixedArrayMarshaler::EmitConvertSpaceNativeToCLR(ILCodeStream* pslILEmit)
45584592

45594593
// new T[cElements]
45604594
pslILEmit->EmitLDC(mops.additive);
4561-
pslILEmit->EmitNEWARR(pslILEmit->GetToken(mops.methodTable));
4595+
pslILEmit->EmitNEWARR(pslILEmit->GetToken(mops.elementTypeHandle));
45624596
EmitStoreManagedValue(pslILEmit);
45634597
}
45644598

@@ -4571,7 +4605,7 @@ void ILFixedArrayMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEm
45714605

45724606
// Compute the total native byte size of the inline array so we can
45734607
// zero it when the managed array is null.
4574-
MethodTable* pElementMT = mops.methodTable;
4608+
MethodTable* pElementMT = mops.elementTypeHandle.GetMethodTable();
45754609
if (pElementMT->IsEnum())
45764610
{
45774611
pElementMT = CoreLibBinder::GetElementType(pElementMT->GetInternalCorElementType());
@@ -4599,7 +4633,7 @@ void ILFixedArrayMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEm
45994633
EmitLoadManagedValue(pslILEmit);
46004634
pslILEmit->EmitBRFALSE(pNullLabel);
46014635

4602-
MethodDesc* pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_UNMANAGED);
4636+
MethodDesc* pMD = GetInstantiatedArrayMethod(m_pargs->m_pMarshalInfo, METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_UNMANAGED, true /* fixedNativeBuffer */);
46034637

46044638
EmitLoadManagedValue(pslILEmit);
46054639
EmitLoadNativeHomeAddr(pslILEmit);
@@ -4674,6 +4708,8 @@ void ILSafeArrayMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit)
46744708

46754709
CREATE_MARSHALER_CARRAY_OPERANDS mops;
46764710
m_pargs->m_pMarshalInfo->GetMops(&mops);
4711+
_ASSERTE(!mops.elementTypeHandle.IsTypeDesc());
4712+
MethodTable* pElementMT = mops.elementTypeHandle.AsMethodTable();
46774713

46784714
DWORD dwFlags = mops.elementType;
46794715
BYTE fStatic = 0;
@@ -4693,7 +4729,7 @@ void ILSafeArrayMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit)
46934729
dwFlags |= ((BYTE)!!m_pargs->m_pMarshalInfo->GetNoLowerBounds()) << 24;
46944730

46954731
pslILEmit->EmitLDLOC(m_dwMngdMarshalerLocalNum);
4696-
pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(mops.methodTable));
4732+
pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(pElementMT));
46974733
pslILEmit->EmitCALL(METHOD__RT_TYPE_HANDLE__TO_INTPTR, 1, 1);
46984734
pslILEmit->EmitLDC(m_pargs->m_pMarshalInfo->GetArrayRank());
46994735
pslILEmit->EmitLDC(dwFlags);
@@ -4703,12 +4739,12 @@ void ILSafeArrayMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit)
47034739
BOOL bNativeDataValid = !!(fStatic & MngdSafeArrayMarshaler::SCSF_NativeDataValid);
47044740
MethodDesc* pConvertToNativeMD = GetInstantiatedSafeArrayMethod(
47054741
METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_UNMANAGED,
4706-
mops.elementType, mops.methodTable, FALSE, bNativeDataValid);
4742+
mops.elementType, pElementMT, FALSE, bNativeDataValid);
47074743
pslILEmit->EmitLDFTN(pslILEmit->GetToken(pConvertToNativeMD));
47084744

47094745
MethodDesc* pConvertToManagedMD = GetInstantiatedSafeArrayMethod(
47104746
METHOD__STUBHELPERS__CONVERT_ARRAY_CONTENTS_TO_MANAGED,
4711-
mops.elementType, mops.methodTable, FALSE);
4747+
mops.elementType, pElementMT, FALSE);
47124748
pslILEmit->EmitLDFTN(pslILEmit->GetToken(pConvertToManagedMD));
47134749

47144750
pslILEmit->EmitCALL(METHOD__MNGD_SAFE_ARRAY_MARSHALER__CREATE_MARSHALER, 6, 0);

‎src/coreclr/vm/mlinfo.cpp‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3311,13 +3311,22 @@ void ArrayMarshalInfo::InitElementInfo(CorNativeType arrayNativeType, MarshalInf
33113311

33123312
m_thElement = thElement;
33133313

3314-
if (m_thElement.IsPointer())
3314+
if ((arrayNativeType == NATIVE_TYPE_ARRAY || arrayNativeType == NATIVE_TYPE_FIXEDARRAY)
3315+
&& (m_thElement.IsPointer() || m_thElement.IsFnPtrType()))
33153316
{
3316-
m_flags = (ArrayMarshalInfoFlags)(m_flags | amiIsPtr);
3317-
m_thElement = ((ParamTypeDesc*)m_thElement.AsTypeDesc())->GetModifiedType();
3317+
// Marshal pointer-sized values without losing the declared element type.
3318+
etElement = ELEMENT_TYPE_I;
33183319
}
3320+
else
3321+
{
3322+
if (m_thElement.IsPointer())
3323+
{
3324+
m_flags = (ArrayMarshalInfoFlags)(m_flags | amiIsPtr);
3325+
m_thElement = ((ParamTypeDesc*)m_thElement.AsTypeDesc())->GetModifiedType();
3326+
}
33193327

3320-
etElement = m_thElement.GetSignatureCorElementType();
3328+
etElement = m_thElement.GetSignatureCorElementType();
3329+
}
33213330

33223331
if (IsAMIPtr(m_flags) && (etElement > ELEMENT_TYPE_R8))
33233332
{

0 commit comments

Comments
 (0)