@@ -1987,14 +1987,20 @@ mro_invoke(PyTypeObject *type)
1987
1987
1988
1988
new_mro = PySequence_Tuple (mro_result );
1989
1989
Py_DECREF (mro_result );
1990
- if (new_mro == NULL )
1990
+ if (new_mro == NULL ) {
1991
1991
return NULL ;
1992
+ }
1992
1993
1993
- if (custom && mro_check ( type , new_mro ) < 0 ) {
1994
+ if (PyTuple_GET_SIZE ( new_mro ) == 0 ) {
1994
1995
Py_DECREF (new_mro );
1996
+ PyErr_Format (PyExc_TypeError , "type MRO must not be empty" );
1995
1997
return NULL ;
1996
1998
}
1997
1999
2000
+ if (custom && mro_check (type , new_mro ) < 0 ) {
2001
+ Py_DECREF (new_mro );
2002
+ return NULL ;
2003
+ }
1998
2004
return new_mro ;
1999
2005
}
2000
2006
@@ -2034,8 +2040,9 @@ mro_internal(PyTypeObject *type, PyObject **p_old_mro)
2034
2040
new_mro = mro_invoke (type ); /* might cause reentrance */
2035
2041
reent = (type -> tp_mro != old_mro );
2036
2042
Py_XDECREF (old_mro );
2037
- if (new_mro == NULL )
2043
+ if (new_mro == NULL ) {
2038
2044
return -1 ;
2045
+ }
2039
2046
2040
2047
if (reent ) {
2041
2048
Py_DECREF (new_mro );
@@ -3590,9 +3597,17 @@ PyObject *
3590
3597
_PyType_GetModuleByDef (PyTypeObject * type , struct PyModuleDef * def )
3591
3598
{
3592
3599
assert (PyType_Check (type ));
3600
+
3593
3601
PyObject * mro = type -> tp_mro ;
3602
+ // The type must be ready
3594
3603
assert (mro != NULL );
3595
- for (Py_ssize_t i = 0 ; i < PyTuple_GET_SIZE (mro ); i ++ ) {
3604
+ assert (PyTuple_Check (mro ));
3605
+ // mro_invoke() ensures that the type MRO cannot be empty, so we don't have
3606
+ // to check i < PyTuple_GET_SIZE(mro) at the first loop iteration.
3607
+ assert (PyTuple_GET_SIZE (mro ) >= 1 );
3608
+
3609
+ Py_ssize_t i = 0 ;
3610
+ do {
3596
3611
PyObject * super = PyTuple_GET_ITEM (mro , i );
3597
3612
// _PyType_GetModuleByDef() must only be called on a heap type created
3598
3613
// by PyType_FromModuleAndSpec() or on its subclasses.
@@ -3605,7 +3620,8 @@ _PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
3605
3620
if (module && PyModule_GetDef (module ) == def ) {
3606
3621
return module ;
3607
3622
}
3608
- }
3623
+ i ++ ;
3624
+ } while (i < PyTuple_GET_SIZE (mro ));
3609
3625
3610
3626
PyErr_Format (
3611
3627
PyExc_TypeError ,
0 commit comments