Skip to content
Closed
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/5253.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fixed a leaked borrow, when converting a mutable sub class into a frozen base class using `PyRef::into_super`
36 changes: 36 additions & 0 deletions src/pycell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,15 @@ where
/// ```
pub fn into_super(self) -> PyRef<'p, U> {
let py = self.py();
if <U::Frozen as crate::pyclass::boolean_struct::private::Boolean>::VALUE {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking the constant value is a neat solution.

Crazy question though, what if U is itself a child of another type V which is not frozen?

Then I think the borrow flag is owned by V and it would be incorrect to release here 🙈

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right... And If we have something like

Base (frozen) -> S1(mut) -> S2(frozen) -> S3(mut)

The counter is owned by S1 I think, so S3 -> S2 should keep it, while S1 -> Base should release it 😭

I feel like this needs to be solved in the borrow checker itself and cant be worked around here... 😞

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I've had an insight here - see #5281

// Frozen classes to not participate in borrow checking. We need to
// release the borrow here, because the BASE does not need it and so
// will also not release it, causing it to be leaked otherwise.
self.inner
.get_class_object()
.borrow_checker()
.release_borrow()
};
PyRef {
inner: unsafe {
ManuallyDrop::new(self)
Expand Down Expand Up @@ -813,4 +822,31 @@ mod tests {
crate::py_run!(py, obj, "assert obj.get_values() == (20, 30, 40)");
});
}

#[test]
fn test_into_frozen_super_released_borrow() {
#[crate::pyclass]
#[pyo3(crate = "crate", subclass, frozen)]
struct BaseClass {}

#[crate::pyclass]
#[pyo3(crate = "crate", extends=BaseClass, subclass)]
struct SubClass {}

#[crate::pymethods]
#[pyo3(crate = "crate")]
impl SubClass {
#[new]
fn new(py: Python<'_>) -> Bound<'_, SubClass> {
let init = crate::PyClassInitializer::from(BaseClass {}).add_subclass(SubClass {});
Bound::new(py, init).expect("allocation error")
}
}

Python::attach(|py| {
let obj = SubClass::new(py);
drop(obj.borrow().into_super());
assert!(obj.try_borrow_mut().is_ok());
})
}
}
Loading