diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index 47e592d16..31975ff16 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -552,6 +552,10 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType, if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type)) { + if (tmp is IPythonDerivedType) + { + ClassDerivedObject.PassedToManaged(value); + } result = tmp; return true; } diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index 05c498443..9791bee72 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -154,19 +154,24 @@ internal void AddFinalizedObject(ref IntPtr obj, int run obj = IntPtr.Zero; } - internal void AddDerivedFinalizedObject(ref IntPtr derived, int run) + /// Whether the object was queued, which it isn't while is false + internal bool AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false) { if (derived == IntPtr.Zero) throw new ArgumentNullException(nameof(derived)); if (!Enable) { - return; + return false; } - 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); + return true; } internal void AddFinalizedBuffer(ref Py_buffer buffer) @@ -254,7 +259,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 +372,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..8b4a250c2 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -188,6 +188,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 daeacfcd7..f11a179da 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,13 @@ public static void Reset() { assemblyBuilders = new Dictionary(); moduleBuilders = new Dictionary, ModuleBuilder>(); + lock (KeptLock) + { + KeptByManagedObject.Clear(); + TakenBackByPython.Clear(); + ReturnedToPython.Clear(); + } + WeaklyHeldWrappers.Clear(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -75,6 +110,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 +122,119 @@ 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 Python passes the Python object to .NET, which may keep it from then on + /// + internal static void PassedToManaged(BorrowedReference ob) + { + lock (KeptLock) + { + ReturnedToPython.Remove(ob.DangerousGetAddress()); + } + } + + /// + /// 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, the last word of the GC header that precedes the object + /// + private const nint FinalizedFlag = 1; + + private static unsafe ref nint FinalizedFlagWord(BorrowedReference ob) + => ref *((nint*)ob.DangerousGetAddress() - 1); + + 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 +260,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 +287,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); @@ -270,7 +430,8 @@ internal static Type CreateDerivedType(string name, } // add the destructor so the python object created in the constructor gets destroyed, - // after the base class finalizers, which may still call the Python overrides + // after the base class finalizers, which may still call the Python overrides. + // Unless PyDeferFinalization defers both until .NET finalizes the object again. MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize", MethodAttributes.Family | MethodAttributes.Virtual | @@ -279,12 +440,17 @@ 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(PyDeferFinalization))); + il.Emit(OpCodes.Brtrue_S, deferred); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance)); 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.MarkLabel(deferred); il.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); @@ -924,6 +1090,20 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec args); } + /// + /// Called by the .NET finalizer of a Python derived type, before the base type's finalizer + /// + /// + /// Whether the finalization waits until handled it, + /// because Python may still reference the Python object: .NET then finalizes the object again. + /// + public static bool PyDeferFinalization(IPythonDerivedType obj) + { + var self = GetPyObj(obj); + return ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference) + && Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); + } + public static void PyFinalize(IPythonDerivedType obj) { // the C# object is being destroyed which must mean there are no more @@ -939,8 +1119,33 @@ public static void PyFinalize(IPythonDerivedType obj) SetPyObj(obj, BorrowedReference.Null); } - 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/MetaType.cs b/src/runtime/Types/MetaType.cs index 34a070c3b..0c9977eb5 100644 --- a/src/runtime/Types/MetaType.cs +++ b/src/runtime/Types/MetaType.cs @@ -244,6 +244,25 @@ public static NewReference tp_call(BorrowedReference tp, BorrowedReference args, : default; } + /// + /// The __del__ that wraps the tp_finalize of a __namespace__ subclass. Python code may replace it, + /// as it can define one on any class. + /// + private static bool IsDerivedClassFinalizer(BorrowedReference descr, BorrowedReference name) + { + if (Runtime.GetManagedString(name) != "__del__") + { + return false; + } + using var declaringType = Runtime.PyObject_GetAttrString(descr, "__objclass__"); + if (declaringType.IsNull()) + { + Exceptions.Clear(); + return false; + } + return GetManagedObject(declaringType.Borrow()) is ClassDerivedObject; + } + /// /// Type __setattr__ implementation for reflected types. Note that this /// is slightly different than the standard setattr implementation for @@ -259,7 +278,7 @@ public static int tp_setattro(BorrowedReference tp, BorrowedReference name, Borr { BorrowedReference dt = Runtime.PyObject_TYPE(descr); - if (dt == Runtime.PyWrapperDescriptorType + if ((dt == Runtime.PyWrapperDescriptorType && !IsDerivedClassFinalizer(descr, name)) || dt == Runtime.PyMethodType || typeof(ExtensionType).IsInstanceOfType(GetManagedObject(descr)) ) diff --git a/tests/test_subclass.py b/tests/test_subclass.py index d4487f349..c85575d9a 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -448,3 +448,350 @@ 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 + + +def test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another(): + class Node(System.Object): + __namespace__ = "test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another" + + refcount = sys.getrefcount(Node) + parents = List[System.Object]() + children = List[System.Object]() + parent, child = Node(), Node() + parent.child, child.parent = child, parent + child.code = 41 + parents.Add(parent) + del parent, child + _release_python_and_net_objects() + + # the child isn't read back from .NET before Python lets go of the cycle again + children.Add(parents[0].child) + parents.Clear() + _release_python_and_net_objects() + assert children[0].code == 41 + assert children[0].parent.child is children[0] + + children.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(Node) == refcount + + +def test_namespaced_subclass_del_can_be_assigned(): + class AssignedDel(System.Object): + __namespace__ = "test_namespaced_subclass_del_can_be_assigned" + + class PlainSubclass(AssignedDel): + pass + + # the subclass first, so its assignment replaces the inherited __del__ rather than one assigned in Python + calls = [] + for cls in (PlainSubclass, AssignedDel): + cls.__del__ = lambda self, cls=cls: calls.append(cls) + cls().__del__() + assert calls == [PlainSubclass, AssignedDel] + + +@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 + + +def test_namespaced_subclass_runs_base_finalizer_while_finalizer_disabled(): + import gc + from System import GC + from Python.Runtime import Finalizer + from Python.Test import FinalizedConstructorTest + + class Finalized(FinalizedConstructorTest): + __namespace__ = "test_namespaced_subclass_runs_base_finalizer_while_finalizer_disabled" + + def __init__(self): + self.me = self + + before = FinalizedConstructorTest.Finalized + held = List[System.Object]() + held.Add(Finalized()) + gc.collect() + instance = held[0] + instance.me = None + del instance + # while disabled, a finalized PyObject releases its Python object without the GIL + for _ in range(2): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + + Finalizer.Instance.Enable = False + try: + held.Clear() + for _ in range(3): + GC.Collect() + GC.WaitForPendingFinalizers() + assert FinalizedConstructorTest.Finalized - before == 1 + finally: + Finalizer.Instance.Enable = True + + +@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