Skip to content

Commit a50f9b6

Browse files
committed
gh-108987: Fix _thread.start_new_thread() race condition
Fix _thread.start_new_thread() race condition. If a thread is created during Python finalization, the newly spawned thread now exits immediately instead of trying to access freed memory and lead to a crash. thread_run() calls PyEval_AcquireThread() which checks if the thread must exit. The problem was that tstate was dereferenced earlier in _PyThreadState_Bind() which leads to a crash most of the time. Move _PyThreadState_CheckConsistency() from thread_run() to _PyThreadState_Bind().
1 parent f63d378 commit a50f9b6

File tree

5 files changed

+69
-41
lines changed

5 files changed

+69
-41
lines changed

Include/internal/pycore_pystate.h

+2
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ extern _Py_thread_local PyThreadState *_Py_tss_tstate;
7171
extern int _PyThreadState_CheckConsistency(PyThreadState *tstate);
7272
#endif
7373

74+
int _PyThreadState_MustExit(PyThreadState *tstate);
75+
7476
// Export for most shared extensions, used via _PyThreadState_GET() static
7577
// inline function.
7678
PyAPI_FUNC(PyThreadState *) _PyThreadState_GetCurrent(void);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :func:`_thread.start_new_thread` race condition. If a thread is created
2+
during Python finalization, the newly spawned thread now exits immediately
3+
instead of trying to access freed memory and lead to a crash. Patch by
4+
Victor Stinner.

Modules/_threadmodule.c

+31-16
Original file line numberDiff line numberDiff line change
@@ -1051,21 +1051,21 @@ _localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
10511051
/* Module functions */
10521052

10531053
struct bootstate {
1054-
PyInterpreterState *interp;
1054+
PyThreadState *tstate;
10551055
PyObject *func;
10561056
PyObject *args;
10571057
PyObject *kwargs;
1058-
PyThreadState *tstate;
1059-
_PyRuntimeState *runtime;
10601058
};
10611059

10621060

10631061
static void
1064-
thread_bootstate_free(struct bootstate *boot)
1062+
thread_bootstate_free(struct bootstate *boot, int decref)
10651063
{
1066-
Py_DECREF(boot->func);
1067-
Py_DECREF(boot->args);
1068-
Py_XDECREF(boot->kwargs);
1064+
if (decref) {
1065+
Py_DECREF(boot->func);
1066+
Py_DECREF(boot->args);
1067+
Py_XDECREF(boot->kwargs);
1068+
}
10691069
PyMem_Free(boot);
10701070
}
10711071

@@ -1076,9 +1076,24 @@ thread_run(void *boot_raw)
10761076
struct bootstate *boot = (struct bootstate *) boot_raw;
10771077
PyThreadState *tstate = boot->tstate;
10781078

1079-
// gh-104690: If Python is being finalized and PyInterpreterState_Delete()
1080-
// was called, tstate becomes a dangling pointer.
1081-
assert(_PyThreadState_CheckConsistency(tstate));
1079+
// gh-108987: If _thread.start_new_thread() is called before or while
1080+
// Python is being finalized, thread_run() can called *after*.
1081+
// _PyRuntimeState_SetFinalizing() is called. At this point, all Python
1082+
// threads must exit, except of the thread calling Py_Finalize() whch holds
1083+
// the GIL and must not exit.
1084+
//
1085+
// At this stage, tstate can be a dangling pointer (point to freed memory),
1086+
// it's ok to call _PyThreadState_MustExit() with a dangling pointer.
1087+
if (_PyThreadState_MustExit(tstate)) {
1088+
// Don't call PyThreadState_Clear() nor _PyThreadState_DeleteCurrent().
1089+
// These functions are called on tstate indirectly by Py_Finalize()
1090+
// which calls _PyInterpreterState_Clear().
1091+
//
1092+
// Py_DECREF() cannot be called because the GIL is not held: leak
1093+
// references on purpose. Python is being finalized anyway.
1094+
thread_bootstate_free(boot, 0);
1095+
goto exit;
1096+
}
10821097

10831098
_PyThreadState_Bind(tstate);
10841099
PyEval_AcquireThread(tstate);
@@ -1097,14 +1112,17 @@ thread_run(void *boot_raw)
10971112
Py_DECREF(res);
10981113
}
10991114

1100-
thread_bootstate_free(boot);
1115+
thread_bootstate_free(boot, 1);
1116+
11011117
tstate->interp->threads.count--;
11021118
PyThreadState_Clear(tstate);
11031119
_PyThreadState_DeleteCurrent(tstate);
11041120

1121+
exit:
11051122
// bpo-44434: Don't call explicitly PyThread_exit_thread(). On Linux with
11061123
// the glibc, pthread_exit() can abort the whole process if dlopen() fails
11071124
// to open the libgcc_s.so library (ex: EMFILE error).
1125+
return;
11081126
}
11091127

