Skip to content

Commit 8482a4d

Browse files
Keep the .NET object of a __namespace__ subclass that Python resurrects, and support Python 3.7
When another object's __del__ gave Python back an instance the cycle GC had handed to .NET, its .NET object could be collected while Python still used it. The finalized .NET object now stays reachable until the queued finalization runs, which gives the Python object a strong handle to it again when Python still references it. On Python 3.7, the GC's finalized flag is in gc_refs, and tp_finalize only runs for types with Py_TPFLAGS_HAVE_FINALIZE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4efed34 commit 8482a4d

5 files changed

Lines changed: 144 additions & 14 deletions

File tree

‎src/runtime/Finalizer.cs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ internal void AddFinalizedObject(ref IntPtr obj, int run
154154
obj = IntPtr.Zero;
155155
}
156156

157-
internal void AddDerivedFinalizedObject(ref IntPtr derived, int run)
157+
internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object managed)
158158
{
159159
if (derived == IntPtr.Zero)
160160
throw new ArgumentNullException(nameof(derived));
@@ -164,7 +164,7 @@ internal void AddDerivedFinalizedObject(ref IntPtr derived, int run)
164164
return;
165165
}
166166

167-
var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run };
167+
var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run, Managed = managed };
168168
derived = IntPtr.Zero;
169169
_derivedQueue.Enqueue(pending);
170170
}
@@ -254,7 +254,7 @@ internal nint DisposeAll()
254254
}
255255

256256
#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use
257-
PythonDerivedType.Finalize(derived.PyObj);
257+
PythonDerivedType.Finalize(derived.PyObj, derived.Managed);
258258
#pragma warning restore CS0618 // Type or member is obsolete
259259

260260
collected++;
@@ -367,6 +367,10 @@ struct PendingFinalization
367367
public IntPtr PyObj;
368368
public BorrowedReference Ref => new(PyObj);
369369
public int RuntimeRun;
370+
/// <summary>
371+
/// The finalized .NET object of a Python derived type, kept alive until it's handled
372+
/// </summary>
373+
public object? Managed;
370374
#if TRACE_ALLOC
371375
public string StackTrace;
372376
#endif

‎src/runtime/Interop.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ public ModulePropertyAttribute()
6363
[Flags]
6464
public enum TypeFlags: long
6565
{
66+
/// <summary>Python 3.7 calls tp_finalize only when set</summary>
67+
HaveFinalize = (1 << 0),
6668
HeapType = (1 << 9),
6769
BaseType = (1 << 10),
6870
Ready = (1 << 12),

‎src/runtime/Types/ClassDerived.cs‎

Lines changed: 73 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ internal class ClassDerivedObject : ClassObject
4545
/// </summary>
4646
internal static readonly HashSet<IntPtr> ReleasedByManagedObject = new();
4747
/// <summary>
48+
/// Python objects .NET let go of while Python still referenced them, see <see cref="ReturnToPython"/>
49+
/// </summary>
50+
private static readonly HashSet<IntPtr> ReturnedToPython = new();
51+
/// <summary>
4852
/// Nothing else references the wrapper of a .NET object its Python object holds weakly:
4953
/// this keeps it alive as long as the .NET object
5054
/// </summary>
@@ -62,7 +66,9 @@ public static void Reset()
6266
moduleBuilders = new Dictionary<Tuple<string, string>, ModuleBuilder>();
6367
KeptByManagedObject.Clear();
6468
ReleasedByManagedObject.Clear();
69+
ReturnedToPython.Clear();
6570
WeaklyHeldWrappers.Clear();
71+
finalizedFlagOffset = GetFinalizedFlagOffset();
6672
}
6773

6874
internal ClassDerivedObject(Type tp) : base(tp)
@@ -94,6 +100,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo
94100

95101
// don't let the python GC destroy this object
96102
Runtime.PyObject_GC_UnTrack(ob.Borrow());
103+
ReturnedToPython.Remove(ob.DangerousGetAddress());
97104

