Skip to content

Commit d1c0989

Browse files
authored
bpo-20526: Fix PyThreadState_Clear(): don't decref frame (GH-19120) (GH-19136) (GH-19137)
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) (cherry picked from commit e97c8b0)
1 parent 1cdc61c commit d1c0989

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

Include/pystate.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ typedef struct _ts {
216216
struct _ts *next;
217217
PyInterpreterState *interp;
218218

219+
/* Borrowed reference to the current frame (it can be NULL) */
219220
struct _frame *frame;
220221
int recursion_depth;
221222
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
@@ -566,11 +566,19 @@ _PyState_ClearModules(void)
566566
void
567567
PyThreadState_Clear(PyThreadState *tstate)
568568
{
569-
if (Py_VerboseFlag && tstate->frame != NULL)
569+
if (Py_VerboseFlag && tstate->frame != NULL) {
570+
/* bpo-20526: After the main thread calls
571+
_PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
572+
exit when trying to take the GIL. If a thread exit in the middle of
573+
_PyEval_EvalFrameDefault(), tstate->frame is not reset to its
574+
previous value. It is more likely with daemon threads, but it can
575+
happen with regular threads if threading._shutdown() fails
576+
(ex: interrupted by CTRL+C). */
570577
fprintf(stderr,
571578
"PyThreadState_Clear: warning: thread still has a frame\n");
579+
}
572580

573-
Py_CLEAR(tstate->frame);
581+
/* Don't clear tstate->frame: it is a borrowed reference */
574582

575583
Py_CLEAR(tstate->dict);
576584
Py_CLEAR(tstate->async_exc);

0 commit comments

Comments
 (0)