Skip to content

Commit 46cae02

Browse files
[3.11] gh-106092: Fix use-after-free crash in frame_dealloc (GH-106875) (#107533)
1 parent 3be07c9 commit 46cae02

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a segmentation fault caused by a use-after-free bug in ``frame_dealloc``
2+
when the trashcan delays the deallocation of a ``PyFrameObject``.

Objects/frameobject.c

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -851,20 +851,21 @@ frame_dealloc(PyFrameObject *f)
851851
/* It is the responsibility of the owning generator/coroutine
852852
* to have cleared the generator pointer */
853853

854-
assert(f->f_frame->owner != FRAME_OWNED_BY_GENERATOR ||
855-
_PyFrame_GetGenerator(f->f_frame)->gi_frame_state == FRAME_CLEARED);
856-
857854
if (_PyObject_GC_IS_TRACKED(f)) {
858855
_PyObject_GC_UNTRACK(f);
859856
}
860857

861858
Py_TRASHCAN_BEGIN(f, frame_dealloc);
862859
PyCodeObject *co = NULL;
863860

861+
/* GH-106092: If f->f_frame was on the stack and we reached the maximum
862+
* nesting depth for deallocations, the trashcan may have delayed this
863+
* deallocation until after f->f_frame is freed. Avoid dereferencing
864+
* f->f_frame unless we know it still points to valid memory. */
865+
_PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
866+
864867
/* Kill all local variables including specials, if we own them */
865-
if (f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
866-
assert(f->f_frame == (_PyInterpreterFrame *)f->_f_frame_data);
867-
_PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
868+
if (f->f_frame == frame && frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
868869
/* Don't clear code object until the end */
869870
co = frame->f_code;
870871
frame->f_code = NULL;

0 commit comments

Comments
 (0)