Skip to content

Commit 3dde055

Browse files
Ensure the FindReferenceTargetsCallback static constructor is called. (#121558)
The code path in question is executed during a GC. This code path also allocates managed memory, which means it is incompatible to run during a GC. Ensuring the cctor run prior to any GC is the goal of this change. Fixes #121538
1 parent 6547b2e commit 3dde055

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/TrackerObjectManager.NativeAot.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ internal static void DetachNonPromotedObjects()
196196
}
197197

198198
// Callback implementation of IFindReferenceTargetsCallback
199+
[EagerStaticClassConstruction]
199200
internal static unsafe class FindReferenceTargetsCallback
200201
{
201202
// Define an on-stack compatible COM instance to avoid allocating

src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -444,12 +444,18 @@ private IntPtr AsUserDefined(in Guid riid)
444444

445445
private void SetFlag(CreateComInterfaceFlagsEx flag)
446446
{
447-
Interlocked.Or(ref Flags, flag);
447+
// Interlocked.Or<T>cannot be used here. It would trigger type checks that can cause
448+
// deadlocks when called during a GC by NativeAOT TrackerObjectManager.
449+
int setMask = (int)flag;
450+
Interlocked.Or(ref Unsafe.As<CreateComInterfaceFlagsEx, int>(ref Flags), setMask);
448451
}
449452

450453
private void ResetFlag(CreateComInterfaceFlagsEx flag)
451454
{
452-
Interlocked.And(ref Flags, ~flag);
455+
// Interlocked.And<T>cannot be used here. It would trigger type checks that can cause
456+
// deadlocks when called during a GC by NativeAOT TrackerObjectManager.
457+
int resetMask = ~(int)flag;
458+
Interlocked.And(ref Unsafe.As<CreateComInterfaceFlagsEx, int>(ref Flags), resetMask);
453459
}
454460

455461
private static uint GetTrackerCount(ulong c)

0 commit comments

Comments
 (0)