Skip to content

Commit 20bf204

Browse files
committed
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 4499a94. 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.)
1 parent 00cefa8 commit 20bf204

6 files changed

Lines changed: 113 additions & 24 deletions

File tree

‎Lib/test/test_capi/test_type.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from test import support
12
from test.support import import_helper, Py_GIL_DISABLED, refleak_helper
23
import unittest
34

@@ -210,6 +211,20 @@ class H2(int): pass
210211
with self.assertRaises(TypeError):
211212
_testcapi.pytype_getmodulebydef(H2)
212213

214+
215+
def test_get_module_by_def_in_dealloc(self):
216+
# gh-160840: PyType_GetModuleByDef() called from tp_dealloc
217+
# of a subclass instance that's in a reference cycle with its class
218+
# (and with itself, so it outlives the class's tp_clear)
219+
class C(_testlimitedcapi.GetModuleByDefInDealloc):
220+
pass
221+
C.inst = C()
222+
C.inst.self = C.inst
223+
with support.catch_unraisable_exception() as cm:
224+
del C
225+
support.gc_collect()
226+
self.assertIsNone(cm.unraisable)
227+
213228
def test_freeze(self):
214229
# test PyType_Freeze()
215230
type_freeze = _testlimitedcapi.type_freeze
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
When a type's internal :term:`method resolution order` data is cleared as
2+
the type is being torn down during garbage collection,
3+
:c:func:`PyType_GetModuleByDef` can
4+
now still retrieve its module.

‎Modules/_testlimitedcapi.c‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ static PyMethodDef TestMethods[] = {
1111
{NULL, NULL} /* sentinel */
1212
};
1313

