Skip to content

Commit e97c8b0

Browse files
authored
bpo-20526: Fix PyThreadState_Clear(): don't decref frame (GH-19120) (GH-19136)
PyThreadState.frame is a borrowed reference, not a strong reference: PyThreadState_Clear() must not call Py_CLEAR(tstate->frame). Remove test_threading.test_warnings_at_exit(): we cannot warranty that the Python thread state of daemon threads is cleared in a reliable way during Python shutdown. (cherry picked from commit 5804f87)
1 parent 21bee0b commit e97c8b0

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

Include/cpython/pystate.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ struct _ts {
5555
struct _ts *next;
5656
PyInterpreterState *interp;
5757

58+
/* Borrowed reference to the current frame (it can be NULL) */
5859
struct _frame *frame;
5960
int recursion_depth;
6061
char overflowed; /* The stack has overflowed. Allow 50 more calls
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :c:func:`PyThreadState_Clear()`. ``PyThreadState.frame`` is a borrowed
2+
reference, not a strong reference: ``PyThreadState_Clear()`` must not call
3+
``Py_CLEAR(tstate->frame)``.

Python/pystate.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -762,11 +762,19 @@ PyThreadState_Clear(PyThreadState *tstate)
762762
{
763763
int verbose = tstate->interp->config.verbose;
764764

765-
if (verbose && tstate->frame != NULL)
765+
if (verbose && tstate->frame != NULL) {
766+
/* bpo-20526: After the main thread calls
767+
_PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
768+
exit when trying to take the GIL. If a thread exit in the middle of
769+
_PyEval_EvalFrameDefault(), tstate->frame is not reset to its
770+
previous value. It is more likely with daemon threads, but it can
771+
happen with regular threads if threading._shutdown() fails
772+
(ex: interrupted by CTRL+C). */
766773
fprintf(stderr,
767774
"PyThreadState_Clear: warning: thread still has a frame\n");
775+
}
768776

769-
Py_CLEAR(tstate->frame);
777+
/* Don't clear tstate->frame: it is a borrowed reference */
770778

771779
Py_CLEAR(tstate->dict);
772780
Py_CLEAR(tstate->async_exc);

0 commit comments

Comments
 (0)