You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Interpreter crashes if creating a generator for a function whose __code__ was re-assigned #163129
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.
deftest_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.defsmall():
yield'small'src= ('def big(*, x):\n'+''.join(f' v{i} = {i}\n'foriinrange(1000))
+' yield x\n')
ns= {}
exec(src, ns)
big=ns['big']
big_code=big.__code__classKey(str):
__hash__=str.__hash__def__eq__(self, other):
big.__code__=small.__code__returnstr.__eq__(self, other)
gens= []
foriinrange(10):
big.__code__=big_codebig.__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()
fori, geninenumerate(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)]
Activity