Skip to content

Interpreter crashes if creating a generator for a function whose __code__ was re-assigned #163129

Backlog

Description

@alexmalyshev

Crash report

When the interpreter goes to create a generator in RETURN_GENERATOR, it fetches the frame's function and then that function's code object, which it then uses to size the generator. However, the function's code object might have changed in-between the current frame being pushed and the RETURN_GENERATOR opcode being executed, such as during argument binding. This might lead to the interpreter allocating a generator that is too small to accommodate the frame that it's about to copy into it, result in a heap overflow, and possibly a crash.

def test_code_reassigned_before_generator_created(self):
    # A generator must be created from the code object of the frame being
    # run, even if __code__ was reassigned after that frame was pushed.
    # Here a keyword default lookup runs __eq__ during argument binding,
    # and swaps in a code object with a much smaller frame.
    def small():
        yield 'small'

    src = ('def big(*, x):\n'
           + ''.join(f'    v{i} = {i}\n' for i in range(1000))
           + '    yield x\n')
    ns = {}
    exec(src, ns)
    big = ns['big']
    big_code = big.__code__

    class Key(str):
        __hash__ = str.__hash__

        def __eq__(self, other):
            big.__code__ = small.__code__
            return str.__eq__(self, other)

    gens = []
    for i in range(10):
        big.__code__ = big_code
        big.__kwdefaults__ = {Key('x'): i}
        gens.append(big())
        self.assertIs(big.__code__, small.__code__)

    # Run a GC pass to touch memory and increase the chance of a crash if
    # the generators trampled over memory when they copied their frames.
    support.gc_collect()

    for i, gen in enumerate(gens):
        self.assertIs(gen.gi_code, big_code)
        self.assertEqual(list(gen), [i])

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.16.0a2+dev (heads/main:6ed9dc2ead6, Dec 4 2026, 00:39:14) [GCC 16.2.1 20261029 (Red Hat 16.2.1-3)]

Linked PRs

Activity

  1. added
    type-crash
    on Dec 4, 2026
  2. added
    interpreter-core
    on Dec 4, 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