diff --git a/newsfragments/6578.fixed.md b/newsfragments/6578.fixed.md new file mode 100644 index 00000000000..6793c569391 --- /dev/null +++ b/newsfragments/6578.fixed.md @@ -0,0 +1 @@ +Fix crash when calling `Python::attach` during interpreter finalization on Python 3.13 and newer. diff --git a/src/internal/state.rs b/src/internal/state.rs index e94bd69b87e..570b012dae3 100644 --- a/src/internal/state.rs +++ b/src/internal/state.rs @@ -99,14 +99,14 @@ impl AttachGuard { } // SAFETY: always safe to call this - if unsafe { ffi::Py_IsInitialized() } == 0 { - return Err(AttachError::NotInitialized); - } + let is_initialized = unsafe { ffi::Py_IsInitialized() } != 0; // Py_IsInitialized() can return 1 while Py_InitializeEx is still // running (e.g. importing site.py). Block until any in-progress PyO3 // initialization has fully completed. - crate::interpreter_lifecycle::wait_for_initialization(); + if is_initialized { + crate::interpreter_lifecycle::wait_for_initialization(); + } // Calling `PyGILState_Ensure` while finalizing may crash CPython in unpredictable // ways, we'll make a best effort attempt here to avoid that. (There's a time of @@ -115,10 +115,13 @@ impl AttachGuard { // SAFETY: always safe to call this #[cfg(Py_3_13)] if unsafe { ffi::Py_IsFinalizing() } != 0 { - // If the interpreter is not initialized, we cannot attach. return Err(AttachError::Finalizing); } + if !is_initialized { + return Err(AttachError::NotInitialized); + } + // SAFETY: We have done everything reasonable to ensure we're in a safe state to // attach to the Python interpreter. Ok(unsafe { Self::do_attach_unchecked() }) diff --git a/tests/test_attach_during_finalization.rs b/tests/test_attach_during_finalization.rs new file mode 100644 index 00000000000..f18286d0af4 --- /dev/null +++ b/tests/test_attach_during_finalization.rs @@ -0,0 +1,47 @@ +#![cfg(all(Py_3_13, not(any(PyPy, GraalPy))))] +#![cfg(not(target_arch = "wasm32"))] + +use pyo3::{Python, ffi}; +use std::sync::atomic::{AtomicBool, Ordering}; + +static CHECK_PASSED: AtomicBool = AtomicBool::new(false); + +extern "C" fn check_attach_during_finalization() { + let result = std::panic::catch_unwind(|| { + // SAFETY: both functions are always safe to call. + unsafe { + assert_eq!(ffi::Py_IsInitialized(), 0); + assert_ne!(ffi::Py_IsFinalizing(), 0); + } + assert!(Python::try_attach(|_| panic!("unexpected attachment")).is_none()); + let panic = std::panic::catch_unwind(|| Python::attach(|_| {})).unwrap_err(); + assert_eq!( + panic.downcast_ref::<&str>().copied(), + Some("Cannot attach to the Python interpreter while it is finalizing.") + ); + }); + CHECK_PASSED.store(result.is_ok(), Ordering::Relaxed); +} + +#[test] +fn test_attach_during_finalization() { + Python::initialize(); + Python::attach(|_| { + assert_eq!( + // SAFETY: the callback matches Py_AtExit's C signature and catches panics + // before returning to CPython. + unsafe { ffi::Py_AtExit(Some(check_attach_during_finalization)) }, + 0 + ); + }); + + // SAFETY: Python is initialized + unsafe { + ffi::PyGILState_Ensure(); + } + // SAFETY: on the thread that initialized Python, with the main interpreter active + unsafe { + assert_eq!(ffi::Py_FinalizeEx(), 0); + } + assert!(CHECK_PASSED.load(Ordering::Relaxed)); +}