From 20bf20443807e8c2e1ce0472e37bed449b353a42 Mon Sep 17 00:00:00 2001 From: Petr Viktorin Date: Fri, 27 Nov 2026 17:47:29 +0100 Subject: [PATCH 1/2] gh-160840: In PyType_GetModuleByDef, fall back to tp_bases if tp_mro is gone (GH-162160) `PyType_GetModuleByDef` asserted that a type's `mro` is not NULL, but this can happen when cleaning a GC cycle. If it does, we can still fall back to walking `tp_bases`. (cherry picked from commit 4499a94c90495a134ca2df07ad0dc0fc3f650fd4. This backport changes only `PyType_GetModuleByDef`, while in 3.15+, `*ByDef` is implemented on top of the new `PyType_GetModuleByToken`, which the original commit changes too.) --- Lib/test/test_capi/test_type.py | 15 ++++ ...-11-17-17-54-53.gh-issue-160840.IaFtRu.rst | 4 ++ Modules/_testlimitedcapi.c | 4 +- Modules/_testlimitedcapi/parts.h | 3 + Modules/_testlimitedcapi/type.c | 40 +++++++++++ Objects/typeobject.c | 71 +++++++++++++------ 6 files changed, 113 insertions(+), 24 deletions(-) create mode 100644 Misc/NEWS.d/next/C_API/2026-11-17-17-54-53.gh-issue-160840.IaFtRu.rst diff --git a/Lib/test/test_capi/test_type.py b/Lib/test/test_capi/test_type.py index 2beda7c5dae0520..a77a9b3a0cf898d 100644 --- a/Lib/test/test_capi/test_type.py +++ b/Lib/test/test_capi/test_type.py @@ -1,3 +1,4 @@ +from test import support from test.support import import_helper, Py_GIL_DISABLED, refleak_helper import unittest @@ -210,6 +211,20 @@ class H2(int): pass with self.assertRaises(TypeError): _testcapi.pytype_getmodulebydef(H2) + + def test_get_module_by_def_in_dealloc(self): + # gh-160840: PyType_GetModuleByDef() called from tp_dealloc + # of a subclass instance that's in a reference cycle with its class + # (and with itself, so it outlives the class's tp_clear) + class C(_testlimitedcapi.GetModuleByDefInDealloc): + pass + C.inst = C() + C.inst.self = C.inst + with support.catch_unraisable_exception() as cm: + del C + support.gc_collect() + self.assertIsNone(cm.unraisable) + def test_freeze(self): # test PyType_Freeze() type_freeze = _testlimitedcapi.type_freeze diff --git a/Misc/NEWS.d/next/C_API/2026-11-17-17-54-53.gh-issue-160840.IaFtRu.rst b/Misc/NEWS.d/next/C_API/2026-11-17-17-54-53.gh-issue-160840.IaFtRu.rst new file mode 100644 index 000000000000000..e6d62434f5bdd0a --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-11-17-17-54-53.gh-issue-160840.IaFtRu.rst @@ -0,0 +1,4 @@ +When a type's internal :term:`method resolution order` data is cleared as +the type is being torn down during garbage collection, +:c:func:`PyType_GetModuleByDef` can +now still retrieve its module. diff --git a/Modules/_testlimitedcapi.c b/Modules/_testlimitedcapi.c index 0da8ed729f2412a..f2a03746b5060ad 100644 --- a/Modules/_testlimitedcapi.c +++ b/Modules/_testlimitedcapi.c @@ -11,7 +11,7 @@ static PyMethodDef TestMethods[] = { {NULL, NULL} /* sentinel */ }; -static struct PyModuleDef _testlimitedcapimodule = { +struct PyModuleDef _Py_TestLimitedCAPI_ModuleDef = { PyModuleDef_HEAD_INIT, .m_name = "_testlimitedcapi", .m_size = 0, @@ -21,7 +21,7 @@ static struct PyModuleDef _testlimitedcapimodule = { PyMODINIT_FUNC PyInit__testlimitedcapi(void) { - PyObject *mod = PyModule_Create(&_testlimitedcapimodule); + PyObject *mod = PyModule_Create(&_Py_TestLimitedCAPI_ModuleDef); if (mod == NULL) { return NULL; } diff --git a/Modules/_testlimitedcapi/parts.h b/Modules/_testlimitedcapi/parts.h index 15ba9c007a7aaaa..9aa76d83595fa94 100644 --- a/Modules/_testlimitedcapi/parts.h +++ b/Modules/_testlimitedcapi/parts.h @@ -22,6 +22,9 @@ # error "Py_BUILD_CORE macro must not be defined" #endif +// Definition of the _testlimitedcapi module +extern PyModuleDef _Py_TestLimitedCAPI_ModuleDef; + int _PyTestLimitedCAPI_Init_Abstract(PyObject *module); int _PyTestLimitedCAPI_Init_ByteArray(PyObject *module); int _PyTestLimitedCAPI_Init_Bytes(PyObject *module); diff --git a/Modules/_testlimitedcapi/type.c b/Modules/_testlimitedcapi/type.c index 640468ae08dcbb6..09ca31cd1d758f6 100644 --- a/Modules/_testlimitedcapi/type.c +++ b/Modules/_testlimitedcapi/type.c @@ -160,6 +160,40 @@ type_issubtype(PyObject *module, PyObject *args) } +// Type whose tp_dealloc calls PyType_GetModuleByDef() (gh-160840) +static int +getmodulebydef_dealloc_traverse(PyObject *op, visitproc visit, void *arg) +{ + Py_VISIT(Py_TYPE(op)); + return 0; +} + +static void +getmodulebydef_dealloc_dealloc(PyObject *op) +{ + PyTypeObject *tp = Py_TYPE(op); + PyObject_GC_UnTrack(op); + + PyObject *mod = PyType_GetModuleByDef(tp, &_Py_TestLimitedCAPI_ModuleDef); + if (mod == NULL) { + PyErr_WriteUnraisable(NULL); + } + + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + tp_free(op); + Py_DECREF(tp); +} + +static PyType_Spec getmodulebydef_dealloc_spec = { + .name = "_testlimitedcapi.GetModuleByDefInDealloc", + .flags = Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + .slots = (PyType_Slot[]) { + {Py_tp_traverse, getmodulebydef_dealloc_traverse}, + {Py_tp_dealloc, getmodulebydef_dealloc_dealloc}, + {0}, + }, +}; + static PyMethodDef test_methods[] = { {"get_heaptype_for_name", get_heaptype_for_name, METH_NOARGS}, {"get_type_name", get_type_name, METH_O}, @@ -182,6 +216,12 @@ _PyTestLimitedCAPI_Init_Type(PyObject *m) return -1; } + PyObject *type = PyType_FromModuleAndSpec( + m, &getmodulebydef_dealloc_spec, NULL); + if (PyModule_Add(m, "GetModuleByDefInDealloc", type) < 0) { + return -1; + } + #define ADD_INT(macro) \ do { \ if (PyModule_AddIntConstant(m, #macro, macro) < 0) { \ diff --git a/Objects/typeobject.c b/Objects/typeobject.c index b1521140aab1a2e..ca6bf738d3aca81 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -5768,9 +5768,31 @@ PyType_GetModuleState(PyTypeObject *type) return _PyModule_GetState(m); } +static PyObject * +get_module_by_def_recursive(PyObject *bases, PyModuleDef *def) +{ + assert(bases != NULL); + Py_ssize_t n = PyTuple_GET_SIZE(bases); + for (Py_ssize_t i = 0; i < n; i++) { + PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i)); + if (!_PyType_HasFeature(base, Py_TPFLAGS_HEAPTYPE)) { + continue; + } + PyObject *module = ((PyHeapTypeObject*)base)->ht_module; + if (module && _PyModule_GetDef(module) == def) { + return module; + break; + } + module = get_module_by_def_recursive(lookup_tp_bases(base), def); + if (module != NULL) { + return module; + } + } + return NULL; +} -/* Get the module of the first superclass where the module has the - * given PyModuleDef. +/* Return borrowed ref to the module of the first superclass where the module + * has the given PyModuleDef. */ PyObject * PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def) @@ -5794,28 +5816,33 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def) BEGIN_TYPE_LOCK(); PyObject *mro = lookup_tp_mro(type); - // The type must be ready - assert(mro != NULL); - assert(PyTuple_Check(mro)); - // mro_invoke() ensures that the type MRO cannot be empty. - assert(PyTuple_GET_SIZE(mro) >= 1); - // Also, the first item in the MRO is the type itself, which - // we already checked above. We skip it in the loop. - assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type); + if (mro == NULL) { + // If the MRO is already cleared during garbage collection, fall + // back to walking tp_bases. + res = get_module_by_def_recursive(lookup_tp_bases(type), def); + } + else { + assert(PyTuple_Check(mro)); + // mro_invoke() ensures that the type MRO cannot be empty. + assert(PyTuple_GET_SIZE(mro) >= 1); + // Also, the first item in the MRO is the type itself, which + // we already checked above. We skip it in the loop. + assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type); - Py_ssize_t n = PyTuple_GET_SIZE(mro); - for (Py_ssize_t i = 1; i < n; i++) { - PyObject *super = PyTuple_GET_ITEM(mro, i); - if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) { - // Static types in the MRO need to be skipped - continue; - } + Py_ssize_t n = PyTuple_GET_SIZE(mro); + for (Py_ssize_t i = 1; i < n; i++) { + PyObject *super = PyTuple_GET_ITEM(mro, i); + if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) { + // Static types in the MRO need to be skipped + continue; + } - PyHeapTypeObject *ht = (PyHeapTypeObject*)super; - PyObject *module = ht->ht_module; - if (module && _PyModule_GetDef(module) == def) { - res = module; - break; + PyHeapTypeObject *ht = (PyHeapTypeObject*)super; + PyObject *module = ht->ht_module; + if (module && _PyModule_GetDef(module) == def) { + res = module; + break; + } } } END_TYPE_LOCK(); From fdf52ddedf418ff2ff6127ef3a62ab20f55f8ce2 Mon Sep 17 00:00:00 2001 From: Petr Viktorin Date: Mon, 30 Nov 2026 18:19:23 +0100 Subject: [PATCH 2/2] Make c-analyzer happy `PyModuleDef` is a typedef for `struct PyModuleDef`, but only one is recognized by the tool. --- Modules/_testlimitedcapi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/_testlimitedcapi.c b/Modules/_testlimitedcapi.c index f2a03746b5060ad..0796940be860591 100644 --- a/Modules/_testlimitedcapi.c +++ b/Modules/_testlimitedcapi.c @@ -11,7 +11,7 @@ static PyMethodDef TestMethods[] = { {NULL, NULL} /* sentinel */ }; -struct PyModuleDef _Py_TestLimitedCAPI_ModuleDef = { +PyModuleDef _Py_TestLimitedCAPI_ModuleDef = { PyModuleDef_HEAD_INIT, .m_name = "_testlimitedcapi", .m_size = 0,