Skip to content

Commit 4499a94

Browse files
authored
gh-160840: In PyType_GetModuleByToken, fall back to tp_bases if tp_mro is gone (GH-162160)
`PyType_GetModuleByToken` 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`.
1 parent 08784b2 commit 4499a94

6 files changed

Lines changed: 112 additions & 23 deletions

File tree

‎Lib/test/test_capi/test_type.py‎

Lines changed: 14 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

@@ -228,6 +229,19 @@ class H2(int): pass
228229
with self.assertRaises(TypeError):
229230
_testcapi.pytype_getmodulebytoken(H2, token)
230231

232+
def test_get_module_by_token_in_dealloc(self):
233+
# gh-160840: PyType_GetModuleByToken() called from tp_dealloc
234+
# of a subclass instance that's in a reference cycle with its class
235+
# (and with itself, so it outlives the class's tp_clear)
236+
class C(_testlimitedcapi.GetModuleByTokenInDealloc):
237+
pass
238+
C.inst = C()
239+
C.inst.self = C.inst
240+
with support.catch_unraisable_exception() as cm:
241+
del C
242+
support.gc_collect()
243+
self.assertIsNone(cm.unraisable)
244+
231245
def test_freeze(self):
232246
# test PyType_Freeze()
233247
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_GetModuleByToken` and :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
@@ -103,7 +103,7 @@ module_exec(PyObject *mod)
103103
return 0;
104104
}
105105

