8000 [3.9] gh-92112: Fix crash triggered by an evil custom `mro()` (GH-921… · python/cpython@f82b324 · GitHub
[go: up one dir, main page]

Skip to content

Commit f82b324

Browse files
JelleZijlstraAlexey Izbyshev
andauthored
[3.9] gh-92112: Fix crash triggered by an evil custom mro() (GH-92113) (GH-92372)
(cherry picked from commit 85354ed) Co-authored-by: Alexey Izbyshev <izbyshev@ispras.ru>
1 parent 518b238 commit f82b324

File tree

3 files changed

+29
-9
lines changed

3 files changed

+29
-9
lines changed

Lib/test/test_descr.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5686,6 +5686,23 @@ def mro(cls):
56865686
class A(metaclass=M):
56875687
pass
56885688

5689+
def test_disappearing_custom_mro(self):
5690+
"""
5691+
gh-92112: A custom mro() returning a result conflicting with
5692+
__bases__ and deleting itself caused a double free.
5693+
"""
5694+
class B:
5695+
pass
5696+
5697+
class M(DebugHelperMeta):
5698+
def mro(cls):
5699+
del M.mro
5700+
return (B,)
5701+
5702+
with self.assertRaises(TypeError):
5703+
class A(metaclass=M):
5704+
pass
5705+
56895706

56905707
if __name__ == "__main__":
56915708
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash triggered by an evil custom ``mro()`` on a metaclass.

Objects/typeobject.c

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -317,25 +317,29 @@ type_mro_modified(PyTypeObject *type, PyObject *bases) {
317317
Py_ssize_t i, n;
318318
int custom = !Py_IS_TYPE(type, &PyType_Type);
319319
int unbound;
320-
PyObject *mro_meth = NULL;
321-
PyObject *type_mro_meth = NULL;
322320

323321
if (!_PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
324322
return;
325323

326324
if (custom) {
325+
PyObject *mro_meth, *type_mro_meth;
327326
mro_meth = lookup_maybe_method(
328327
(PyObject *)type, &PyId_mro, &unbound);
329-
if (mro_meth == NULL)
328+
if (mro_meth == NULL) {
330329
goto clear;
330+
}
331331
type_mro_meth = lookup_maybe_method(
332332
(PyObject *)&PyType_Type, &PyId_mro, &unbound);
333-
if (type_mro_meth == NULL)
333+
if (type_mro_meth == NULL) {
334+
Py_DECREF(mro_meth);
334335
goto clear;
335-
if (mro_meth != type_mro_meth)
336+
}
337+
int custom_mro = (mro_meth != type_mro_meth);
338+
Py_DECREF(mro_meth);
339+
Py_DECREF(type_mro_meth);
340+
if (custom_mro) {
336341
goto clear;
337-
Py_XDECREF(mro_meth);
338-
Py_XDECREF(type_mro_meth);
342+
}
339343
}
340344
n = PyTuple_GET_SIZE(bases);
341345
for (i = 0; i < n; i++) {
@@ -352,8 +356,6 @@ type_mro_modified(PyTypeObject *type, PyObject *bases) {
352356
}
353357
return;
354358
clear:
355-
Py_XDECREF(mro_meth);
356-
Py_XDECREF(type_mro_meth);
357359
type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
358360
Py_TPFLAGS_VALID_VERSION_TAG);
359361
}

0 commit comments

Comments
 (0)
0