Conversation
…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: 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. |
Member
Author
|
/cc @dotnet/gc @jkotas @rolfbjarne @VSadov |
Contributor
|
Tagging subscribers to this area: @anicka-net, @dotnet/gc |
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
marked this pull request as ready for review
November 26, 2026 22:19
AaronRobinsonMSFT
requested review from
MichalStrehovsky,
steveisok and
vitek-karas
as code owners
November 26, 2026 22:19
Member
Author
|
I've updated #138113 with the new API. Once that is approved, we can get this merged in. |
3 tasks
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
ObjectiveCMarshallets an interop client (macios) tell the GC about this. During each GC, the runtime calls the client:BeginEndCallback(begin)IsReferencedCallbackTrackedObjectEnteredFinalizationBeginEndCallback(end)macios answers
IsReferencedCallbackby 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 itThe 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
IsReferencedCallbackreturns, the answer is final.objc_loadWeakRetainedcalls the object's-retainWeakReferenceoverride while holding an Objective-C side-table lock.IsReferencedCallbackcalls-retainCount, which takes the same kind of lock. If the override waits for the GC (that is, blocks) while the GC is still callingretainCount, 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)"]HaveReferencesChangedCallbackis called once per GC, after the lastIsReferencedCallbackand 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 callIsReferencedCallbackagain in that GC; those objects are reconsidered in the next GC.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
All initialization arguments, including the exception propagation handler, are grouped in the struct. Passing it as
inallows the struct to grow without changing the method signature or increasing the size of the value passed by copy.The existing
Initializeoverload keeps its current behavior, except that End also moves after finalization notifications.What macios does today
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
IsReferencedCallbackreturning 0 andTrackedObjectEnteredFinalizationmarking 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 finalizationchangedand open the gate.-retainWeakReferencewhile the gate is open: succeed as today and setchanged(lock-free, no waiting).HaveReferencesChangedCallback: close the gate and readchangedin one atomic step, so no weak load can slip in between them. Return the value.-retainWeakReferencewhile the gate is closed: wait until End, then fail if the object was marked finalizing, otherwise succeed.TrackedObjectEnteredFinalization: mark the object finalizing, as today.Every weak load then lands on one side of a single decision point:
Why waiting is safe now
The issue says
-retainWeakReferencemust never wait for the GC, because the GC may need the same side-table lock to call-retainCount. That's true whileIsReferencedCallbackcalls are still happening. The new callback marks the point where they stop: afterHaveReferencesChangedCallback, the GC doesn't callIsReferencedCallbackagain in that GC. Waiting from that point until End is safe, as long as macios'sTrackedObjectEnteredFinalizationand 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.