-
Notifications
You must be signed in to change notification settings - Fork 901
add ModuleState, core lifecycle callbacks for #[pymodule]s
#5600
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
Open
bazaah
wants to merge
13
commits into
PyO3:main
Choose a base branch
from
bazaah:feat/module-state-core
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,173
−2
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
36a2493
src/impl_: add pymodule_state for core ModuleState
bazaah 164b603
src/impl_: prepare ModuleDef for per-module state init
bazaah 163b2fb
src/impl_: add test module_state_init
bazaah 24f4868
pyo3-macros-backend: add Py_mod_exec slot for initializing ModuleState
bazaah ce5ea35
internal/typemap: add TypeMap implementation
bazaah d2e6193
src/impl_: switch to real StateMap implementation
bazaah e8cbf20
src/impl_: add getters for ModuleState->StateMap, from_bound construc…
bazaah 00dd9a3
src/types: add module state methods to PyModuleMethods
bazaah 2e6a026
src/impl_: update test to use PyModuleMethods, assert on dummy UserState
bazaah 097a060
src/impl_: inline size_of<ModuleState>
bazaah 195bd34
src/impl_: make ModuleState::drop_impl unsafe, document usage
bazaah a42992d
src/impl_: use trampoline in pyo3_module_state_init
bazaah 9a12a8e
newsfragments: add PR description
bazaah 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
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 |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| added per-module ModuleState, init + free lifecycle hooks and getters / setters in PyModuleMethods |
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 |
|---|---|---|
|
|
@@ -28,3 +28,5 @@ pub mod pymodule; | |
| pub mod trampoline; | ||
| pub mod unindent; | ||
| pub mod wrap; | ||
|
|
||
| pub(crate) mod pymodule_state; | ||
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 |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| use std::ptr::NonNull; | ||
|
|
||
| use crate::internal::typemap::{CloneAny, TypeMap}; | ||
| use crate::types::PyModule; | ||
| use crate::{ffi, Bound}; | ||
|
|
||
| /// The internal typemap for [`ModuleState`] | ||
| pub type StateMap = TypeMap<dyn CloneAny + Send>; | ||
|
|
||
| /// A marker trait for indicating what type level guarantees (and requirements) | ||
| /// are made for PyO3 `PyModule` state types. | ||
| /// | ||
| /// In general, a type *must be* | ||
| /// | ||
| /// 1. Fully owned (`'static`) | ||
| /// 2. Cloneable (`Clone`) | ||
| /// 3. Sendable (`Send`) | ||
| /// | ||
| /// To qualify as `PyModule` state. | ||
| /// | ||
| /// This type is automatically implemented for all types that qualify, so no | ||
| /// further action is required. | ||
| pub trait ModuleStateType: Clone + Send {} | ||
| impl<T: Clone + Send> ModuleStateType for T {} | ||
|
|
||
| /// Represents a Python module's state. | ||
| /// | ||
| /// More precisely, this `struct` resides on the per-module memory area | ||
| /// allocated during the module's creation. | ||
| #[repr(C)] | ||
| #[derive(Debug)] | ||
| pub struct ModuleState { | ||
| inner: Option<NonNull<StateCapsule>>, | ||
| } | ||
|
|
||
| impl ModuleState { | ||
| /// Create a new, empty [`ModuleState`] | ||
| pub fn new() -> Self { | ||
| let boxed = Box::new(StateCapsule::new()); | ||
|
|
||
| Self { | ||
| inner: NonNull::new(Box::into_raw(boxed)), | ||
| } | ||
| } | ||
|
|
||
| pub fn state_map_ref(&self) -> &StateMap { | ||
| &self.inner_ref().sm | ||
| } | ||
|
|
||
| pub fn state_map_mut(&mut self) -> &mut StateMap { | ||
| &mut self.inner_mut().sm | ||
| } | ||
|
|
||
| fn inner_ref(&self) -> &StateCapsule { | ||
| self.inner | ||
| .as_ref() | ||
| .map(|ptr| unsafe { ptr.as_ref() }) | ||
| .expect("BUG: ModuleState.inner should always be Some, except when dropping") | ||
| } | ||
|
|
||
| fn inner_mut(&mut self) -> &mut StateCapsule { | ||
| self.inner | ||
| .as_mut() | ||
| .map(|ptr| unsafe { ptr.as_mut() }) | ||
| .expect("BUG: ModuleState.inner should always be Some, except when dropping") | ||
| } | ||
|
|
||
| /// This is the actual [`Drop::drop`] implementation, split out | ||
| /// so we can run it on the state ptr returned from [`Self::pymodule_get_state`] | ||
| /// | ||
| /// While this function does not take a owned `self`, the calling ModuleState | ||
| /// should not be accessed again | ||
| /// | ||
| /// Calling this function multiple times on a single ModuleState is a noop, | ||
| /// beyond the first | ||
| unsafe fn drop_impl(&mut self) { | ||
| if let Some(ptr) = self.inner.take().map(|state| state.as_ptr()) { | ||
| // SAFETY: This ptr is allocated via Box::new in Self::new, and is | ||
| // non null | ||
| unsafe { drop(Box::from_raw(ptr)) } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ModuleState { | ||
| /// Fetch the [`ModuleState`] from a bound PyModule, inheriting it's lifetime | ||
| /// | ||
| /// ## Panics | ||
| /// | ||
| /// This function can panic if called on a PyModule that has not yet been | ||
| /// initialized | ||
| pub(crate) fn from_bound<'a>(this: &'a Bound<'_, PyModule>) -> &'a Self { | ||
| unsafe { | ||
| Self::pymodule_get_state(this.as_ptr()) | ||
| .map(|ptr| ptr.as_ref()) | ||
| .expect("pyo3 PyModules should always have per-module state") | ||
| } | ||
| } | ||
|
|
||
| /// Fetch the [`ModuleState`] mutably from a bound PyModule, inheriting it's | ||
| /// lifetime | ||
| /// | ||
| /// ## Panics | ||
| /// | ||
| /// This function can panic if called on a PyModule that has not yet been | ||
| /// initialized | ||
| pub(crate) fn from_bound_mut<'a>(this: &'a mut Bound<'_, PyModule>) -> &'a mut Self { | ||
| unsafe { | ||
| Self::pymodule_get_state(this.as_ptr()) | ||
| .map(|mut ptr| ptr.as_mut()) | ||
| .expect("pyo3 PyModules should always have per-module state") | ||
| } | ||
| } | ||
|
|
||
| /// Associated low level function for retrieving a pyo3 `pymodule`'s state | ||
| /// | ||
| /// If this function returns None, it means the underlying C PyModule does | ||
| /// not have module state. | ||
| /// | ||
| /// This function should only be called on a PyModule that is already | ||
| /// initialized via PyModule_New (or Py_mod_create) | ||
| pub(crate) unsafe fn pymodule_get_state(module: *mut ffi::PyObject) -> Option<NonNull<Self>> { | ||
| unsafe { | ||
| let state: *mut ModuleState = ffi::PyModule_GetState(module).cast(); | ||
|
|
||
| match state.is_null() { | ||
| true => None, | ||
| false => Some(NonNull::new_unchecked(state)), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Associated low level function for freeing our `pymodule`'s state | ||
| /// via a ModuleDef's m_free C callback | ||
| pub(crate) unsafe fn pymodule_free_state(module: *mut ffi::PyObject) { | ||
| unsafe { | ||
| if let Some(state) = Self::pymodule_get_state(module) { | ||
| // SAFETY: this callback is called when python is freeing the | ||
| // associated PyModule, so we should never be accessed again | ||
| (*state.as_ptr()).drop_impl() | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for ModuleState { | ||
| fn drop(&mut self) { | ||
| // SAFETY: we're being dropped, so we'll never be accessed again | ||
| unsafe { self.drop_impl() }; | ||
| } | ||
| } | ||
|
|
||
| impl Default for ModuleState { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| /// Inner layout of [`ModuleState`]. | ||
| #[derive(Debug, Clone)] | ||
| struct StateCapsule { | ||
| sm: StateMap, | ||
| } | ||
|
|
||
| impl StateCapsule { | ||
| fn new() -> Self { | ||
| Self { | ||
| sm: StateMap::new(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Default for StateCapsule { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn type_assertions() { | ||
| fn is_send<T: Send>(_t: &T) {} | ||
| fn is_clone<T: Clone>(_t: &T) {} | ||
|
|
||
| let this = StateCapsule::new(); | ||
| is_send(&this); | ||
| is_clone(&this); | ||
| } | ||
| } | ||
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 |
|---|---|---|
|
|
@@ -2,3 +2,4 @@ | |
|
|
||
| pub(crate) mod get_slot; | ||
| pub(crate) mod state; | ||
| pub(crate) mod typemap; | ||
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.
Rather than
Option<NonNull<_>>probably can useManuallyDrophere.The invariant "should not be accessed again" makes this sound like
unsafe fnis appropriate here.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.
To be clear, this is a logic error rather than a safety one -- dropping the state without going through the
m_freecallback to drop the owning module can't result in memory safety issues, but will make our (and consumer) functions that expect a state to exist when it doesn't do the wrong thing. I'm happy to make it unsafe though it really shouldn't ever be called outside exactly the two cases in the code (Drop::drop&m_freecallbacks)