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

Abierto
#138,113 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
8/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
c, csharp, objective-c
Área
mobile-dev

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
C#
Estrellas
18.5k
Forks
5.8k
Merge medio
2 d 18 h
PR fusionados (30 d)
588

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de dotnet/runtime

Todos los issues de dotnet/runtime

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.