diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index 05c498443..e78120dd1 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -154,7 +154,7 @@ internal void AddFinalizedObject(ref IntPtr obj, int run obj = IntPtr.Zero; } - internal void AddDerivedFinalizedObject(ref IntPtr derived, int run) + internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false) { if (derived == IntPtr.Zero) throw new ArgumentNullException(nameof(derived)); @@ -164,7 +164,10 @@ internal void AddDerivedFinalizedObject(ref IntPtr derived, int run) return; } - var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run }; + var pending = new PendingFinalization + { + PyObj = derived, RuntimeRun = run, Deferred = deferred, KeptReference = keptReference, + }; derived = IntPtr.Zero; _derivedQueue.Enqueue(pending); } @@ -254,7 +257,7 @@ internal nint DisposeAll() } #pragma warning disable CS0618 // Type or member is obsolete. OK for internal use - PythonDerivedType.Finalize(derived.PyObj); + PythonDerivedType.Finalize(derived.PyObj, derived.Deferred, derived.KeptReference); #pragma warning restore CS0618 // Type or member is obsolete collected++; @@ -367,6 +370,14 @@ struct PendingFinalization public IntPtr PyObj; public BorrowedReference Ref => new(PyObj); public int RuntimeRun; + /// + /// The .NET object of a Python derived type whose finalization waits until this is handled + /// + public object? Deferred; + /// + /// holds a reference to + /// + public bool KeptReference; #if TRACE_ALLOC public string StackTrace; #endif diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index bcf99bede..74ba31123 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -63,6 +63,8 @@ public ModulePropertyAttribute() [Flags] public enum TypeFlags: long { + /// Python 3.7 calls tp_finalize only when set + HaveFinalize = (1 << 0), HeapType = (1 << 9), BaseType = (1 << 10), Ready = (1 << 12), @@ -188,6 +190,9 @@ internal static ThunkInfo GetThunk(Delegate @delegate) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void N_V(NewReference ob); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void B_V(BorrowedReference ob); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int BPP_I32(BorrowedReference ob, IntPtr a1, IntPtr a2); } diff --git a/src/runtime/Native/ITypeOffsets.cs b/src/runtime/Native/ITypeOffsets.cs index bae8636c5..3d19cb71e 100644 --- a/src/runtime/Native/ITypeOffsets.cs +++ b/src/runtime/Native/ITypeOffsets.cs @@ -52,6 +52,7 @@ interface ITypeOffsets int tp_descr_set { get; } int tp_dict { get; } int tp_dictoffset { get; } + int tp_finalize { get; } int tp_flags { get; } int tp_free { get; } int tp_getattro { get; } diff --git a/src/runtime/Native/TypeOffset.cs b/src/runtime/Native/TypeOffset.cs index 76196bcad..314f3c8f4 100644 --- a/src/runtime/Native/TypeOffset.cs +++ b/src/runtime/Native/TypeOffset.cs @@ -59,6 +59,7 @@ static partial class TypeOffset internal static int tp_descr_set { get; private set; } internal static int tp_dict { get; private set; } internal static int tp_dictoffset { get; private set; } + internal static int tp_finalize { get; private set; } internal static int tp_flags { get; private set; } internal static int tp_free { get; private set; } internal static int tp_getattro { get; private set; } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 6c2c81b13..8c3d2070f 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Python.Runtime.Native; @@ -34,6 +35,33 @@ internal class ClassDerivedObject : ClassObject private static Dictionary assemblyBuilders; private static Dictionary, ModuleBuilder> moduleBuilders; + /// + /// Python objects whose .NET object holds one reference to them, taken in + /// + private static readonly HashSet KeptByManagedObject = new(); + /// + /// Python objects that took back the reference their .NET object kept, in , + /// while .NET may already be finalizing that .NET object + /// + private static readonly HashSet TakenBackByPython = new(); + /// + /// Python objects whose .NET object was finalized while it held the reference taken in + /// , and that weren't passed to .NET since: the next time the GC finds + /// such an object unreachable, nothing else references it and the GC frees the cycle + /// + private static readonly HashSet ReturnedToPython = new(); + /// + /// Guards , and + /// , which the .NET finalizer thread updates in + /// + /// + private static readonly object KeptLock = new(); + /// + /// Nothing else references the wrapper of a .NET object its Python object holds weakly: + /// this keeps it alive as long as the .NET object + /// + private static readonly ConditionalWeakTable WeaklyHeldWrappers = new(); + static ClassDerivedObject() { assemblyBuilders = new Dictionary(); @@ -44,6 +72,14 @@ public static void Reset() { assemblyBuilders = new Dictionary(); moduleBuilders = new Dictionary, ModuleBuilder>(); + lock (KeptLock) + { + KeptByManagedObject.Clear(); + TakenBackByPython.Clear(); + ReturnedToPython.Clear(); + } + WeaklyHeldWrappers.Clear(); + finalizedFlagOffset = GetFinalizedFlagOffset(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -75,6 +111,10 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); + lock (KeptLock) + { + ReturnedToPython.Remove(ob.DangerousGetAddress()); + } // self may be null after Shutdown begun if (self is not null) @@ -83,11 +123,136 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // deallocate the object until the C# object that references it is destroyed. // So we don't call PyObject_GC_Del here and instead we set the python // reference to a weak reference so that the C# object can be collected. - GCHandle oldHandle = GetGCHandle(ob.Borrow()); - GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak); - SetGCHandle(ob.Borrow(), gc); - oldHandle.Free(); + ReplaceGCHandle(ob.Borrow(), self, GCHandleType.Weak); + } + } + + /// + /// Called by the Python cyclic GC on an object it found unreachable from Python, before it clears + /// the cycle. .NET may still reference the object, which Python can't see, so instead of letting + /// the cycle be cleared, the .NET object keeps one reference to the Python object, and the Python + /// object stops keeping the .NET object alive, as does. Python gets that + /// reference back in , and the .NET object releases it when it's finalized. + /// + public static void tp_finalize(BorrowedReference ob) + { + // The GC marks an object finalized before it calls tp_finalize and doesn't call it again + // once marked. Otherwise, it's a direct __del__ call from Python, which still references the object. + if ((FinalizedFlagWord(ob) & FinalizedFlag) == 0) + { + return; + } + + // .NET already let go of the object while Python still referenced it: the GC frees the cycle + lock (KeptLock) + { + if (ReturnedToPython.Remove(ob.DangerousGetAddress())) + { + return; + } + } + + var self = (CLRObject?)GetManagedObject(ob); + // null once the .NET object is gone: the GC frees the cycle + if (self is null) + { + return; + } + + // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again + FinalizedFlagWord(ob) &= ~FinalizedFlag; + Runtime.XIncref(ob); + lock (KeptLock) + { + KeptByManagedObject.Add(ob.DangerousGetAddress()); } + // Another object's __del__ may give Python the object back before the cycle is cleared. + // Tracking resurrection keeps the handle valid until Finalize(IntPtr, object, bool) takes + // the .NET object back after its finalizer ran. + ReplaceGCHandle(ob, self, GCHandleType.WeakTrackResurrection); + } + + /// + /// Called by the .NET finalizer of a Python derived type. Returns true when the .NET object + /// held the Python object since , or Python took it back while .NET + /// may have been finalizing it: Python may still reference the object, so its .NET finalization + /// waits until handles it. + /// + internal static bool DeferFinalization(IntPtr ob, out bool keptReference) + { + lock (KeptLock) + { + keptReference = KeptByManagedObject.Remove(ob); + if (keptReference) + { + ReturnedToPython.Add(ob); + } + return TakenBackByPython.Remove(ob) || keptReference; + } + } + + /// + /// Called when .NET finalized the .NET object of a Python object Python still references: + /// through the cycle, or because Python got the object back without .NET. The Python object + /// keeps the .NET object alive again, as for any object Python holds. + /// + internal static void ReturnToPython(BorrowedReference ob, object managed) + { + if (WeaklyHeldWrappers.TryGetValue(managed, out var self)) + { + ReplaceGCHandle(ob, self, GCHandleType.Normal); + } + } + + /// + /// The GC's finalized flag: bit 0 of _gc_prev since Python 3.8, of gc_refs before + /// + private const nint FinalizedFlag = 1; + + /// + /// Offset from the object to the GC header word that holds + /// + private static nint finalizedFlagOffset; + + private static unsafe ref nint FinalizedFlagWord(BorrowedReference ob) + => ref *(nint*)((byte*)ob.DangerousGetAddress() + finalizedFlagOffset); + + private static nint GetFinalizedFlagOffset() + { + if (Runtime.PyVersion >= new Version(3, 8)) + { + // _gc_prev, the last word of the GC header that precedes the object + return -IntPtr.Size; + } + + // Python 3.7: gc_refs, the third word of a GC header padded to the platform's + // long double alignment. sys.getsizeof adds that header to __sizeof__. + using var list = Runtime.PyList_New(0); + using var sizeOf = Runtime.PyObject_GetAttrString(list.Borrow(), "__sizeof__"); + using var noArgs = Runtime.PyTuple_New(0); + using var size = Runtime.PyObject_CallObject(sizeOf.BorrowOrThrow(), noArgs.Borrow()); + using var getSizeOfArgs = Runtime.PyTuple_New(1); + Runtime.PyTuple_SetItem(getSizeOfArgs.Borrow(), 0, list.Borrow()); + using var sizeWithGCHeader = Runtime.PyObject_CallObject( + Runtime.PySys_GetObject("getsizeof"), getSizeOfArgs.Borrow()); + nint gcHeaderSize = Runtime.PyLong_AsSignedSize_t(sizeWithGCHeader.BorrowOrThrow()) + - Runtime.PyLong_AsSignedSize_t(size.BorrowOrThrow()); + return -gcHeaderSize + 2 * IntPtr.Size; + } + + private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type) + { + if (type != GCHandleType.Normal) + { + WeaklyHeldWrappers.AddOrUpdate(self.inst, self); + } + else + { + WeaklyHeldWrappers.Remove(self.inst); + } + GCHandle oldHandle = GetGCHandle(ob); + SetGCHandle(ob, GCHandle.Alloc(self, type)); + oldHandle.Free(); } /// @@ -113,6 +278,23 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } + bool kept; + lock (KeptLock) + { + ReturnedToPython.Remove(self.DangerousGetAddress()); + kept = KeptByManagedObject.Remove(self.DangerousGetAddress()); + if (kept) + { + TakenBackByPython.Add(self.DangerousGetAddress()); + } + } + if (kept) + { + // Python takes over the reference the .NET object kept in tp_finalize + ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal); + return NewReference.DangerousFromPointer(self.DangerousGetAddress()); + } + var result = new NewReference(self); // when the C# constructor creates the python object it starts as a weak @@ -123,11 +305,7 @@ internal static NewReference ToPython(IPythonDerivedType obj) if (Runtime.Refcount(self) == 1) { Runtime._Py_NewReference(self); - GCHandle weak = GetGCHandle(self); - var clrObject = GetManagedObject(self); - GCHandle gc = GCHandle.Alloc(clrObject, GCHandleType.Normal); - SetGCHandle(self, gc); - weak.Free(); + ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal); // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); @@ -269,7 +447,8 @@ internal static Type CreateDerivedType(string name, } } - // add the destructor so the python object created in the constructor gets destroyed + // add the destructor so the python object created in the constructor gets destroyed, + // then runs the base type's finalizer, unless PyFinalize defers it MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize", MethodAttributes.Family | MethodAttributes.Virtual | @@ -278,12 +457,15 @@ internal static Type CreateDerivedType(string name, typeof(void), Type.EmptyTypes); ILGenerator il = methodBuilder.GetILGenerator(); + Label deferred = il.DefineLabel(); il.Emit(OpCodes.Ldarg_0); #pragma warning disable CS0618 // PythonDerivedType is for internal use only il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(PyFinalize))); #pragma warning restore CS0618 // PythonDerivedType is for internal use only + il.Emit(OpCodes.Brfalse_S, deferred); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance)); + il.MarkLabel(deferred); il.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); @@ -923,16 +1105,55 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec args); } - public static void PyFinalize(IPythonDerivedType obj) + /// + /// Called by the .NET finalizer of a Python derived type + /// + /// + /// Whether the base type's finalizer runs now. When Python may still reference the Python object, + /// .NET finalizes the object again once handled it. + /// + public static bool PyFinalize(IPythonDerivedType obj) { + var self = GetPyObj(obj); + if (ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference)) + { + Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); + return false; + } + // the C# object is being destroyed which must mean there are no more // references to the Python object as well - var self = GetPyObj(obj); Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run); + return true; } - internal static void Finalize(IntPtr derived) + /// The Python object + /// + /// The .NET object, when deferred its finalization + /// + /// + /// The .NET object holds a reference to the Python object, taken in tp_finalize + /// + internal static void Finalize(IntPtr derived, object? deferred = null, bool keptReference = false) { + if (deferred is not null) + { + var ob = new BorrowedReference(derived); + bool referencedByPython = Runtime.Refcount(ob) > (keptReference ? 1 : 0); + if (keptReference) + { + // when it's the last reference, tp_dealloc waits for the .NET object, as for any object + Runtime.XDecref(StolenReference.DangerousFromPointer(derived)); + } + if (referencedByPython) + { + ClassDerivedObject.ReturnToPython(ob, deferred); + } + // finalized once nothing references it, which runs the base type's finalizer + GC.ReRegisterForFinalize(deferred); + return; + } + var @ref = NewReference.DangerousFromPointer(derived); ClassBase.tp_clear(@ref.Borrow()); diff --git a/src/runtime/Types/ReflectedClrType.cs b/src/runtime/Types/ReflectedClrType.cs index 15ea5c2b2..eab7df316 100644 --- a/src/runtime/Types/ReflectedClrType.cs +++ b/src/runtime/Types/ReflectedClrType.cs @@ -112,6 +112,10 @@ static ReflectedClrType AllocateClass(Type clrType) | TypeFlags.HeapType | TypeFlags.BaseType | TypeFlags.HaveGC; + if (Runtime.PyVersion < new Version(3, 8)) + { + type.Flags |= TypeFlags.HaveFinalize; + } return new ReflectedClrType(type.Steal()); } diff --git a/tests/test_subclass.py b/tests/test_subclass.py index 85c50d21a..1b126285d 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -305,3 +305,273 @@ class Derived(BaseClass): import gc gc.collect() + + +def _release_python_and_net_objects(): + """Collect Python cycles and .NET objects, then free the Python objects whose .NET object was finalized""" + import gc + from System import GC + + for _ in range(3): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + # every 200th Python object passed to .NET frees the queued ones + List[System.Object]([object() for _ in range(300)]) + gc.collect() + + +def test_namespaced_subclass_held_by_net_keeps_its_cycle(): + from System import String + + class CycleHolder(System.Object): + __namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_cycle" + + def __init__(self, code): + self.code = code + self.me = self + self.items = [self] + self.items.append(self.items) + + def ToString(self): + return "holder {}".format(self.code) + + class PythonSubclass(CycleHolder): + pass + + # each instance references its class, until it's freed + refcounts = sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass) + held = List[System.Object]() + held.Add(CycleHolder(7)) + held.Add(PythonSubclass(8)) + + for _ in range(2): + _release_python_and_net_objects() + # .NET calls the Python override while only .NET holds the object + assert String.Join[System.Object](",", held) == "holder 7,holder 8" + + holder = held[0] + assert holder.code == 7 + assert holder.me is holder + assert holder.items[0] is holder + assert held[1].code == 8 + del holder + + held.Clear() + _release_python_and_net_objects() + assert (sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass)) == refcounts + + +def test_namespaced_subclass_cycle_is_collected(): + class CycleMember(System.Object): + __namespace__ = "test_namespaced_subclass_cycle_is_collected" + + def __init__(self): + self.me = self + + refcount = sys.getrefcount(CycleMember) + for _ in range(100): + CycleMember() + first, second = CycleMember(), CycleMember() + first.other, second.other = second, first + del first, second + + held = List[System.Object]() + first, second = CycleMember(), CycleMember() + first.other, second.other = second, first + first.code = 1 + held.Add(second) + del first, second + + _release_python_and_net_objects() + assert held[0].other.code == 1 + assert held[0].other.other is held[0] + assert sys.getrefcount(CycleMember) == refcount + 2 + + held.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(CycleMember) == refcount + + +def test_namespaced_subclass_direct_del_call_keeps_net_object(): + class DirectDelCall(System.Object): + __namespace__ = "test_namespaced_subclass_direct_del_call_keeps_net_object" + + def __init__(self): + self.me = self + + instance = DirectDelCall() + instance.__del__() + _release_python_and_net_objects() + instance.GetHashCode() + assert instance.me is instance + + +def _resurrect_through_python(cls, survivors): + """Drop an instance in a cycle whose other member's __del__ gives Python the instance back""" + import gc + from System import GC + + class Resurrector: + def __init__(self, owner): + self.owner = owner + + def __del__(self): + survivors.append(self.owner) + + owner = cls() + owner.other = Resurrector(owner) + del owner + + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + + +def test_namespaced_subclass_resurrected_by_python_keeps_net_object(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_keeps_net_object" + + def __init__(self): + self.code = 7 + + survivors = [] + _resurrect_through_python(Resurrected, survivors) + # before the finalized .NET object is handled + survivors[0].GetHashCode() + + _release_python_and_net_objects() + assert survivors[0].GetType().Name == "Resurrected" + assert survivors[0].code == 7 + + +def test_namespaced_subclass_resurrected_by_python_is_collected(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_is_collected" + + def __init__(self): + self.code = 7 + + refcount = sys.getrefcount(Resurrected) + survivors = [] + _resurrect_through_python(Resurrected, survivors) + + _release_python_and_net_objects() + assert survivors[0].code == 7 + assert survivors[0].other.owner is survivors[0] + + survivors.clear() + _release_python_and_net_objects() + assert sys.getrefcount(Resurrected) == refcount + + +def test_namespaced_subclass_resurrected_by_python_and_passed_to_net(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_and_passed_to_net" + + def __init__(self): + self.code = 7 + + from Python.Runtime import Finalizer + + refcount = sys.getrefcount(Resurrected) + survivors = [] + held = List[System.Object]() + threshold = Finalizer.Instance.Threshold + # .NET gets the instance back before the finalized .NET object is handled + Finalizer.Instance.Threshold = 1000000 + try: + _resurrect_through_python(Resurrected, survivors) + held.Add(survivors[0]) + alias = held[0] + assert alias is survivors[0] + # the next Python object passed to .NET handles the finalized .NET object + Finalizer.Instance.Threshold = 1 + List[System.Object]([object()]) + finally: + Finalizer.Instance.Threshold = threshold + assert alias.code == 7 + + # Python lets go first, then .NET + survivors.clear() + del alias + _release_python_and_net_objects() + assert held[0].code == 7 + assert held[0].GetType().Name == "Resurrected" + + held.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(Resurrected) == refcount + + +def test_namespaced_subclass_taken_back_by_python_then_released(): + class TakenBack(System.Object): + __namespace__ = "test_namespaced_subclass_taken_back_by_python_then_released" + + def __init__(self): + self.code = 7 + self.me = self + + refcount = sys.getrefcount(TakenBack) + held = List[System.Object]() + held.Add(TakenBack()) + _release_python_and_net_objects() + + instance = held[0] + assert instance.code == 7 + instance.me = None + del instance + held.Clear() + for _ in range(2): + _release_python_and_net_objects() + assert sys.getrefcount(TakenBack) == refcount + + +@pytest.mark.parametrize("cycle", ["none", "self", "resurrected"]) +def test_namespaced_subclass_runs_base_finalizer_once(cycle): + from Python.Test import FinalizedConstructorTest + + class Finalized(FinalizedConstructorTest): + __namespace__ = "test_namespaced_subclass_runs_base_finalizer_once_{}".format(cycle) + + def __init__(self): + self.code = 7 + + before = FinalizedConstructorTest.Finalized + survivors = [] + if cycle == "resurrected": + _resurrect_through_python(Finalized, survivors) + _release_python_and_net_objects() + assert survivors[0].code == 7 + survivors.clear() + else: + instance = Finalized() + if cycle == "self": + instance.me = instance + del instance + + for _ in range(3): + _release_python_and_net_objects() + assert FinalizedConstructorTest.Finalized - before == 1 + + +@pytest.mark.parametrize("in_cycle", [False, True]) +def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle): + class HeldByNet(System.Object): + __namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_wrapper_{}".format(in_cycle) + + def __init__(self, code): + self.code = code + if in_cycle: + self.me = self + + held = List[System.Object]() + held.Add(HeldByNet(7)) + for _ in range(2): + _release_python_and_net_objects() + + instance = held[0] + assert instance.code == 7 + assert held.Contains(instance) + assert instance.GetType().Name == "HeldByNet" + del instance