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

Aperta
#138,113 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
8/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
c, csharp, objective-c
Ambito
mobile-dev

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area-System.Runtime.InteropServices untriaged

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:

  1. The GC calls isReferencedCallback. Native code only has a weak reference, so we return 0.
  2. Another thread calls retainWeakReference, turning a weak reference into a strong one. We return true, because trackedObjectEnteredFinalization hasn't been called yet.
  3. 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:

  1. 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.
  2. It locks that side table's lock (SideTable::slock, a spinlock_t, which is an os_unfair_lock). This lock isn't recursive: locking it again on the same thread aborts the process.
  3. While holding the lock, it calls -retainWeakReference on the object.
  4. 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) locks SideTables ()[X].slock, then calls -retainWeakReference, which waits for the GC.
  • GC thread: calls isReferencedCallback for object Y, which calls [Y retainCount], which waits for SideTables ()[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.

Lingua principale
C#
Stelle
18.5k
Fork
5.8k
Merge medio
2g 18h
PR unite (30g)
588

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/runtime

Tutte le issue di dotnet/runtime

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.