Repository navigation
Description
Crash report
FrameLocalsProxy.__setitem__ (framelocalsproxy_setitem()) takes a pointer to the frame's locals array before it looks up the key. The lookup calls PyObject_Hash() / PyObject_RichCompareBool(), i.e. arbitrary Python code. If that code closes or exhausts the generator that owns the frame while the frame object is still referenced, _PyFrame_ClearExceptCode() moves the frame (locals included) into the frame object via take_ownership() and re-points frame->f_frame. The cached pointer is now stale, so:
- the new value is written into the abandoned copy inside the generator object — the assignment is silently lost, and
- the old value's reference, which now belongs to the relocated frame, is released anyway. Its refcount ends up one too low and it is freed while still referenced.
Assigning to the same closed frame after g.close() returns works fine; only the re-entrant timing is broken.
Reproduction
import sys
old = [1, 2, 3]
def gen():
a = old
f = sys._getframe()
yield f
yield a
g = gen()
f = next(g)
p = f.f_locals
class K:
def __hash__(self):
g.close() # closes the generator while __setitem__ is running
return hash("a")
def __eq__(self, other):
return other == "a"
p[K()] = "NEW"
print(g.gi_state, p["a"]) # GEN_CLOSED [1, 2, 3] <- the write was lost$ python3.15 repro.py
GEN_CLOSED [1, 2, 3]
Segmentation fault # exit status 139, during interpreter shutdown; 20/20 runs
Two single-change controls behave correctly and exit 0:
- remove
g.close()from__hash__→GEN_SUSPENDED NEW - move
g.close()before the assignment →GEN_CLOSED NEW
$ PYTHONMALLOC=malloc valgrind --tool=memcheck python3.15 repro.py
GEN_CLOSED [1, 2, 3]
==38249== Invalid read of size 8
==38249== at 0x1AEE123: _PyObject_ClearFreeLists.warm (in .../bin/python3.15)
==38249== by 0x1ACB528: gc_collect_main.warm (in .../bin/python3.15)
==38249== by 0x19844CE: finalize_modules (in .../bin/python3.15)
==38249== by 0x19820A4: _Py_Finalize (in .../bin/python3.15)
==38249== Address 0x1517b1140 is not stack'd, malloc'd or (recently) free'd
==38249==
==38249== Process terminating with default action of signal 11 (SIGSEGV)
==38249== Access not within mapped region at address 0x1517B1140
The shutdown crash is a late symptom. The memory error itself is deterministic and visible without tools:
import weakref
class X:
pass
def gen():
a = X()
yield
g = gen()
next(g)
p = g.gi_frame.f_locals
keep = p["a"] # strong reference held outside the frame
ref = weakref.ref(keep)
class K(str):
def __hash__(self):
g.close() # closes the generator while __setitem__ is running
return super().__hash__()
p[K("a")] = "NEW"
del p # frame object dies
print("died while `keep` still references it:", ref() is None)$ python3.15 repro2.py
died while `keep` still references it: True # expected: False
Moving g.close() before the assignment prints False.
$ PYTHONMALLOC=malloc valgrind --tool=memcheck python3.15 repro2.py
died while `keep` still references it: True
==38251== Invalid read of size 8
==38251== at 0x1800661: dict_traverse (in .../bin/python3.15)
==38251== by 0x1806102: gc_collect_main (in .../bin/python3.15)
==38251== by 0x1982049: _Py_Finalize (in .../bin/python3.15)
==38251== Address 0x5396988 is 40 bytes inside a block of size 328 free'd
==38251== at 0x484787F: free (vg_replace_malloc.c:989)
==38251== by 0x181293A: subtype_dealloc
==38251== by 0x1808330: tuple_dealloc
==38251== by 0x1801E90: _Py_Dealloc
==38251== by 0x1ACEF96: frame_dealloc.warm
==38251== by 0x1801E90: _Py_Dealloc
==38251== by 0x192A884: framelocalsproxy_dealloc
==38251== by 0x1801E90: _Py_Dealloc
==38251== by 0x1884359: _PyDict_DelItem_KnownHash_LockHeld # the `del p`
==38251== Block was alloc'd at
==38251== at 0x4844818: malloc (vg_replace_malloc.c:446)
==38251== by 0x1820DFD: PyType_GenericAlloc
==38251== by 0x1807791: type_call # X() inside the generator
...
==38251== Invalid write of size 4
==38251== at 0x1810C92: dictkeys_decref
==38251== by 0x18109B0: dict_tp_clear # module dict cleared, releasing `keep`
==38251== by 0x1ACB220: gc_collect_main.warm
==38251== by 0x19844CE: finalize_modules
==38251== Address 0x5396980 is 32 bytes inside a block of size 328 free'd
...
==38251== ERROR SUMMARY: 10 errors from 10 contexts
The control (g.close() before the assignment) reports 0 valgrind errors.
Root cause (v3.15.2)
Objects/frameobject.c:246-321—framelocalsproxy_setitem():fast = _PyFrame_GetLocalsArray(frame->f_frame)andcoare computed at lines 251-252, before the key lookup at line 254.Objects/frameobject.c:115,160—framelocalsproxy_getkeyindex():PyObject_Hash(key)andPyObject_RichCompareBool(name, key, Py_EQ)run arbitrary Python code. (Its own reads are safe: lines 128/166 passframe->f_frameafresh toframelocalsproxy_getval(), which is why the read path is fine.)g.close()→Objects/genobject.c:499-512→gen_clear_frame()(Objects/genobject.c:166-175) →_PyFrame_ClearExceptCode()(Python/frame.c:106-128). If the frame object has other references (line 119 — here the proxy),take_ownership()(Python/frame.c:48-90) copies the_PyInterpreterFrame, locals included, into the frame object and re-pointsf->f_frame(line 58), then returns without clearing either copy (lines 120-122). The frame object now owns the locals; the generator-embedded_PyInterpreterFrameis dead storage that merely still holds the old pointer values.- Back in
framelocalsproxy_setitem(), lines 269 and 286-293 use the cachedfast:PyStackRef_CLOSE(fast[i])(line 291) releases a reference that is now owned by the relocated frame's slot, andfast[i] = PyStackRef_FromPyObjectNew(value)(line 293) stores the new value in the dead copy. Becauseadd_overwritten_fast_local()takes a new reference first (line 288), the refcount looks unchanged at this point — but the relocated slot andf_overwritten_fast_localsnow hold two references where only one is counted. Both are released when the frame dies (frame_dealloc(), lines 1945-1956;frame_tp_clear(), lines 1983-1993).
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Output from running 'python -VV' on the command line:
Python 3.15.2 (main, Nov 11 2026, 00:19:20) [Clang 23.1.3 ]
Activity
pythongh-162593: Fix use-after-free in FrameLocalsProxy item assignment
pythongh-162593: add tests for FrameLocalsProxy writes on closed and …