11101128
static PyObject *
@@ -1128,7 +1146,6 @@ and False otherwise.\n");
11281146
static PyObject *
11291147
thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
11301148
{
1131-
_PyRuntimeState *runtime = &_PyRuntime;
11321149
PyObject *func, *args, *kwargs = NULL;
11331150

11341151
if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
@@ -1171,16 +1188,14 @@ thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
11711188
if (boot == NULL) {
11721189
return PyErr_NoMemory();
11731190
}
1174-
boot->interp = _PyInterpreterState_GET();
1175-
boot->tstate = _PyThreadState_New(boot->interp);
1191+
boot->tstate = _PyThreadState_New(interp);
11761192
if (boot->tstate == NULL) {
11771193
PyMem_Free(boot);
11781194
if (!PyErr_Occurred()) {
11791195
return PyErr_NoMemory();
11801196
}
11811197
return NULL;
11821198
}
1183-
boot->runtime = runtime;
11841199
boot->func = Py_NewRef(func);
11851200
boot->args = Py_NewRef(args);
11861201
boot->kwargs = Py_XNewRef(kwargs);
@@ -1189,7 +1204,7 @@ thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
11891204
if (ident == PYTHREAD_INVALID_THREAD_ID) {
11901205
PyErr_SetString(ThreadError, "can't start new thread");
11911206
PyThreadState_Clear(boot->tstate);
1192-
thread_bootstate_free(boot);
1207+
thread_bootstate_free(boot, 1);
11931208
return NULL;
11941209
}
11951210
return PyLong_FromUnsignedLong(ident);

Python/ceval_gil.c

+3-25
Original file line numberDiff line numberDiff line change
@@ -329,28 +329,6 @@ drop_gil(struct _ceval_state *ceval, PyThreadState *tstate)
329329
}
330330

331331

332-
/* Check if a Python thread must exit immediately, rather than taking the GIL
333-
if Py_Finalize() has been called.
334-
335-
When this function is called by a daemon thread after Py_Finalize() has been
336-
called, the GIL does no longer exist.
337-
338-
tstate must be non-NULL. */
339-
static inline int
340-
tstate_must_exit(PyThreadState *tstate)
341-
{
342-
/* bpo-39877: Access _PyRuntime directly rather than using
343-
tstate->interp->runtime to support calls from Python daemon threads.
344-
After Py_Finalize() has been called, tstate can be a dangling pointer:
345-
point to PyThreadState freed memory. */
346-
PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
347-
if (finalizing == NULL) {
348-
finalizing = _PyInterpreterState_GetFinalizing(tstate->interp);
349-
}
350-
return (finalizing != NULL && finalizing != tstate);
351-
}
352-
353-
354332
/* Take the GIL.
355333
356334
The function saves errno at entry and restores its value at exit.
@@ -366,7 +344,7 @@ take_gil(PyThreadState *tstate)
366344
// XXX It may be more correct to check tstate->_status.finalizing.
367345
// XXX assert(!tstate->_status.cleared);
368346

369-
if (tstate_must_exit(tstate)) {
347+
if (_PyThreadState_MustExit(tstate)) {
370348
/* bpo-39877: If Py_Finalize() has been called and tstate is not the
371349
thread which called Py_Finalize(), exit immediately the thread.
372350
@@ -404,7 +382,7 @@ take_gil(PyThreadState *tstate)
404382
_Py_atomic_load_relaxed(&gil->locked) &&
405383
gil->switch_number == saved_switchnum)
406384
{
407-
if (tstate_must_exit(tstate)) {
385+
if (_PyThreadState_MustExit(tstate)) {
408386
MUTEX_UNLOCK(gil->mutex);
409387
// gh-96387: If the loop requested a drop request in a previous
410388
// iteration, reset the request. Otherwise, drop_gil() can
@@ -444,7 +422,7 @@ take_gil(PyThreadState *tstate)
444422
MUTEX_UNLOCK(gil->switch_mutex);
445423
#endif
446424

447-
if (tstate_must_exit(tstate)) {
425+
if (_PyThreadState_MustExit(tstate)) {
448426
/* bpo-36475: If Py_Finalize() has been called and tstate is not
449427
the thread which called Py_Finalize(), exit immediately the
450428
thread.

Python/pystate.c

+29
Original file line numberDiff line numberDiff line change
@@ -1907,6 +1907,10 @@ PyThreadState_Swap(PyThreadState *newts)
19071907
void
19081908
_PyThreadState_Bind(PyThreadState *tstate)
19091909
{
1910+
// gh-104690: If Python is being finalized and PyInterpreterState_Delete()
1911+
// was called, tstate becomes a dangling pointer.
1912+
assert(_PyThreadState_CheckConsistency(tstate));
1913+
19101914
bind_tstate(tstate);
19111915
// This makes sure there's a gilstate tstate bound
19121916
// as soon as possible.
@@ -2908,6 +2912,31 @@ _PyThreadState_CheckConsistency(PyThreadState *tstate)
29082912
#endif
29092913

29102914

2915+
// Check if a Python thread must exit immediately, rather than taking the GIL
2916+
// if Py_Finalize() has been called.
2917+
//
2918+
// When this function is called by a daemon thread after Py_Finalize() has been
2919+
// called, the GIL does no longer exist.
2920+
//
2921+
// tstate can be a dangling pointer (point to freed memory): only tstate value
2922+
// is used, the pointer is not deferenced.
2923+
//
2924+
// tstate must be non-NULL.
2925+
int
2926+
_PyThreadState_MustExit(PyThreadState *tstate)
2927+
{
2928+
/* bpo-39877: Access _PyRuntime directly rather than using
2929+
tstate->interp->runtime to support calls from Python daemon threads.
2930+
After Py_Finalize() has been called, tstate can be a dangling pointer:
2931+
point to PyThreadState freed memory. */
2932+
PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
2933+
if (finalizing == NULL) {
2934+
finalizing = _PyInterpreterState_GetFinalizing(tstate->interp);
2935+
}
2936+
return (finalizing != NULL && finalizing != tstate);
2937+
}
2938+
2939+
29112940
#ifdef __cplusplus
29122941
}
29132942
#endif

0 commit comments

Comments
 (0)