106-
static struct PyModuleDef _testlimitedcapimodule_def = {
106+
PyModuleDef _Py_TestLimitedCAPI_ModuleDef = {
107107
PyModuleDef_HEAD_INIT,
108108
.m_name = "_testlimitedcapi",
109109
.m_size = 0,
@@ -119,5 +119,5 @@ static struct PyModuleDef _testlimitedcapimodule_def = {
119119
PyMODINIT_FUNC
120120
PyInit__testlimitedcapi(void)
121121
{
122-
return PyModuleDef_Init(&_testlimitedcapimodule_def);
122+
return PyModuleDef_Init(&_Py_TestLimitedCAPI_ModuleDef);
123123
}

‎Modules/_testlimitedcapi/parts.h‎

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

27+
// Definition (and token) of the _testlimitedcapi module
28+
extern PyModuleDef _Py_TestLimitedCAPI_ModuleDef;
29+
2730
int _PyTestLimitedCAPI_Init_Abstract(PyObject *module);
2831
int _PyTestLimitedCAPI_Init_ByteArray(PyObject *module);
2932
int _PyTestLimitedCAPI_Init_Bytes(PyObject *module);

‎Modules/_testlimitedcapi/type.c‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Do no check PyType_Check() so Python tests can pass arbitrary objects,
33
// even if it's likely to crash.
44

5-
// Need limited C API version 3.14 for PyType_Freeze()
5+
// Need limited C API version 3.15 for PyType_Freeze()
66
#include "pyconfig.h" // Py_GIL_DISABLED
77
#if !defined(Py_GIL_DISABLED) && !defined(Py_LIMITED_API)
88
# define Py_LIMITED_API 0x030e0000
@@ -160,6 +160,40 @@ type_issubtype(PyObject *module, PyObject *args)
160160
}
161161

162162

163+
// Type whose tp_dealloc calls PyType_GetModuleByToken() (gh-160840)
164+
static int
165+
getmodulebytoken_dealloc_traverse(PyObject *op, visitproc visit, void *arg)
166+
{
167+
Py_VISIT(Py_TYPE(op));
168+
return 0;
169+
}
170+
171+
static void
172+
getmodulebytoken_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 getmodulebytoken_dealloc_spec = {
188+
.name = "_testlimitedcapi.GetModuleByTokenInDealloc",
189+
.flags = Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
190+
.slots = (PyType_Slot[]) {
191+
{Py_tp_traverse, getmodulebytoken_dealloc_traverse},
192+
{Py_tp_dealloc, getmodulebytoken_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, &getmodulebytoken_dealloc_spec, NULL);
221+
if (PyModule_Add(m, "GetModuleByTokenInDealloc", 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: 48 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5924,6 +5924,29 @@ PyType_GetModuleState(PyTypeObject *type)
59245924
return _PyModule_GetState(m);
59255925
}
59265926

5927+
static PyObject *
5928+
get_module_by_token_recursive(PyObject *bases, const void *token)
5929+
{
5930+
assert(bases != NULL);
5931+
Py_ssize_t n = PyTuple_GET_SIZE(bases);
5932+
for (Py_ssize_t i = 0; i < n; i++) {
5933+
PyTypeObject *base = _PyType_CAST(PyTuple_GET_ITEM(bases, i));
5934+
if (!_PyType_HasFeature(base, Py_TPFLAGS_HEAPTYPE)) {
5935+
continue;
5936+
}
5937+
PyObject *module = ((PyHeapTypeObject*)base)->ht_module;
5938+
if (module && _PyModule_GetToken(module) == token) {
5939+
return module;
5940+
break;
5941+
}
5942+
module = get_module_by_token_recursive(lookup_tp_bases(base), token);
5943+
if (module != NULL) {
5944+
return module;
5945+
}
5946+
}
5947+
return NULL;
5948+
}
5949+
59275950
/* Return borrowed ref to the module of the first superclass where the module
59285951
* has the given token.
59295952
*/
@@ -5949,28 +5972,33 @@ PyType_GetModuleByToken_DuringGC(PyTypeObject *type, const void *token)
59495972
BEGIN_TYPE_LOCK();
59505973

59515974
PyObject *mro = lookup_tp_mro(type);
5952-
// The type must be ready
5953-
assert(mro != NULL);
5954-
assert(PyTuple_Check(mro));
5955-
// mro_invoke() ensures that the type MRO cannot be empty.
5956-
assert(PyTuple_GET_SIZE(mro) >= 1);
5957-
// Also, the first item in the MRO is the type itself, which
5958-
// we already checked above. We skip it in the loop.
5959-
assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type);
5975+
if (mro == NULL) {
5976+
// If the MRO is already cleared during garbage collection, fall
5977+
// back to walking tp_bases.
5978+
res = get_module_by_token_recursive(lookup_tp_bases(type), token);
5979+
}
5980+
else {
5981+
assert(PyTuple_Check(mro));
5982+
// mro_invoke() ensures that the type MRO cannot be empty.
5983+
assert(PyTuple_GET_SIZE(mro) >= 1);
5984+
// Also, the first item in the MRO is the type itself, which
5985+
// we already checked above. We skip it in the loop.
5986+
assert(PyTuple_GET_ITEM(mro, 0) == (PyObject *)type);
59605987

5961-
Py_ssize_t n = PyTuple_GET_SIZE(mro);
5962-
for (Py_ssize_t i = 1; i < n; i++) {
5963-
PyObject *super = PyTuple_GET_ITEM(mro, i);
5964-
if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
5965-
// Static types in the MRO need to be skipped
5966-
continue;
5967-
}
5988+
Py_ssize_t n = PyTuple_GET_SIZE(mro);
5989+
for (Py_ssize_t i = 1; i < n; i++) {
5990+
PyObject *super = PyTuple_GET_ITEM(mro, i);
5991+
if (!_PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) {
5992+
// Static types in the MRO need to be skipped
5993+
continue;
5994+
}
59685995

5969-
PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
5970-
PyObject *module = ht->ht_module;
5971-
if (module && _PyModule_GetToken(module) == token) {
5972-
res = module;
5973-
break;
5996+
PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
5997+
PyObject *module = ht->ht_module;
5998+
if (module && _PyModule_GetToken(module) == token) {
5999+
res = module;
6000+
break;
6001+
}
59746002
}
59756003
}
59766004
END_TYPE_LOCK();

0 commit comments

Comments
 (0)