Skip to content

Commit

Permalink
pythongh-124068: Fix reference leak with generators in the free-threa…
Browse files Browse the repository at this point in the history
…ded build (python#124069)

If the generator is already cleared, then most fields in the
generator's frame are not valid other than f_executable. The invalid
fields may contain dangling pointers and should not be used.
  • Loading branch information
colesbury authored Sep 14, 2024
1 parent 3880917 commit b02301f
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Python/gc_free_threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,20 @@ frame_disable_deferred_refcounting(_PyInterpreterFrame *frame)
// Convert locals, variables, and the executable object to strong
// references from (possibly) deferred references.
assert(frame->stackpointer != NULL);
assert(frame->owner == FRAME_OWNED_BY_FRAME_OBJECT ||
frame->owner == FRAME_OWNED_BY_GENERATOR);

frame->f_executable = PyStackRef_AsStrongReference(frame->f_executable);

if (frame->owner == FRAME_OWNED_BY_GENERATOR) {
PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame);
if (gen->gi_frame_state == FRAME_CLEARED) {
// gh-124068: if the generator is cleared, then most fields other
// than f_executable are not valid.
return;
}
}

for (_PyStackRef *ref = frame->localsplus; ref < frame->stackpointer; ref++) {
if (!PyStackRef_IsNull(*ref) && PyStackRef_IsDeferred(*ref)) {
*ref = PyStackRef_AsStrongReference(*ref);
Expand Down

0 comments on commit b02301f

Please sign in to comment.