From f29f87872941ac061ef64034373730683e0203fb Mon Sep 17 00:00:00 2001 From: Matt Wozniski Date: Wed, 6 Aug 2025 11:43:56 -0400 Subject: [PATCH 1/2] gh-137400: Stop the world when swapping profile functions One thread's profile function or profile object can be changed from another thread, for instance by `sys._setprofileallthreads`. This can lead to crashes unless the two threads are synchronized. We need a stop-the-world to ensure that the thread whose profile function or profile object is being changed is in a state where it's not in the middle of using either of those pointers. Signed-off-by: Matt Wozniski --- Python/legacy_tracing.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Python/legacy_tracing.c b/Python/legacy_tracing.c index dbd19d7755c237..0a0d231cb12d0c 100644 --- a/Python/legacy_tracing.c +++ b/Python/legacy_tracing.c @@ -484,13 +484,19 @@ setup_profile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg, PyObject } } + _PyEval_StopTheWorld(tstate->interp); + int delta = (func != NULL) - (tstate->c_profilefunc != NULL); tstate->c_profilefunc = func; *old_profileobj = tstate->c_profileobj; tstate->c_profileobj = Py_XNewRef(arg); tstate->interp->sys_profiling_threads += delta; assert(tstate->interp->sys_profiling_threads >= 0); - return tstate->interp->sys_profiling_threads; + Py_ssize_t ret = tstate->interp->sys_profiling_threads; + + _PyEval_StartTheWorld(tstate->interp); + + return ret; } int From ba368249d72ecf7fde6d221f452c6d59a7616141 Mon Sep 17 00:00:00 2001 From: Matt Wozniski Date: Wed, 6 Aug 2025 11:56:28 -0400 Subject: [PATCH 2/2] Add news entry Signed-off-by: Matt Wozniski --- .../2025-08-06-11-56-15.gh-issue-137472.Pr_BLB.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2025-08-06-11-56-15.gh-issue-137472.Pr_BLB.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-08-06-11-56-15.gh-issue-137472.Pr_BLB.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-08-06-11-56-15.gh-issue-137472.Pr_BLB.rst new file mode 100644 index 00000000000000..acfc4dbdea12de --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-08-06-11-56-15.gh-issue-137472.Pr_BLB.rst @@ -0,0 +1,3 @@ +Fix a crash that can occur in free-threading builds when +``sys._setprofileallthreads`` or ``sys._settraceallthreads`` changes the +profile function underneath a running thread.