-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add minimal capi lifecycle support #7648
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ff5c178
Add minimal capi lifecycle support
bschoenmaeckers 131bb0e
Mark refcount methods as unsafe
bschoenmaeckers 14f3d51
Fix clippy warnings
bschoenmaeckers d1984b1
Force enable `threading` on `stdlib`
bschoenmaeckers 20e75be
Fix more clippy warnings
bschoenmaeckers e6cfbb1
Add capi support to `rustpython` executable
bschoenmaeckers e276364
Use `VM_CURRENT` when already active
bschoenmaeckers 9206893
Test that we do not create second vm when calling `PyGILState_Ensure`
bschoenmaeckers 4e88888
Fix warnings
bschoenmaeckers 3e65cec
Unify C API thread VM tracking
youknowone 0441648
Add `PYGILSTATE` to dictionary
bschoenmaeckers File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -161,6 +161,7 @@ Pyfunc | |
| pylifecycle | ||
| pymain | ||
| pyrepl | ||
| pystate | ||
| PYTHONTRACEMALLOC | ||
| PYTHONUTF8 | ||
| pythonw | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -189,6 +189,7 @@ pycodecs | |
| pycs | ||
| pydatetime | ||
| pyexpat | ||
| PYGILSTATE | ||
| pyio | ||
| pymain | ||
| PYTHONAPI | ||
|
|
||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,29 @@ | ||
| fn main() { | ||
| if std::env::var("CARGO_CFG_TARGET_OS").unwrap() == "windows" { | ||
| println!("cargo:rerun-if-changed=logo.ico"); | ||
| let mut res = winresource::WindowsResource::new(); | ||
| if std::path::Path::new("logo.ico").exists() { | ||
| res.set_icon("logo.ico"); | ||
| } else { | ||
| println!("cargo:warning=logo.ico not found, skipping icon embedding"); | ||
| return; | ||
| let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap(); | ||
| let capi_enabled = std::env::var_os("CARGO_FEATURE_CAPI").is_some(); | ||
|
|
||
| match target.as_str() { | ||
| "linux" if capi_enabled => { | ||
| println!("cargo:rustc-link-arg-bin=rustpython=-Wl,--export-dynamic"); | ||
| } | ||
| res.compile() | ||
| .map_err(|e| { | ||
| println!("cargo:warning=Failed to compile Windows resources: {e}"); | ||
| }) | ||
| .ok(); | ||
| "macos" if capi_enabled => { | ||
| println!("cargo:rustc-link-arg-bin=rustpython=-Wl,-export_dynamic"); | ||
| } | ||
| "windows" => { | ||
| println!("cargo:rerun-if-changed=logo.ico"); | ||
| let mut res = winresource::WindowsResource::new(); | ||
| if std::path::Path::new("logo.ico").exists() { | ||
| res.set_icon("logo.ico"); | ||
| } else { | ||
| println!("cargo:warning=logo.ico not found, skipping icon embedding"); | ||
| return; | ||
| } | ||
| res.compile() | ||
| .map_err(|e| { | ||
| println!("cargo:warning=Failed to compile Windows resources: {e}"); | ||
| }) | ||
| .ok(); | ||
| } | ||
| _ => {} | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| [env] | ||
| PYO3_CONFIG_FILE = { value = "pyo3-rustpython.config", relative = true } | ||
| PYO3_NO_PYTHON = { value = "1" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| [package] | ||
| name = "rustpython-capi" | ||
| description = "Minimal CPython C-API compatibility exports for RustPython" | ||
| version.workspace = true | ||
| authors.workspace = true | ||
| edition.workspace = true | ||
| rust-version.workspace = true | ||
| repository.workspace = true | ||
| license.workspace = true | ||
|
|
||
| [lib] | ||
| crate-type = ["cdylib", "rlib"] | ||
|
|
||
| [dependencies] | ||
| rustpython-vm = { workspace = true, features = ["threading"] } | ||
| rustpython-stdlib = {workspace = true, features = ["threading"] } | ||
|
|
||
| [dev-dependencies] | ||
| pyo3 = { version = "0.28", features = ["auto-initialize", "abi3"] } | ||
|
|
||
| [lints] | ||
| workspace = true | ||
|
|
||
| [package.metadata.cargo-shear] | ||
| # Not a direct dependency (yet), but we need to enable threading support in the stdlib. | ||
| ignored = ["rustpython-stdlib"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| implementation=CPython | ||
| version=3.14 | ||
| shared=true | ||
| abi3=true | ||
| suppress_build_script_link_lines=true | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| #![allow(clippy::missing_safety_doc)] | ||
|
|
||
| use crate::pylifecycle::MAIN_INTERP; | ||
| use rustpython_vm::Interpreter; | ||
| pub use rustpython_vm::PyObject; | ||
| use std::sync::MutexGuard; | ||
|
|
||
| extern crate alloc; | ||
|
|
||
| pub mod pylifecycle; | ||
| pub mod pystate; | ||
| pub mod refcount; | ||
|
|
||
| /// Get main interpreter of this process. Will be None if it has not been initialized yet. | ||
| pub fn get_main_interpreter() -> MutexGuard<'static, Option<Interpreter>> { | ||
| MAIN_INTERP | ||
| .lock() | ||
| .expect("Failed to lock interpreter mutex") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| use crate::get_main_interpreter; | ||
| use crate::pystate::ensure_thread_has_vm_attached; | ||
| use core::ffi::c_int; | ||
| use rustpython_vm::Interpreter; | ||
| use rustpython_vm::vm::thread::ThreadedVirtualMachine; | ||
| use std::sync::Mutex; | ||
|
|
||
| pub(crate) static MAIN_INTERP: Mutex<Option<Interpreter>> = Mutex::new(None); | ||
|
|
||
| /// Request a thread local vm from the main interpreter | ||
| pub(crate) fn request_vm_from_interpreter() -> ThreadedVirtualMachine { | ||
| get_main_interpreter() | ||
| .as_ref() | ||
| .expect("Interpreter not initialized") | ||
| .enter(|vm| vm.new_thread()) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_IsInitialized() -> c_int { | ||
| get_main_interpreter().is_some() as c_int | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_Initialize() { | ||
| Py_InitializeEx(0); | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_InitializeEx(_initsigs: c_int) { | ||
| let mut interp = get_main_interpreter(); | ||
| if interp.is_none() { | ||
| *interp = Interpreter::with_init(Default::default(), |_vm| {}).into(); | ||
| drop(interp); | ||
| ensure_thread_has_vm_attached(); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_Finalize() { | ||
| let _ = Py_FinalizeEx(); | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_FinalizeEx() -> c_int { | ||
| 0 | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn Py_IsFinalizing() -> c_int { | ||
| 0 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| use crate::pylifecycle::request_vm_from_interpreter; | ||
| use core::ffi::c_int; | ||
| use core::ptr; | ||
| use rustpython_vm::vm::thread::{ | ||
| CurrentVmAttachState, attach_current_thread, release_current_thread, | ||
| }; | ||
|
|
||
| #[allow(non_camel_case_types)] | ||
| type PyGILState_STATE = c_int; | ||
| const PYGILSTATE_LOCKED: PyGILState_STATE = 0; | ||
| const PYGILSTATE_UNLOCKED: PyGILState_STATE = 1; | ||
|
|
||
| #[repr(C)] | ||
| pub struct PyThreadState { | ||
| _interp: *mut core::ffi::c_void, | ||
| } | ||
|
|
||
| /// Make sure this thread has a running vm attached. This only creates a new vm if we don't already | ||
| /// have one. So this will only create a new vm when we are in a new thread created outside RustPython. | ||
| pub(crate) fn ensure_thread_has_vm_attached() -> CurrentVmAttachState { | ||
| attach_current_thread(request_vm_from_interpreter) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn PyGILState_Ensure() -> PyGILState_STATE { | ||
| match ensure_thread_has_vm_attached() { | ||
| CurrentVmAttachState::AlreadyAttached => PYGILSTATE_LOCKED, | ||
| CurrentVmAttachState::Attached => PYGILSTATE_UNLOCKED, | ||
| } | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn PyGILState_Release(state: PyGILState_STATE) { | ||
| if state == PYGILSTATE_UNLOCKED { | ||
| release_current_thread(CurrentVmAttachState::Attached); | ||
| } | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub extern "C" fn PyEval_SaveThread() -> *mut PyThreadState { | ||
| ptr::null_mut() | ||
| } | ||
|
bschoenmaeckers marked this conversation as resolved.
|
||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use crate::get_main_interpreter; | ||
| use crate::pystate::{PyGILState_Ensure, PyGILState_Release}; | ||
| use pyo3::prelude::*; | ||
| use rustpython_vm::vm::thread::{current_vm_is_set, with_current_vm}; | ||
|
|
||
| #[test] | ||
| fn test_new_thread() { | ||
| Python::attach(|_py| { | ||
| with_current_vm(|_vm| { | ||
| assert!( | ||
| current_vm_is_set(), | ||
| "This thread did not have a vm attached" | ||
| ) | ||
| }); | ||
|
|
||
| std::thread::spawn(move || { | ||
| Python::attach(|_py| { | ||
| with_current_vm(|_vm| { | ||
| assert!( | ||
| current_vm_is_set(), | ||
| "This thread did not have a vm attached" | ||
| ) | ||
| }); | ||
| }); | ||
| }) | ||
| .join() | ||
| .unwrap(); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_current_vm_main_thread() { | ||
| Python::initialize(); | ||
|
|
||
| // let RustPython create a vm for this thread. | ||
| let vm = get_main_interpreter() | ||
| .as_ref() | ||
| .unwrap() | ||
| .enter(|vm| vm.new_thread()); | ||
|
|
||
| // Attach the vm using RustPython | ||
| vm.run(|_vm| { | ||
| assert!(current_vm_is_set(), "This thread should have a vm attached"); | ||
|
|
||
| Python::attach(|_py| { | ||
| with_current_vm(|_vm| { | ||
| assert!(current_vm_is_set()); | ||
| }) | ||
| }) | ||
| }); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_gilstate_release_detaches_external_thread() { | ||
| Python::initialize(); | ||
|
|
||
| std::thread::spawn(|| { | ||
| let state = PyGILState_Ensure(); | ||
| assert!(current_vm_is_set()); | ||
| PyGILState_Release(state); | ||
| assert!(!current_vm_is_set()); | ||
| }) | ||
| .join() | ||
| .unwrap(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| use crate::PyObject; | ||
| use core::ptr::NonNull; | ||
| use rustpython_vm::PyObjectRef; | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn _Py_DecRef(op: *mut PyObject) { | ||
| // By dropping PyObjectRef, we will decrement the reference count. | ||
| unsafe { drop(PyObjectRef::from_raw(NonNull::new_unchecked(op))) }; | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn _Py_IncRef(op: *mut PyObject) { | ||
| // Don't drop the owned value, as we just want to increment the refcount. | ||
| core::mem::forget(unsafe { (*op).to_owned() }); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there any freethreading marker? we only target free-treading, which represents
abi3tUh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
abi3tsupport is not yet implemented in PyO3. But for now I make sure not to use incompatible api's. For progress see PyO3/pyo3#5786