Registry Mirror
Skip to content

Conversation

@AaronRobinsonMSFT

@AaronRobinsonMSFT AaronRobinsonMSFT commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Objective-C reference tracking: let the client report references that changed during a GC

Background: how Objective-C reference tracking works

On Apple platforms, a managed object can have a native Objective-C object paired with it. The native side controls lifetime: as long as native code holds the Objective-C object, the managed object must stay alive, because it may hold state that native code will use later.

ObjectiveCMarshal lets an interop client (macios) tell the GC about this. During each GC, the runtime calls the client:

Callback When Purpose
BeginEndCallback (begin) Before tracking queries Client prepares for the GC
IsReferencedCallback For each tracked object Client answers "does native code still hold this object?"
TrackedObjectEnteredFinalization For each tracked object the GC will finalize Client learns the object is dead
BeginEndCallback (end) After finalization notifications Client resumes normal operation

macios answers IsReferencedCallback by checking the native retain count.

The problem

Native code can also hold an Objective-C weak reference. A weak reference doesn't show up in the retain count, so the GC is told "not referenced". But at any time, on any thread, native code can turn that weak reference back into a strong one (objc_loadWeakRetained). Those threads aren't running managed code, so the GC doesn't suspend them.

That creates a window between "the client answered" and "the GC acted on the answer":

