Skip to content

segfault in FrameLocalsProxy #162593

Backlog

Description

@agenticensor

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)

  1. Objects/frameobject.c:246-321 — framelocalsproxy_setitem(): fast = _PyFrame_GetLocalsArray(frame->f_frame) and co are computed at lines 251-252, before the key lookup at line 254.
  2. Objects/frameobject.c:115,160 — framelocalsproxy_getkeyindex(): PyObject_Hash(key) and PyObject_RichCompareBool(name, key, Py_EQ) run arbitrary Python code. (Its own reads are safe: lines 128/166 pass frame->f_frame afresh to framelocalsproxy_getval(), which is why the read path is fine.)
  3. 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-points f->f_frame (line 58), then returns without clearing either copy (lines 120-122). The frame object now owns the locals; the generator-embedded _PyInterpreterFrame is dead storage that merely still holds the old pointer values.
  4. Back in framelocalsproxy_setitem(), lines 269 and 286-293 use the cached fast: PyStackRef_CLOSE(fast[i]) (line 291) releases a reference that is now owned by the relocated frame's slot, and fast[i] = PyStackRef_FromPyObjectNew(value) (line 293) stores the new value in the dead copy. Because add_overwritten_fast_local() takes a new reference first (line 288), the refcount looks unchanged at this point — but the relocated slot and f_overwritten_fast_locals now 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 ]

Linked PRs

Activity

  1. added
    type-crash
    on Nov 25, 2026
  2. added
    interpreter-core
    on Nov 25, 2026
  3. added a commit that references this issue on Nov 25, 2026
  4. added a commit that references this issue on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-crash

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions