Skip to content

[Mono] Interpreter: Missing write barrier in Delegate field assignment (+=) causes GC consistency error and crash in Delegate.Remove #124941

Closed

Description

@Liangjia0411

Description

We are encountering random crashes in Delegate.Remove (specifically around InternalEqualTypes / MINT_INTRINS_GET_TYPE) when running on Mono Interpreter (iOS, Android, and Windows).

All signs point to a GC liveness/rooting issue where the Delegate object is prematurely collected by a Minor GC, resulting in a wild pointer access during the subsequent Delegate.Remove call.

After enabling the GC debug option check-remset-consistency, we caught a definitive log indicating a missing write barrier.

Configuration

  • Version: .NET 9.0.11 (Mono Runtime)
  • OS: iOS, Android, Windows
  • Execution Mode: Interpreter enabled
  • GC: SGen

Reproduction Steps

The issue occurs with C# event operations involving a long-lived object (Old Gen) referencing a short-lived Delegate (New Gen).

Pseudo-code context:

// Scenario: Use a custom EventProxy to manage events on a long-lived EventDispatcher.
partial class EventProxy
{
    // EventDispatcher is a long-lived object (likely in Old Gen)
    readonly EventDispatcher mDispatcher; 
    
    // ... verification logic ...

    public event Action ActivityNewyear2026RefreshPreviewSellPrice
    {
        add
        {
            // The 'value' is a new Delegate (likely in New Gen/Nursery).
            // We verify logic and then modify the field on mDispatcher.
            
            // PROBLEM TRIGGER: This operation (+=) seems to miss a Write Barrier in Interpreter mode.
            mDispatcher.EventActivityNewyear2026RefreshPreviewSellPrice += value;
        }
        remove
        {
             // CRASH HAPPENS HERE:
             // When attempting to remove, 'value' or the field in 'mDispatcher' 
             // points to garbage memory because it was collected in a prior Minor GC.
             mDispatcher.EventActivityNewyear2026RefreshPreviewSellPrice -= value;
        }
    }
}

partial class EventDispatcher
{
    // This object is promoted to Old Space.
    // Offset 8888 corresponds to this field.
    public event Action? EventActivityNewyear2026RefreshPreviewSellPrice = null; 
}

Analysis & Logs

We enabled the GC consistency check via environment variable/argument:
MONO_GC_DEBUG=check-remset-consistency

After executing the += operation (add), the following error is logged immediately before the crash occurs in a subsequent operation:

59:46 Begin heap consistency check...
2026-02-27 10:59:46 Oldspace->newspace reference 000002770A8153D0 at offset 8888 in object 0000027709A63798 (Tenth.EventDispatcher) not found in remsets.
2026-02-27 10:59:46 Heap consistency check done.

Interpretation:

  1. Tenth.EventDispatcher (0000027709A63798) is in Old Gen (Oldspace).
  2. The field at offset 8888 (EventActivityNewyear2026RefreshPreviewSellPrice) references 000002770A8153D0.
  3. The referenced object 000002770A8153D0 (The Delegate) is in New Gen (Newspace).
  4. Error: "not found in remsets".

This confirms that the Write Barrier was missing when the Interpreter executed the field assignment (likely inside the Combine implementation or the storing of the combined delegate back to the field).

Because the remset does not record this relationship, the subsequent Minor GC assumes the Delegate is unreachable (if no other roots exist) and reclaims it. When Delegate.Remove is called later, it tries to access this reclaimed object, causing a crash or ArgumentException inside InternalEqualTypes.

Related Issues

We are aware of issue #85318 which discusses missing write barriers, but that issue focuses on native code modifying managed fields. In our case, all operations (add/remove) are performed in pure C#, suggesting the issue lies within the Mono Interpreter's handling of delegate field updates (possibly stfld or specific delegate intrinsics).

Impact

This causes random stability issues on all platforms using the Mono Interpreter (including iOS/Android release builds) that are extremely hard to debug without consistency checks.

Activity

  1. added
    untriaged
    on Feb 27, 2026
  2. dotnet-policy-service commented on Feb 27, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @vitek-karas, @BrzVlad, @kotlarmilos
    See info in area-owners.md if you want to be subscribed.

  3. Liangjia0411 commented on Feb 28, 2026

    @Liangjia0411
    Author

    I apologize for the confusion in my initial report. After deeper investigation, the root cause is NOT a missing write barrier, but an off-by-one error in sgen_card_table_region_begin_scanning (specifically when SGEN_HAVE_OVERLAPPING_CARDS is enabled).

    Root Cause Analysis

    The issue stems from how sgen_card_table_region_begin_scanning iterates using memory addresses (start += CARD_SIZE_IN_BYTES). When the object's start address is misaligned relative to the card boundary (e.g., offset 472), simply adding 512 bytes repeatedly can cause the loop condition start < end to terminate before checking the final card that covers the tail of the object.

    Scenario:

    • Start Address Offset: 472 (inside Card N)
    • Object Size: Spans into Card N+18 (e.g., field at offset 8888).
    • Iteration Logic:
      • The loop checks start + 17*512 (Card N+17).
      • The loop terminates because start + 18*512 >= end.
    • Result: Card N+18 is skipped. If that card was the only dirty one, the reference is missed -> Crash.

    Proposed Fix

    I have locally patched src/mono/mono/sgen/sgen-cardtable.c to perform a safety check after the loop terminates. This ensures the tail card is always scanned.

    static gboolean
    sgen_card_table_region_begin_scanning (mword start, mword size)
    {
        mword end = start + size;
        gboolean check_last = FALSE;
        /*XXX this can be improved to work on words and have a single loop induction var */
        while (start < end) {
            if (sgen_card_table_card_begin_scanning (start))
                return TRUE;
            start += CARD_SIZE_IN_BYTES;
            check_last = TRUE;
        }
    
        // Fix: Ensure the last card is checked if the loop terminated early due to misalignment
        if (check_last && sgen_card_table_card_begin_scanning (start))
            return TRUE;
    
        return FALSE;
    }

    Reference

    I noticed PR #118271 touches related code. Could you please verify if that PR also addresses this alignment/off-by-one issue? If so, is it the intended long-term fix?

  4. BrzVlad commented on Mar 3, 2026

    @BrzVlad
    Member

    @Liangjia0411 Thanks a lot for investigating this!! I submitted a fix for the bug. Note that this code path is only reachable for objects bigger than 8k (los objects) that are not arrays.

  5. Liangjia0411 commented on Mar 4, 2026

    @Liangjia0411
    Author

    thanks

  6. removed
    untriaged
    on Mar 4, 2026
  7. locked and limited conversation to collaborators on Apr 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions