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
  3. picnixz commented on Dec 4, 2026

    @picnixz
    Member

    I feel that this crash is similar to messing up with code.__replace__. When is it possible for such even to happen for regular code and not just code that replaces __code__ attributes without taking care of that? is it something we should support?

  4. alexmalyshev commented on Dec 4, 2026

    @alexmalyshev
    ContributorAuthor

    @picnixz It's definitely not something most users would encounter. I would say that it's important to address the potential crash, because the interpreter shouldn't crash from Python code like this, but it doesn't really matter how the code behaves / what it resolves to.

  5. picnixz commented on Dec 4, 2026

    @picnixz
    Member

    , but it doesn't really matter how the code behaves / what it resolves to.

    No it matters. We don't consider these as real issues if the reproducer is messing with interpreter's state in such a way that could affect performance for instance.

    For instance, any crashes obtained by incorrectly using code.__replace__ is not considered a bug. Potential crashes that require contrived examples like that are therefore rejected. But if you can get that crash without such convoluted example, we usually accept the report.

    That's why I want to know if there are legitimate use cases of changing __code__ entirely after creating a generator.

  6. alexmalyshev commented on Dec 4, 2026

    @alexmalyshev
    ContributorAuthor

    @picnixz Asking some basic questions, sorry, new here, thanks for bearing with me :)

    We don't consider these as real issues if the reproducer is messing with interpreter's state in such a way that could affect performance for instance.

    "Messing with the interpreter's state" to me sounds like a user calling through the C API though, rather than through Python code. I would assume that Python code should never crash the interpreter, is that not the case?

    For instance, any crashes obtained by incorrectly using code.replace is not considered a bug.

    Is this documented anywhere? And what does "incorrect" usage here mean? I only found https://docs.python.org/3/reference/datamodel.html#codeobject.replace which doesn't include any warnings / suggestions on using this correctly.

    That's why I want to know if there are legitimate use cases of changing code entirely after creating a generator.

    It's not really a legitimate situation on the GIL build, it's more of a problem for the free-threaded build. Any thread that's re-assigning a function's __code__ (hot reloading?) can collide with another thread that's creating a generator for the same function. I wanted to submit a reproducer that affected both GIL and FT so it could be tested across both builds, hence the odd case.

  7. picnixz commented on Dec 4, 2026

    @picnixz
    Member

    "Messing with the interpreter's state" to me sounds like a user calling through the C API though, rather than through Python code. I would assume that Python code should never crash the interpreter, is that not the case?

    No it's not the case. For instance, messing with ctypes, with concurrent mutations that are weird or with code.__replace__ are usually not legitimate changes.


    It's not documented because it's something a "if you mess with something incorrectly that is deeply related to internals, you're on your own", and we don't want to document any changes that should not be done because it can crash something (it's part of what people would consider "common sense"). It's an oral... knowledge (like anything in computer science). I've written something in the devguide but I haven't merged that yet.

    . Any thread that's re-assigning a function's code (hot reloading?) can collide with another thread that's creating a generator for the same function.

    Is this something that happens frequently? I would assume that it's a case where you're responsible for the change.


    That being said, the change you're suggesting looks small enough to be accepted but I still think it's a pathological case.

  8. alexmalyshev commented on Dec 4, 2026

    @alexmalyshev
    ContributorAuthor

    Is this something that happens frequently? I would assume that it's a case where you're responsible for the change.

    Probably not frequently, but without this fix it would be troublesome to handle it from user code. To me at least, it would be a surprise that I'd need guard all uses (reads, calls, .etc) of func with a lock to be safe to assign to func.__code__ but not for func.__name__, for instance. At least in the context of not crashing, vs not racing.

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