14-
static struct PyModuleDef _testlimitedcapimodule = {
14+
struct PyModuleDef _Py_TestLimitedCAPI_ModuleDef = {
1515
PyModuleDef_HEAD_INIT,
1616
.m_name = "_testlimitedcapi",
1717
.m_size = 0,
@@ -21,7 +21,7 @@ static struct PyModuleDef _testlimitedcapimodule = {
2121
PyMODINIT_FUNC
2222
PyInit__testlimitedcapi(void)
2323
{
24-
PyObject *mod = PyModule_Create(&_testlimitedcapimodule);
24+
PyObject *mod = PyModule_Create(&_Py_TestLimitedCAPI_ModuleDef);
2525
if (mod == NULL) {
2626
return NULL;
2727
}

‎Modules/_testlimitedcapi/parts.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
# error "Py_BUILD_CORE macro must not be defined"
2323
#endif
2424

25+
// Definition of the _testlimitedcapi module
26+
extern PyModuleDef _Py_TestLimitedCAPI_ModuleDef;
27+
2528
int _PyTestLimitedCAPI_Init_Abstract(PyObject *module);
2629
int _PyTestLimitedCAPI_Init_ByteArray(PyObject *module);
2730
int _PyTestLimitedCAPI_Init_Bytes(PyObject *module);

‎Modules/_testlimitedcapi/type.c‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,40 @@ type_issubtype(PyObject *module, PyObject *args)
160160
}
161161

162162

163+
// Type whose tp_dealloc calls PyType_GetModuleByDef() (gh-160840)
164+
static int
165+
getmodulebydef_dealloc_traverse(PyObject *op, visitproc visit, void *arg)
166+
{
167+
Py_VISIT(Py_TYPE(op));
168+
return 0;
169+
}
170+
171+
static void
172+
getmodulebydef_dealloc_dealloc(PyObject *op)
173+
{
174+
PyTypeObject *tp = Py_TYPE(op);
175+
PyObject_GC_UnTrack(op);
176+
177+
PyObject *mod = PyType_GetModuleByDef(tp, &_Py_TestLimitedCAPI_ModuleDef);
178+
if (mod == NULL) {
179+
PyErr_WriteUnraisable(NULL);
180+
}
181+
182+
freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free);
183+
tp_free(op);
184+
Py_DECREF(tp);
185+
}
186+
187+
static PyType_Spec getmodulebydef_dealloc_spec = {
188+
.name = "_testlimitedcapi.GetModuleByDefInDealloc",
189+
.flags = Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
190+
.slots = (PyType_Slot[]) {
191+
{Py_tp_traverse, getmodulebydef_dealloc_traverse},
192+
{Py_tp_dealloc, getmodulebydef_dealloc_dealloc},
193+
{0},
194+
},
195+
};
196+
163197
static PyMethodDef test_methods[] = {
164198
{"get_heaptype_for_name", get_heaptype_for_name, METH_NOARGS},
165199
{"get_type_name", get_type_name, METH_O},
@@ -182,6 +216,12 @@ _PyTestLimitedCAPI_Init_Type(PyObject *m)
182216
return -1;
183217
}
184218

219+
PyObject *type = PyType_FromModuleAndSpec(
220+
m, &getmodulebydef_dealloc_spec, NULL);
221+
if (PyModule_Add(m, "GetModuleByDefInDealloc", type) < 0) {
222+
return -1;
223+
}
224+
185225
#define ADD_INT(macro) \
186226
do { \
187227
if (PyModule_AddIntConstant(m, #macro, macro) < 0) { \

‎Objects/typeobject.c‎

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5768,9 +5768,31 @@ PyType_GetModuleState(PyTypeObject *type)
57685768
return _PyModule_GetState(m);
57695769
}
57705770

5771+
static PyObject *
5772+
get_module_by_def_recursive(PyObject *bases, PyModuleDef *def)
5773+
{
5774+
assert(bases != NULL);
5775+
Py_ssize_t n = PyTuple_GET_SIZE(bases);
5776+
for (Py_ssize_t i = 0; i < n; i++) {
5777+
PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i));
5778+
if (!_PyType_HasFeature(base, Py_TPFLAGS_HEAPTYPE)) {
5779+
continue;
5780+
}
5781+
PyObject *module = ((PyHeapTypeObject*)base)->ht_module;
5782+
if (module && _PyModule_GetDef(module) == def) {
5783+
return module;
5784+
break;
5785+
}
5786+
module = get_module_by_def_recursive(lookup_tp_bases(base), def);
5787+
if (module != NULL) {
5788+
return module;
5789+
}
5790+
}
5791+
return NULL;
5792+
}
57715793

5772-
/* Get the module of the first superclass where the module has the
5773-
* given PyModuleDef.
5794+
/* Return borrowed ref to the module of the first superclass where the module
5795+
* has the given PyModuleDef.
57745796
*/
57755797
PyObject *
57765798
PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
@@ -5794,28 +5816,33 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
57945816
BEGIN_TYPE_LOCK();
57955817

57965818
PyObject *mro = lookup_tp_mro(type);
5797-
// The type must be ready
5798-
assert(mro != NULL);
5799-
assert(PyTuple_Check(mro));
5800-
// mro_invoke() ensures that the type MRO cannot be empty.
5801-
assert(PyTuple_GET_SIZE(mro) >= 1);
5802-
// Also, the first item in the MRO is the type itself, which
5803-
// we already checked above. We skip it in the loop.
5804-
assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type);
5819+
if (mro == NULL) {
5820+
// If the MRO is already cleared during garbage collection, fall
5821+
// back to walking tp_bases.
5822+
res = get_module_by_def_recursive(lookup_tp_bases(type), def);
5823+
}
5824+
else {
5825+
assert(PyTuple_Check(mro));
5826+
// mro_invoke() ensures that the type MRO cannot be empty.
5827+
assert(PyTuple_GET_SIZE(mro) >= 1);
5828+
// Also, the first item in the MRO is the type itself, which
5829+
// we already checked above. We skip it in the loop.
5830+
assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type);
58055831

5806-
Py_ssize_t n = PyTuple_GET_SIZE(mro);
5807-
for (Py_ssize_t i = 1; i < n; i++) {
5808-
PyObject *super = PyTuple_GET_ITEM(mro, i);
5809-
if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
5810-
// Static types in the MRO need to be skipped
5811-
continue;
5812-
}
5832+
Py_ssize_t n = PyTuple_GET_SIZE(mro);
5833+
for (Py_ssize_t i = 1; i < n; i++) {
5834+
PyObject *super = PyTuple_GET_ITEM(mro, i);
5835+
if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
5836+
// Static types in the MRO need to be skipped
5837+
continue;
5838+
}
58135839

5814-
PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
5815-
PyObject *module = ht->ht_module;
5816-
if (module && _PyModule_GetDef(module) == def) {
5817-
res = module;
5818-
break;
5840+
PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
5841+
PyObject *module = ht->ht_module;
5842+
if (module && _PyModule_GetDef(module) == def) {
5843+
res = module;
5844+
break;
5845+
}
58195846
}
58205847
}
58215848
END_TYPE_LOCK();

0 commit comments

Comments
 (0)