From e6ef47ac229b5c4a62b9c907e4232e350db77ce3 Mon Sep 17 00:00:00 2001 From: "Tomas R." Date: Fri, 11 Apr 2025 23:05:03 +0200 Subject: [PATCH] gh-132386: Fix a crash when passing a dict subclass to `exec` (GH-132412) * Fix crash when passing a dict subclass to exec * Add news entry --- Lib/test/test_compile.py | 10 ++++++++++ .../2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst | 2 ++ Python/ceval.c | 2 ++ 3 files changed, 14 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index ce9c060641d..9cc025d85e1 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -1636,6 +1636,16 @@ class TestSpecifics(unittest.TestCase): pass [[]] + def test_globals_dict_subclass(self): + # gh-132386 + class WeirdDict(dict): + pass + + ns = {} + exec('def foo(): return a', WeirdDict(), ns) + + self.assertRaises(NameError, ns['foo']) + class TestBooleanExpression(unittest.TestCase): class Value: def __init__(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst new file mode 100644 index 00000000000..65ba7fc182b --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst @@ -0,0 +1,2 @@ +Fix crash when passing a dict subclass as the ``globals`` parameter to +:func:`exec`. diff --git a/Python/ceval.c b/Python/ceval.c index 8ab0c6318c1..e4a63ad9287 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3312,6 +3312,8 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name _PyEval_FormatExcCheckArg( PyThreadState_GET(), PyExc_NameError, NAME_ERROR_MSG, name); + *writeto = PyStackRef_NULL; + return; } } *writeto = PyStackRef_FromPyObjectSteal(res);