Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Lib/test/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"""
Expand Down
Original file line number Diff line number Diff line change
@@ -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
10 changes: 8 additions & 2 deletions Objects/frameobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading