[3.13] gh-137400: Fix thread-safety issues when profiling all threads (gh-137518) (gh-137733)

There were a few thread-safety issues when profiling or tracing all
threads via PyEval_SetProfileAllThreads or PyEval_SetTraceAllThreads:

* The loop over thread states could crash if a thread exits concurrently
  (in both the free threading and default build)
* The modification of `c_profilefunc` and `c_tracefunc` wasn't
  thread-safe on the free threading build.
(cherry picked from commit a10152f8fd)
This commit is contained in:
Sam Gross 2025-10-09 11:42:47 -04:00 committed by GitHub
parent f6186a3709
commit 16d2e97cf3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 29814 additions and 29714 deletions

View file

@ -399,7 +399,6 @@ _Py_COMP_DIAG_POP
&(runtime)->unicode_state.ids.mutex, \
&(runtime)->imports.extensions.mutex, \
&(runtime)->ceval.pending_mainthread.mutex, \
&(runtime)->ceval.sys_trace_profile_mutex, \
&(runtime)->atexit.mutex, \
&(runtime)->audit_hooks.mutex, \
&(runtime)->allocators.mutex, \
@ -654,8 +653,6 @@ init_interpreter(PyInterpreterState *interp,
}
}
interp->sys_profile_initialized = false;
interp->sys_trace_initialized = false;
#ifdef _Py_TIER2
(void)_Py_SetOptimizer(interp, NULL);
interp->executor_list_head = NULL;
@ -838,8 +835,6 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
Py_CLEAR(interp->monitoring_callables[t][e]);
}
}
interp->sys_profile_initialized = false;
interp->sys_trace_initialized = false;
for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
Py_CLEAR(interp->monitoring_tool_names[t]);
}
@ -1724,11 +1719,11 @@ PyThreadState_Clear(PyThreadState *tstate)
}
if (tstate->c_profilefunc != NULL) {
tstate->interp->sys_profiling_threads--;
_Py_atomic_add_ssize(&tstate->interp->sys_profiling_threads, -1);
tstate->c_profilefunc = NULL;
}
if (tstate->c_tracefunc != NULL) {
tstate->interp->sys_tracing_threads--;
_Py_atomic_add_ssize(&tstate->interp->sys_tracing_threads, -1);
tstate->c_tracefunc = NULL;
}
Py_CLEAR(tstate->c_profileobj);