Skip to content

Commit 8765a69

Browse files
alexmalyshevclaude
andcommitted
gh-163129: Size new generators from the frame's code object
Currently RETURN_GENERATOR sizes the new generator (and determines its type) from the code object loaded from the function on the current frame. This is not necessarily the same code object that was current when the frame was actually pushed. The function's __code__ could have been re-assigned in the interim. This is dangerous as the generator's frame size won't match that of the interpreter, and when the interpreter goes to call _PyFrame_Copy it risks a heap overflow. Pass the frame's code object to _Py_MakeCoro() explicitly instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6ed9dc2 commit 8765a69

8 files changed

Lines changed: 58 additions & 12 deletions

File tree

‎Include/internal/pycore_ceval.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ extern int _PyEval_EnsureBuiltinsWithModule(
266266
PyObject *,
267267
PyObject **p_builtins);
268268

269-
PyAPI_FUNC(PyObject *)_Py_MakeCoro(PyFunctionObject *func);
269+
PyAPI_FUNC(PyObject *)_Py_MakeCoro(PyFunctionObject *func, PyCodeObject *code);
270270

271271
/* Handle signals, pending calls, GIL drop request
272272
and asynchronous exception */

‎Lib/test/test_generators.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,45 @@ def generator(arg):
330330
g.gi_frame.clear()
331331
self.assertTrue(DetectDelete.deleted)
332332

333+
def test_code_reassigned_before_generator_created(self):
334+
# A generator must be created from the code object of the frame being
335+
# run, even if __code__ was reassigned after that frame was pushed.
336+
# Here a keyword default lookup runs __eq__ during argument binding,
337+
# and swaps in a code object with a much smaller frame.
338+
def small():
339+
yield 'small'
340+
341+
src = ('def big(*, x):\n'
342+
+ ''.join(f' v{i} = {i}\n' for i in range(1000))
343+
+ ' yield x\n')
344+
ns = {}
345+
exec(src, ns)
346+
big = ns['big']
347+
big_code = big.__code__
348+
349+
class Key(str):
350+
__hash__ = str.__hash__
351+
352+
def __eq__(self, other):
353+
big.__code__ = small.__code__
354+
return str.__eq__(self, other)
355+
356+
gens = []
357+
for i in range(10):
358+
big.__code__ = big_code
359+
big.__kwdefaults__ = {Key('x'): i}
360+
gens.append(big())
361+
self.assertIs(big.__code__, small.__code__)
362+
363+
# Run a GC pass to touch memory and increase the chance of a crash if
364+
# the generators trampled over memory when they copied their frames.
365+
support.gc_collect()
366+
367+
for i, gen in enumerate(gens):
368+
self.assertIs(gen.gi_code, big_code)
369+
self.assertEqual(list(gen), [i])
370+
371+
333372
class ModifyUnderlyingIterableTest(unittest.TestCase):
334373
iterables = [
335374
range(0),
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a heap buffer overflow when creating a generator, coroutine or
2+
asynchronous generator for a function whose :attr:`~function.__code__`
3+
was reassigned after the call began.

‎Modules/_testinternalcapi/test_cases.c.h‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Objects/genobject.c‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,9 +1104,8 @@ PyTypeObject PyGen_Type = {
11041104
};
11051105

11061106
static PyObject *
1107-
make_gen(PyTypeObject *type, PyFunctionObject *func)
1107+
make_gen(PyTypeObject *type, PyFunctionObject *func, PyCodeObject *code)
11081108
{
1109-
PyCodeObject *code = (PyCodeObject *)func->func_code;
11101109
int slots = _PyFrame_NumSlotsForCodeObject(code);
11111110
PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots);
11121111
if (gen == NULL) {
@@ -1127,18 +1126,23 @@ make_gen(PyTypeObject *type, PyFunctionObject *func)
11271126
return (PyObject *)gen;
11281127
}
11291128

1129+
/* Create a generator object for a frame that is executing
1130+
RETURN_GENERATOR. *code* must be the frame's code object. The
1131+
function's __code__ may have been reassigned since the frame was
1132+
pushed, but the generator must be sized for the frame it will hold.
1133+
*/
11301134
PyObject *
1131-
_Py_MakeCoro(PyFunctionObject *func)
1135+
_Py_MakeCoro(PyFunctionObject *func, PyCodeObject *code)
11321136
{
1133-
int coro_flags = ((PyCodeObject *)func->func_code)->co_flags &
1137+
int coro_flags = code->co_flags &
11341138
(CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR);
11351139
assert(coro_flags);
11361140
if (coro_flags == CO_GENERATOR) {
1137-
return make_gen(&PyGen_Type, func);
1141+
return make_gen(&PyGen_Type, func, code);
11381142
}
11391143
if (coro_flags == CO_ASYNC_GENERATOR) {
11401144
PyAsyncGenObject *ag;
1141-
ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func);
1145+
ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func, code);
11421146
if (ag == NULL) {
11431147
return NULL;
11441148
}
@@ -1150,7 +1154,7 @@ _Py_MakeCoro(PyFunctionObject *func)
11501154
}
11511155

11521156
assert (coro_flags == CO_COROUTINE);
1153-
PyObject *coro = make_gen(&PyCoro_Type, func);
1157+
PyObject *coro = make_gen(&PyCoro_Type, func, code);
11541158
if (!coro) {
11551159
return NULL;
11561160
}

‎Python/bytecodes.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5810,7 +5810,7 @@ dummy_func(
58105810
inst(RETURN_GENERATOR, (-- res)) {
58115811
assert(PyStackRef_FunctionCheck(frame->f_funcobj));
58125812
PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj);
5813-
PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func);
5813+
PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func, _PyFrame_GetCode(frame));
58145814
ERROR_IF(gen == NULL);
58155815
assert(STACK_LEVEL() <= 2);
58165816
SAVE_STACK();

‎Python/executor_cases.c.h‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Python/generated_cases.c.h‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)