98105
if (ReleasedByManagedObject.Remove(ob.DangerousGetAddress()))
99106
{
@@ -123,7 +130,13 @@ public static void tp_finalize(BorrowedReference ob)
123130
{
124131
// The GC marks an object finalized before it calls tp_finalize and doesn't call it again
125132
// once marked. Otherwise, it's a direct __del__ call from Python, which still references the object.
126-
if ((GCPrev(ob) & FinalizedFlag) == 0)
133+
if ((FinalizedFlagWord(ob) & FinalizedFlag) == 0)
134+
{
135+
return;
136+
}
137+
138+
// .NET already let go of the object while Python still referenced it: the GC frees the cycle
139+
if (ReturnedToPython.Remove(ob.DangerousGetAddress()))
127140
{
128141
return;
129142
}
@@ -136,26 +149,70 @@ public static void tp_finalize(BorrowedReference ob)
136149
}
137150

138151
// the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again
139-
GCPrev(ob) &= ~FinalizedFlag;
152+
FinalizedFlagWord(ob) &= ~FinalizedFlag;
140153
Runtime.XIncref(ob);
141154
KeptByManagedObject.Add(ob.DangerousGetAddress());
142-
ReplaceGCHandle(ob, self, GCHandleType.Weak);
155+
// Another object's __del__ may give Python the object back before the cycle is cleared.
156+
// Tracking resurrection keeps the handle valid until Finalize(IntPtr, object) takes the
157+
// .NET object back after its finalizer ran.
158+
ReplaceGCHandle(ob, self, GCHandleType.WeakTrackResurrection);
159+
}
160+
161+
/// <summary>
162+
/// Called when the .NET object kept the Python object since <see cref="tp_finalize"/> and was
163+
/// finalized while Python still references the Python object: through the cycle, or because Python
164+
/// got the object back without .NET. The Python object keeps the .NET object alive again, as for
165+
/// any object Python holds, and the next time the GC finds the cycle unreachable, it frees it.
166+
/// </summary>
167+
internal static void ReturnToPython(BorrowedReference ob, object managed)
168+
{
169+
if (WeaklyHeldWrappers.TryGetValue(managed, out var self))
170+
{
171+
ReplaceGCHandle(ob, self, GCHandleType.Normal);
172+
GC.ReRegisterForFinalize(managed);
173+
ReturnedToPython.Add(ob.DangerousGetAddress());
174+
}
143175
}
144176

145177
/// <summary>
146-
/// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev
178+
/// The GC's finalized flag: bit 0 of _gc_prev since Python 3.8, of gc_refs before
147179
/// </summary>
148180
private const nint FinalizedFlag = 1;
149181

150182
/// <summary>
151-
/// _gc_prev, the last field of the GC header that precedes the object
183+
/// Offset from the object to the GC header word that holds <see cref="FinalizedFlag"/>
152184
/// </summary>
153-
private static unsafe ref nint GCPrev(BorrowedReference ob)
154-
=> ref *((nint*)ob.DangerousGetAddress() - 1);
185+
private static nint finalizedFlagOffset;
186+
187+
private static unsafe ref nint FinalizedFlagWord(BorrowedReference ob)
188+
=> ref *(nint*)((byte*)ob.DangerousGetAddress() + finalizedFlagOffset);
189+
190+
private static nint GetFinalizedFlagOffset()
191+
{
192+
if (Runtime.PyVersion >= new Version(3, 8))
193+
{
194+
// _gc_prev, the last word of the GC header that precedes the object
195+
return -IntPtr.Size;
196+
}
197+
198+
// Python 3.7: gc_refs, the third word of a GC header padded to the platform's
199+
// long double alignment. sys.getsizeof adds that header to __sizeof__.
200+
using var list = Runtime.PyList_New(0);
201+
using var sizeOf = Runtime.PyObject_GetAttrString(list.Borrow(), "__sizeof__");
202+
using var noArgs = Runtime.PyTuple_New(0);
203+
using var size = Runtime.PyObject_CallObject(sizeOf.BorrowOrThrow(), noArgs.Borrow());
204+
using var getSizeOfArgs = Runtime.PyTuple_New(1);
205+
Runtime.PyTuple_SetItem(getSizeOfArgs.Borrow(), 0, list.Borrow());
206+
using var sizeWithGCHeader = Runtime.PyObject_CallObject(
207+
Runtime.PySys_GetObject("getsizeof"), getSizeOfArgs.Borrow());
208+
nint gcHeaderSize = Runtime.PyLong_AsSignedSize_t(sizeWithGCHeader.BorrowOrThrow())
209+
- Runtime.PyLong_AsSignedSize_t(size.BorrowOrThrow());
210+
return -gcHeaderSize + 2 * IntPtr.Size;
211+
}
155212

