bpo-40137: _PyType_GetModuleByDef() doesn't check tp_flags (GH-25504)

_PyType_GetModuleByDef() no longer checks if types are heap types.

_PyType_GetModuleByDef() must only be called on a heap type created
by PyType_FromModuleAndSpec() or on its subclasses.
type_ready_mro() ensures that a static type cannot inherit from a
heap type.
This commit is contained in:
Victor Stinner 2021-04-21 23:36:26 +02:00 committed by GitHub
parent 81fe01492c
commit d4aaa34798
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 15 deletions

View File

@ -3590,24 +3590,23 @@ PyObject *
_PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def) _PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
{ {
assert(PyType_Check(type)); assert(PyType_Check(type));
assert(type->tp_mro); PyObject *mro = type->tp_mro;
int i; assert(mro != NULL);
for (i = 0; i < PyTuple_GET_SIZE(type->tp_mro); i++) { for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(mro); i++) {
PyObject *super = PyTuple_GET_ITEM(type->tp_mro, i); PyObject *super = PyTuple_GET_ITEM(mro, i);
if (!PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) { // _PyType_GetModuleByDef() must only be called on a heap type created
/* Currently, there's no way for static types to inherit // by PyType_FromModuleAndSpec() or on its subclasses.
* from heap types, but to allow that possibility, // type_ready_mro() ensures that a static type cannot inherit from a
* we `continue` rather than `break`. // heap type.
* We'll just potentially loop a few more times before throwing assert(_PyType_HasFeature((PyTypeObject *)type, Py_TPFLAGS_HEAPTYPE));
* the error.
*/
continue;
}
PyHeapTypeObject *ht = (PyHeapTypeObject*)super; PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
if (ht->ht_module && PyModule_GetDef(ht->ht_module) == def) { PyObject *module = ht->ht_module;
return ht->ht_module; if (module && PyModule_GetDef(module) == def) {
return module;
} }
} }
PyErr_Format( PyErr_Format(
PyExc_TypeError, PyExc_TypeError,
"_PyType_GetModuleByDef: No superclass of '%s' has the given module", "_PyType_GetModuleByDef: No superclass of '%s' has the given module",