Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/6578.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix crash when calling `Python::attach` during interpreter finalization on Python 3.13 and newer.
13 changes: 8 additions & 5 deletions src/internal/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() })
Expand Down
47 changes: 47 additions & 0 deletions tests/test_attach_during_finalization.rs
Original file line number Diff line number Diff line change
@@ -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));
}
Loading