diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 1d2c105ac047e18..c2d62cf59602d2a 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -755,6 +755,22 @@ def __dir__(self): # test that object has a __dir__() self.assertEqual(sorted([].__dir__()), dir([])) + @support.skip_emscripten_stack_overflow() + @support.skip_wasi_stack_overflow() + def test_dir_cyclic_bases(self): + class Fake: + pass + + a = Fake() + a.__bases__ = (a,) + + class C: + @property + def __class__(self): + return a + + self.assertRaises(RecursionError, dir, C()) + def test___ne__(self): self.assertFalse(None.__ne__(None)) self.assertIs(None.__ne__(0), NotImplemented) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-09-21-24-08.gh-issue-155452.4mUzjM.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-09-21-24-08.gh-issue-155452.4mUzjM.rst new file mode 100644 index 000000000000000..196e5c2edd51bea --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-09-21-24-08.gh-issue-155452.4mUzjM.rst @@ -0,0 +1,2 @@ +Fix a crash in :func:`dir` when an object's ``__class__`` has cyclic +``__bases__``. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index e3026397c8673f1..ed3e5a06709841e 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -3,6 +3,7 @@ #include "Python.h" #include "pycore_abstract.h" // _PySequence_IterSearch() #include "pycore_call.h" // _PyObject_VectorcallTstate() +#include "pycore_ceval.h" // _Py_EnterRecursiveCall() #include "pycore_code.h" // CO_FAST_FREE #include "pycore_descrobject.h" // _PyMember_GetOffset() #include "pycore_dict.h" // _PyDict_KeysSize() @@ -6949,22 +6950,27 @@ merge_class_dict(PyObject *dict, PyObject *aclass) Py_DECREF(bases); return -1; } - else { - for (i = 0; i < n; i++) { - int status; - PyObject *base = PySequence_GetItem(bases, i); - if (base == NULL) { - Py_DECREF(bases); - return -1; - } - status = merge_class_dict(dict, base); - Py_DECREF(base); - if (status < 0) { - Py_DECREF(bases); - return -1; - } + if (_Py_EnterRecursiveCall(" in __bases__")) { + Py_DECREF(bases); + return -1; + } + for (i = 0; i < n; i++) { + int status; + PyObject *base = PySequence_GetItem(bases, i); + if (base == NULL) { + _Py_LeaveRecursiveCall(); + Py_DECREF(bases); + return -1; + } + status = merge_class_dict(dict, base); + Py_DECREF(base); + if (status < 0) { + _Py_LeaveRecursiveCall(); + Py_DECREF(bases); + return -1; } } + _Py_LeaveRecursiveCall(); Py_DECREF(bases); } return 0;