diff --git a/Lib/test/test_frame.py b/Lib/test/test_frame.py index 2b41ef33a30b44..ccba216cdeea3a 100644 --- a/Lib/test/test_frame.py +++ b/Lib/test/test_frame.py @@ -780,6 +780,31 @@ def g(xs): self.assertEqual(f(), 2) + def test_setitem_after_frame_relocation(self): + # gh-162593: a key's __hash__ may close the generator whose frame + # the proxy refers to. Closing moves the interpreter frame into the + # frame object, so a locals pointer cached before the key lookup is + # stale. The assignment must go to the relocated frame. + def gen(): + a = [1, 2, 3] + yield sys._getframe() + + g = gen() + f = next(g) + p = f.f_locals + + class Key: + def __hash__(self): + g.close() # relocate frame during the lookup + return hash("a") + + def __eq__(self, other): + return other == "a" + + p[Key()] = "NEW" + self.assertEqual(g.gi_frame, None) + self.assertEqual(p["a"], "NEW") + class FrameLocalsProxyMappingTests(mapping_tests.TestHashMappingProtocol): """Test that FrameLocalsProxy behaves like a Mapping (with exceptions)""" diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-25-104500.gh-issue-162593.FrLmQz.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-25-104500.gh-issue-162593.FrLmQz.rst new file mode 100644 index 00000000000000..78bbe0a5fb4703 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-25-104500.gh-issue-162593.FrLmQz.rst @@ -0,0 +1 @@ +Fix a crash in :class:`types.FrameType` locals proxies when a key's __hash__ or __eq__ closes a generator during item assignment. The frame can be relocated into its frame object at that point; the assignment now re-fetches the locals array instead of using a stale pointer, avoiding a use-after-free.\n \ No newline at end of file diff --git a/Objects/frameobject.c b/Objects/frameobject.c index cb987f1606611f..80e3234f91e764 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -271,13 +271,19 @@ framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value) { /* Merge locals into fast locals */ PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; - _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame); - PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); int i = framelocalsproxy_getkeyindex(frame, key, false, NULL); if (i == -2) { return -1; } + // gh-162593: the key lookup above calls PyObject_Hash() and + // PyObject_RichCompareBool(), which can execute arbitrary Python code. + // That code may close a generator and cause the frame to be relocated + // into its frame object (take_ownership()), which invalidates any + // locals-array pointer obtained before the lookup. Fetch it afterwards. + _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame); + PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); + if (i >= 0) { if (value == NULL) { PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");