156213
private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type)
157214
{
158-
if (type == GCHandleType.Weak)
215+
if (type != GCHandleType.Normal)
159216
{
160217
WeaklyHeldWrappers.AddOrUpdate(self.inst, self);
161218
}
@@ -191,6 +248,7 @@ internal static NewReference ToPython(IPythonDerivedType obj)
191248
return default;
192249
}
193250

251+
ReturnedToPython.Remove(self.DangerousGetAddress());
194252
if (KeptByManagedObject.Remove(self.DangerousGetAddress()))
195253
{
196254
// Python takes over the reference the .NET object kept in tp_finalize
@@ -1009,16 +1067,20 @@ public static void PyFinalize(IPythonDerivedType obj)
10091067
// the C# object is being destroyed which must mean there are no more
10101068
// references to the Python object as well
10111069
var self = GetPyObj(obj);
1012-
Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run);
1070+
Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj);
10131071
}
10141072

1015-
internal static void Finalize(IntPtr derived)
1073+
internal static void Finalize(IntPtr derived, object? managed = null)
10161074
{
10171075
if (ClassDerivedObject.KeptByManagedObject.Remove(derived))
10181076
{
1019-
// the Python object may still be part of a cycle: Python frees it once nothing references it
1077+
// tp_dealloc frees the Python object if this was its last reference
10201078
ClassDerivedObject.ReleasedByManagedObject.Add(derived);
10211079
Runtime.XDecref(StolenReference.DangerousFromPointer(derived));
1080+
if (ClassDerivedObject.ReleasedByManagedObject.Remove(derived) && managed is not null)
1081+
{
1082+
ClassDerivedObject.ReturnToPython(new BorrowedReference(derived), managed);
1083+
}
10221084
return;
10231085
}
10241086

‎src/runtime/Types/ReflectedClrType.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ static ReflectedClrType AllocateClass(Type clrType)
112112
| TypeFlags.HeapType
113113
| TypeFlags.BaseType
114114
| TypeFlags.HaveGC;
115+
if (Runtime.PyVersion < new Version(3, 8))
116+
{
117+
type.Flags |= TypeFlags.HaveFinalize;
118+
}
115119

116120
return new ReflectedClrType(type.Steal());
117121
}

‎tests/test_subclass.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,64 @@ def __init__(self):
407407
assert instance.me is instance
408408

409409

410+
def _resurrect_through_python(cls, survivors):
411+
"""Drop an instance in a cycle whose other member's __del__ gives Python the instance back"""
412+
import gc
413+
from System import GC
414+
415+
class Resurrector:
416+
def __init__(self, owner):
417+
self.owner = owner
418+
419+
def __del__(self):
420+
survivors.append(self.owner)
421+
422+
owner = cls()
423+
owner.other = Resurrector(owner)
424+
del owner
425+
426+
gc.collect()
427+
GC.Collect()
428+
GC.WaitForPendingFinalizers()
429+
430+
431+
def test_namespaced_subclass_resurrected_by_python_keeps_net_object():
432+
class Resurrected(System.Object):
433+
__namespace__ = "test_namespaced_subclass_resurrected_by_python_keeps_net_object"
434+
435+
def __init__(self):
436+
self.code = 7
437+
438+
survivors = []
439+
_resurrect_through_python(Resurrected, survivors)
440+
# before the finalized .NET object is handled
441+
survivors[0].GetHashCode()
442+
443+
_release_python_and_net_objects()
444+
assert survivors[0].GetType().Name == "Resurrected"
445+
assert survivors[0].code == 7
446+
447+
448+
def test_namespaced_subclass_resurrected_by_python_is_collected():
449+
class Resurrected(System.Object):
450+
__namespace__ = "test_namespaced_subclass_resurrected_by_python_is_collected"
451+
452+
def __init__(self):
453+
self.code = 7
454+
455+
refcount = sys.getrefcount(Resurrected)
456+
survivors = []
457+
_resurrect_through_python(Resurrected, survivors)
458+
459+
_release_python_and_net_objects()
460+
assert survivors[0].code == 7
461+
assert survivors[0].other.owner is survivors[0]
462+
463+
survivors.clear()
464+
_release_python_and_net_objects()
465+
assert sys.getrefcount(Resurrected) == refcount
466+
467+
410468
@pytest.mark.parametrize("in_cycle", [False, True])
411469
def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle):
412470
class HeldByNet(System.Object):

0 commit comments

Comments
 (0)