diff --git a/graalpython/com.oracle.graal.python.cext/src/gcmodule.c b/graalpython/com.oracle.graal.python.cext/src/gcmodule.c index e883ce2bd4..7437668606 100644 --- a/graalpython/com.oracle.graal.python.cext/src/gcmodule.c +++ b/graalpython/com.oracle.graal.python.cext/src/gcmodule.c @@ -2888,7 +2888,8 @@ _PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems) void PyObject_GC_Del(void *op) { - size_t presize = _PyType_PreHeaderSize(Py_TYPE(op)); // GraalPy change + PyTypeObject *tp = Py_TYPE(op); // GraalPy change + size_t presize = _PyType_PreHeaderSize(tp); // GraalPy change PyGC_Head *g = AS_GC(op); if (_PyObject_GC_IS_TRACKED(op)) { gc_list_remove(g); @@ -2902,6 +2903,32 @@ PyObject_GC_Del(void *op) PyErr_SetRaisedException(exc); #endif } + /* GraalPy change: release the instance dict that lives in the pre-header. + * + * CPython drops this reference in 'subtype_dealloc' (or in the type's own + * tp_dealloc via 'PyObject_ClearManagedDict'). On GraalPy, a managed + * (Python-level) subclass of a native type does not get 'subtype_dealloc' + * but inherits the tp_dealloc of its native base (see 'type_new_alloc' and + * 'CExtNodes.lookupNativeMemberInMRO'), which knows nothing about the + * subclass' __dict__, and 'PyObject_ClearManagedDict' is a no-op. So this + * is the last point where the reference can be dropped. Otherwise the dict + * keeps 'ob_refcnt > MANAGED_REFCNT' forever, its handle table reference + * stays strong and the dict, as well as everything reachable from it, is + * never collected. + * + * For the usual managed dict this is at most an upcall that makes the + * handle table reference weak, but '__dict__' may also be a dict subclass + * with native backing, whose final DECREF runs its tp_dealloc; that is why + * the pointer is cleared before the DECREF. + */ + if (_PyType_HasFeature(tp, Py_TPFLAGS_MANAGED_DICT)) { + PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer((PyObject *)op); + PyObject *dict = (PyObject *)managed_dict->dict; + if (dict != NULL) { + managed_dict->dict = NULL; + Py_DECREF(dict); + } + } GCState *gcstate = get_gc_state(); if (gcstate->generations[0].count > 0) { gcstate->generations[0].count--; diff --git a/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c b/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c index 48887ad7ca..e97eb3ad25 100644 --- a/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c @@ -3488,7 +3488,10 @@ PyUnicode_Decode(const char *s, if (!mv) { return NULL; } - return GraalPyPrivate_Unicode_Decode(mv, encoding, errors != NULL ? errors : "strict"); + // GraalPy change: the upcall borrows 'mv' (NativeToPythonNode); release the temporary (it leaked before) + PyObject *result = GraalPyPrivate_Unicode_Decode(mv, encoding, errors != NULL ? errors : "strict"); + Py_DECREF(mv); + return result; } #if 0 // GraalPy change diff --git a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py index 21ab75981e..aa565e13e5 100644 --- a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py +++ b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py @@ -1138,3 +1138,77 @@ def test_transitive_native_root(self): GCGraphNode.release() a.set(None, None) b.set(None, None) + + +NativeBaseForManagedSubclass = CPyExtType( + "NativeBaseForManagedSubclass", + ''' + static Py_ssize_t nbms_deallocs = 0; + + static int nbms_traverse(PyObject *self, visitproc visit, void *arg) { + return 0; + } + + /* Same shape as the tp_dealloc that Cython generates for a cdef class: it knows nothing + about the __dict__ of a Python subclass. */ + static void nbms_dealloc(PyObject *self) { + PyObject_GC_UnTrack(self); + nbms_deallocs++; + Py_TYPE(self)->tp_free(self); + } + + /* Allocates an instance of the given Python subclass from C, so that no reference to it + exists outside this function, gives it a fresh instance dict, then drops the only + reference to the instance, which runs tp_dealloc and tp_free right here. Returns + (refcount of the instance before the drop, tp_dealloc calls during the drop, + references the dict lost during the drop). */ + static PyObject *nbms_drop_instance_with_dict(PyObject *unused, PyObject *subclass) { + if (!PyType_Check(subclass)) { + PyErr_SetString(PyExc_TypeError, "expected a type"); + return NULL; + } + PyTypeObject *tp = (PyTypeObject *)subclass; + PyObject *dict = PyDict_New(); + if (dict == NULL) { + return NULL; + } + PyObject *obj = tp->tp_alloc(tp, 0); + if (obj == NULL) { + Py_DECREF(dict); + return NULL; + } + if (PyObject_GenericSetDict(obj, dict, NULL) < 0) { + Py_DECREF(obj); + Py_DECREF(dict); + return NULL; + } + Py_ssize_t obj_refcnt = Py_REFCNT(obj); + Py_ssize_t dict_refcnt = Py_REFCNT(dict); + Py_ssize_t deallocs = nbms_deallocs; + Py_DECREF(obj); + PyObject *result = Py_BuildValue("nnn", obj_refcnt, nbms_deallocs - deallocs, dict_refcnt - Py_REFCNT(dict)); + Py_DECREF(dict); + return result; + } + ''', + tp_flags='Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC', + tp_traverse='(traverseproc)nbms_traverse', + tp_dealloc='(destructor)nbms_dealloc', + tp_methods='{"drop_instance_with_dict", (PyCFunction)nbms_drop_instance_with_dict, METH_O | METH_STATIC, ""}', +) + + +class TestManagedSubclassOfNativeType(unittest.TestCase): + """An instance of a Python subclass of a native type is a native object that keeps its + ``__dict__`` in the pre-header. Deallocating the instance must release the dict, even if the + native base's tp_dealloc does not know about it.""" + + def test_instance_dict_released_on_dealloc(self): + class ManagedSubclass(NativeBaseForManagedSubclass): + pass + + obj_refcnt, deallocs, dict_released = NativeBaseForManagedSubclass.drop_instance_with_dict(ManagedSubclass) + # Preconditions: the C helper held the only reference, so dropping it deallocated the instance. + assert obj_refcnt == 1, f"instance refcount before the drop is {obj_refcnt}, expected 1" + assert deallocs == 1, f"tp_dealloc ran {deallocs} times during the drop, expected 1" + assert dict_released == 1, f"the instance dict lost {dict_released} references on dealloc, expected 1" diff --git a/graalpython/lib-graalpython/patches/orjson-3.12.0.patch b/graalpython/lib-graalpython/patches/orjson-3.12.0.patch index 18b9261a7d..599a14179c 100644 --- a/graalpython/lib-graalpython/patches/orjson-3.12.0.patch +++ b/graalpython/lib-graalpython/patches/orjson-3.12.0.patch @@ -275,7 +275,7 @@ diff --git a/src/ffi/pydictref.rs b/src/ffi/pydictref.rs index 4a6c6cf..238b192 100644 --- a/src/ffi/pydictref.rs +++ b/src/ffi/pydictref.rs -@@ -19,7 +19,7 @@ impl PartialEq for PyDictRef { +@@ -19,7 +19,7 @@ } } @@ -284,22 +284,29 @@ index 4a6c6cf..238b192 100644 #[inline] fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { unsafe { -@@ -32,13 +32,13 @@ fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyO - } - } - --#[cfg(Py_GIL_DISABLED)] -+#[cfg(any(Py_GIL_DISABLED, not(CPython)))] - #[inline] - fn reverse_pydict_incref(_: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { +@@ -38,10 +38,21 @@ unsafe { crate::ffi::Py_DECREF(value) } } -#[cfg(not(Py_3_12))] -+#[cfg(all(CPython, not(Py_3_12)))] ++// GraalPy: get_unicode_key returns a new reference (no key cache), and PyDict_SetItem ++// takes its own references, so release both the key and the value. ++#[cfg(not(CPython))] #[inline] fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { unsafe { ++ crate::ffi::Py_DECREF(key); ++ crate::ffi::Py_DECREF(value); ++ } ++} ++ ++#[cfg(all(CPython, not(Py_3_12)))] ++#[inline] ++fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { ++ unsafe { + (*key).ob_refcnt -= 1; + (*value).ob_refcnt -= 1; + } diff --git a/src/ffi/pystrref/object.rs b/src/ffi/pystrref/object.rs index 69069fa..bc44e7c 100644 --- a/src/ffi/pystrref/object.rs diff --git a/graalpython/lib-graalpython/patches/orjson-3.13.0.patch b/graalpython/lib-graalpython/patches/orjson-3.13.0.patch index 34a05e7569..87df8122c2 100644 --- a/graalpython/lib-graalpython/patches/orjson-3.13.0.patch +++ b/graalpython/lib-graalpython/patches/orjson-3.13.0.patch @@ -277,7 +277,7 @@ diff --git a/src/ffi/pydictref.rs b/src/ffi/pydictref.rs index 5ecc624..64b4f0d 100644 --- a/src/ffi/pydictref.rs +++ b/src/ffi/pydictref.rs -@@ -19,7 +19,7 @@ impl PartialEq for PyDictRef { +@@ -19,7 +19,7 @@ } } @@ -286,22 +286,29 @@ index 5ecc624..64b4f0d 100644 #[inline] fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { unsafe { -@@ -32,13 +32,13 @@ fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyO - } - } - --#[cfg(Py_GIL_DISABLED)] -+#[cfg(any(Py_GIL_DISABLED, not(CPython)))] - #[inline] - fn reverse_pydict_incref(_: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { +@@ -38,10 +38,21 @@ unsafe { crate::ffi::Py_DECREF(value) } } -#[cfg(not(Py_3_12))] -+#[cfg(all(CPython, not(Py_3_12)))] ++// GraalPy: get_unicode_key returns a new reference (no key cache), and PyDict_SetItem ++// takes its own references, so release both the key and the value. ++#[cfg(not(CPython))] #[inline] fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { unsafe { ++ crate::ffi::Py_DECREF(key); ++ crate::ffi::Py_DECREF(value); ++ } ++} ++ ++#[cfg(all(CPython, not(Py_3_12)))] ++#[inline] ++fn reverse_pydict_incref(key: *mut pyo3_ffi::PyObject, value: *mut pyo3_ffi::PyObject) { ++ unsafe { + (*key).ob_refcnt -= 1; + (*value).ob_refcnt -= 1; + } diff --git a/src/ffi/pystrref/object.rs b/src/ffi/pystrref/object.rs index 69069fa..bc44e7c 100644 --- a/src/ffi/pystrref/object.rs