sequenceDiagram
    participant GC as GC thread
    participant C as macios callbacks
    participant N as Native thread

    GC->>C: IsReferenced(A)?
    C-->>GC: 0 (only weak references)
    N->>C: objc_loadWeakRetained(A)
    C-->>N: retained (A isn't finalizing yet)
    Note over N: Native code now holds A strongly
    GC->>C: TrackedObjectEnteredFinalization(A)
    Note over GC,N: A's managed object is finalized while native code uses it
Loading

The result is a native object whose managed peer has been finalized. Its managed state is lost.

Why the client can't fix this alone today

  1. The client has no way to tell the GC "my answer is stale." After IsReferencedCallback returns, the answer is final.
  2. End callback comes too early. The End callback runs before the GC decides what to finalize, so the client can't use Begin/End to keep weak loads blocked until finalization decisions are made.
  3. A per-object "can I finalize this?" callback isn't enough. If B references A and the client keeps B alive, A is kept alive too, after the client may have already told native code that A was gone. Any fix has to let the GC keep the whole reachable graph alive.
  4. Lock ordering. objc_loadWeakRetained calls the object's -retainWeakReference override while holding an Objective-C side-table lock. IsReferencedCallback calls -retainCount, which takes the same kind of lock. If the override waits for the GC (that is, blocks) while the GC is still calling retainCount, the two threads can deadlock. The issue has the full details.

The fix

The runtime adds one new callback, HaveReferencesChangedCallback, and moves the End callback.

flowchart TD
    B[Begin] --> Q[IsReferenced for each tracked object]
    Q --> H{"HaveReferencesChanged? (new)"}
    H -- "0: answers still valid" --> W
    H -- "1: something changed" --> R["Treat every unmarked tracked object as referenced<br/>and mark everything reachable from it"]
    R --> W[Clear weak references, disconnect proxies]
    W --> F[TrackedObjectEnteredFinalization for dead tracked objects]
    F --> E["End (moved here)"]
Loading
  • HaveReferencesChangedCallback is called once per GC, after the last IsReferencedCallback and before the GC acts on the answers. If the client returns 1, the GC keeps alive every tracked object it hasn't already found alive, along with everything reachable from them. The GC doesn't call IsReferencedCallback again in that GC; those objects are reconsidered in the next GC.
  • End callback now runs after finalization notifications. By End, the client has been told every tracked object the GC chose to finalize.

Keeping everything alive is deliberately conservative: it keeps whole graphs alive correctly, and it doesn't need the client to say which object changed. The cost is that an object may survive one extra GC. This can also become degenerate and objects stay alive longer if there are many of these weak reference creation races - current data says this is rare.

New API

namespace System.Runtime.InteropServices.ObjectiveC;

public unsafe struct ObjectiveCReferenceTrackingCallbacks
{
    public delegate* unmanaged<void> BeginEndCallback { get; set; }
    public delegate* unmanaged<IntPtr, int> IsReferencedCallback { get; set; }
    public delegate* unmanaged<int> HaveReferencesChangedCallback { get; set; }
    public delegate* unmanaged<IntPtr, void> TrackedObjectEnteredFinalization { get; set; }
    public ObjectiveCMarshal.UnhandledExceptionPropagationHandler UnhandledExceptionPropagationHandler { get; set; }
}

public static class ObjectiveCMarshal
{
    public static void Initialize(
        in ObjectiveCReferenceTrackingCallbacks callbacks);
}

All initialization arguments, including the exception propagation handler, are grouped in the struct. Passing it as in allows the struct to grow without changing the method signature or increasing the size of the value passed by copy.

The existing Initialize overload keeps its current behavior, except that End also moves after finalization notifications.

What macios does today

  • Begin/End: takes and releases an internal lock that protects framework-peer handoff. It doesn't block weak loads.
  • IsReferencedCallback: returns 1 if the native retain count shows native references.
  • TrackedObjectEnteredFinalization: marks the object as finalizing.
  • -retainWeakReference: fails if the object is marked finalizing; otherwise it succeeds.

The race is the gap between IsReferencedCallback returning 0 and TrackedObjectEnteredFinalization marking the object.

What macios needs to do

sequenceDiagram
    participant GC as GC thread
    participant C as macios callbacks
    participant N as Native thread

    GC->>C: Begin
    Note over C: changed = false, gate open
    GC->>C: IsReferenced(A)?
    C-->>GC: 0
    N->>C: -retainWeakReference(A)
    Note over C: gate open: succeed, set changed = true
    GC->>C: HaveReferencesChanged?
    Note over C: atomically close gate and read changed
    C-->>GC: 1
    Note over GC: A and its graph survive this GC
    N->>C: -retainWeakReference(B)
    Note over C: gate closed: wait for End
    GC->>C: TrackedObjectEnteredFinalization(...)
    GC->>C: End
    Note over C: open gate, wake waiters
    Note over C: B succeeds or fails based on finalization
Loading
  1. Begin: reset changed and open the gate.
  2. -retainWeakReference while the gate is open: succeed as today and set changed (lock-free, no waiting).
  3. HaveReferencesChangedCallback: close the gate and read changed in one atomic step, so no weak load can slip in between them. Return the value.
  4. -retainWeakReference while the gate is closed: wait until End, then fail if the object was marked finalizing, otherwise succeed.
  5. TrackedObjectEnteredFinalization: mark the object finalizing, as today.
  6. End: open the gate and wake the waiting threads.

Every weak load then lands on one side of a single decision point:

  • Before the gate closes: the GC is told something changed, so the object survives.
  • After the gate closes: the load waits until the GC has finished finalization decisions, and then gets a definite answer.

Why waiting is safe now

The issue says -retainWeakReference must never wait for the GC, because the GC may need the same side-table lock to call -retainCount. That's true while IsReferencedCallback calls are still happening. The new callback marks the point where they stop: after HaveReferencesChangedCallback, the GC doesn't call IsReferencedCallback again in that GC. Waiting from that point until End is safe, as long as macios's TrackedObjectEnteredFinalization and End don't take side-table locks (they don't need to).

Resolves #138113

Note

This PR description was drafted with help from GitHub Copilot.

…ring GC

During a GC, the runtime asks the Objective-C interop client whether each
tracked object is still referenced. Native code can obtain a strong reference
to an object through an Objective-C weak reference after that query returns,
so the GC may collect an object that native code is about to use. The
existing Objective-C marshalling callbacks gave the client no way to report
this change, and no way to synchronize with the end of the GC.

Add ObjectiveCReferenceTrackingCallbacks and an ObjectiveCMarshal.Initialize
overload that accepts a HaveReferencesChanged callback. When the client
reports a change, the GC conservatively promotes the tracked objects before
clearing weak references and disconnecting reference tracker proxies. The
End callback now runs after finalization scanning so the client can
synchronize through it.

Fixes both CoreCLR and NativeAOT. Adds regression tests for the existing and
new initialization APIs.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c714f067-8bfb-47b6-b786-d794b5d7ccef
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 4 pipeline(s).
11 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@AaronRobinsonMSFT

Copy link
Copy Markdown
Member Author

/cc @dotnet/gc @jkotas @rolfbjarne @VSadov

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @anicka-net, @dotnet/gc
See info in area-owners.md if you want to be subscribed.

@rolfbjarne

Copy link
Copy Markdown
Member

I've build this PR locally, adopted the required changes in dotnet/macios, and I can verify it works (current set of dotnet/macios changes in dotnet/macios#27476, but it won't build on CI until this change has flowed to us).

I also tested this PR without any dotnet/macios changes (to check if existing workloads continue to work after this PR), and didn't find any problems.

@AaronRobinsonMSFT
AaronRobinsonMSFT marked this pull request as ready for review November 26, 2026 22:19
@AaronRobinsonMSFT AaronRobinsonMSFT added the NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) label Nov 26, 2026
@AaronRobinsonMSFT

Copy link
Copy Markdown
Member Author

I've updated #138113 with the new API. Once that is approved, we can get this merged in.

Include the exception propagation handler and pass the struct by readonly reference. Keep the existing Initialize overload unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c714f067-8bfb-47b6-b786-d794b5d7ccef

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-GC-coreclr NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons)

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

ObjectiveCMarshal: an Objective-C weak reference can come back to life while the GC finalizes its managed object

2 participants