ObjectiveCMarshal: an Objective-C weak reference can come back to life while the GC finalizes its managed object
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 8/100
- Issue type
- Bug
- Clarity
- Mostly clear
- Activity status
- Active
- Tech stack
- c, csharp, objective-c
- Domain
- mobile-dev
Research direction
The race sits between the Objective-C runtime's objc_loadWeakRetained and the managed ObjectiveCMarshal reference-tracking callbacks in runtime/runtime.m. Start by reading the retainWeakReference override and the framework_peer_release_lock begin/end logic there. Done would be a lock-free ordering scheme (for example, a per-object atomic state where the GC and retainWeakReference race to win) that passes the finalization tests, without ever waiting on the GC from inside the override.
Written by the indexing model from the issue text.
Description
The problem
In .NET for Apple platforms, a managed subclass of NSObject has a native Objective-C object behind it. The managed object must stay alive as long as native code uses the native object, because it can hold managed state.
We use ObjectiveCMarshal reference tracking for this. When the GC finds no managed references to such an object, it calls our isReferencedCallback. We check the native retain count, and if native code still holds the object, we return 1 to keep it alive.
This breaks when native objects are referenced using Objective-C weak references:
Native code can hold a weak reference to the object, which we don't see, and later turn it into a strong one (by calling objc_loadWeakRetained). Technically, Objective-C calls the retainWeakReference selector (which we override) on an NSObject subclass. This selector must return true if the object was retained (at which point the caller has a strong reference), or false if the object couldn't be retained. In our override, we return false if the managed peer has entered finalization (i.e. the trackedObjectEnteredFinalization callback has been called for the object).
The problem is that retainWeakReference can be called on any thread, even a thread the GC doesn't suspend (any thread that isn't running managed code), so timing can be:
- The GC calls
isReferencedCallback. Native code only has a weak reference, so we return 0. - Another thread calls
retainWeakReference, turning a weak reference into a strong one. We returntrue, becausetrackedObjectEnteredFinalizationhasn't been called yet. - The GC queues the managed object for finalization and calls
trackedObjectEnteredFinalization.
Native code now uses an object whose managed object is being finalized. Its managed state is lost: later calls from native code can fail, or we create a new managed object without the original state.
The begin/end callback doesn't help either: the "end" call comes before the GC decides what to finalize.
Background and a repro: dotnet/macios#27374.
What we'd need
We need the GC to make the final decision and the weak-to-strong check happen in a fixed order, so one of these is always true:
- The weak reference became strong first: the managed object (and everything it references) survives this GC and isn't finalized.
- The GC decided first: any later attempt to turn a weak reference into a strong one fails.
A simple "can this object be finalized?" callback isn't enough. If we say yes for object A and no for object B, and B references A, then keeping B alive also keeps A alive, after we already told native code that A is gone.
Additional limits: lock ordering
Our retainWeakReference override can't call managed code, wait for the GC, or take any lock the GC holds. The GC side has a matching limit. Here's why.
objc_loadWeakRetained (objc4 source) does this:
- It picks the side table for the object. The Objective-C runtime has a fixed array of side tables (8 on iOS devices, 64 elsewhere), and picks one by hashing the object's address. Many unrelated objects share each side table.
- It locks that side table's lock (
SideTable::slock, aspinlock_t, which is anos_unfair_lock). This lock isn't recursive: locking it again on the same thread aborts the process. - While holding the lock, it calls
-retainWeakReferenceon the object. - It unlocks the side table.
The GC's isReferencedCallback calls -retainCount, which calls objc_object::rootRetainCount (source). That always takes the same side table lock (sidetable_lock ()), even when the count is stored inline.
That leads to two problems:
Re-entrancy. Anything -retainWeakReference does must not touch the same side table. A retain, release, retainCount, or weak reference operation on any object whose address hashes to the same side table would lock it again and abort. Managed code, and most runtime code, can't promise that. (For the same reason, we can't even look up associated objects in our override: that caused a lock-order deadlock with fork, see dotnet/macios#26844.)
Deadlock with the GC. Say our override waited for the GC in any way: by entering managed code (which blocks while the GC runs), or by taking a lock the GC holds. Then:
- Thread N (a native thread, not suspended):
objc_loadWeakRetained (X)locksSideTables ()[X].slock, then calls-retainWeakReference, which waits for the GC. - GC thread: calls
isReferencedCallbackfor object Y, which calls[Y retainCount], which waits forSideTables ()[Y].slock.
If X and Y hash to the same side table (X and Y can be the same object, but don't have to be), neither thread can continue. With only 8 side tables on iOS devices, this would happen often.
This is also why we can't close the race on our side by making the override take a lock the GC holds. For example, our begin/end callback holds a lock (framework_peer_release_lock in runtime/runtime.m) between "begin" and "end". If -retainWeakReference took that lock, it would deadlock exactly as described above.
The matching limit on the GC side: a GC callback may only wait for a lock if the thread holding it never waits for the GC while holding it. Side table locks are fine as long as -retainWeakReference never waits for the GC. So whatever coordination we add must be lock-free on our side (for example, an atomic compare-and-swap of a per-object state: the GC callback marks the object "finalizing", and -retainWeakReference marks it "retained"; whichever comes first wins).
[!NOTE]
This issue was drafted with help from GitHub Copilot.
- Dominant language
- C#
- Stars
- 18.5k
- Forks
- 5.8k
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 588
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/runtime
-
area-CodeGen-coreclr untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
dotnet/runtime#138181 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Collections untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
dotnet/runtime#138090 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Text.Json untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
dotnet/runtime#138089 · 1 comment ·
Maintainers usually reply within 1 day
-
area-Setup untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
dotnet/runtime#137376 · 1 comment ·
Maintainers usually reply within 1 day
-
area-System.Memory untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
dotnet/runtime#137334 · 4 comments ·
Maintainers usually reply within 1 day
Similar issues
-
Add `net10.0`Open
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
dotnet-outdated/dotnet-outdated#871 ·
Maintainers usually reply within 1 day
-
triage/untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
unoplatform/uno#26676 ·
Maintainers usually reply within 1 day
-
.NET bug
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
jhaizhou-ops/S2Arm#2177 · 3 comments ·
Maintainers usually reply within 1 day