gh-112723: Call PyThreadState_Clear() from the correct interpreter (#112776)

The `PyThreadState_Clear()` function must only be called with the GIL
held and must be called from the same interpreter as the passed in
thread state. Otherwise, any Python objects on the thread state may be
destroyed using the wrong interpreter, leading to memory corruption.

This is also important for `Py_GIL_DISABLED` builds because free lists
will be associated with PyThreadStates and cleared in
`PyThreadState_Clear()`.

This fixes two places that called `PyThreadState_Clear()` from the wrong
interpreter and adds an assertion to `PyThreadState_Clear()`.
This commit is contained in:
Sam Gross 2023-12-12 19:20:21 -05:00 committed by GitHub
parent 8a4c1f3ff1
commit a3c031884d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 34 additions and 55 deletions

View file

@ -447,7 +447,7 @@ init_own_gil(PyInterpreterState *interp, struct _gil_runtime_state *gil)
interp->ceval.own_gil = 1;
}
PyStatus
void
_PyEval_InitGIL(PyThreadState *tstate, int own_gil)
{
assert(tstate->interp->ceval.gil == NULL);
@ -466,8 +466,6 @@ _PyEval_InitGIL(PyThreadState *tstate, int own_gil)
// Lock the GIL and mark the current thread as attached.
_PyThreadState_Attach(tstate);
return _PyStatus_OK();
}
void