Skip to content
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

Fix: Object::from_ref no longer forgetting to increment the strong count #5858

Merged
merged 3 commits into from
Oct 24, 2024
Merged
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
13 changes: 11 additions & 2 deletions Source/DafnyRuntime/DafnyRuntimeRust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3508,15 +3508,24 @@ impl <T: ?Sized> AsRef<T> for Object<T> {
fn increment_strong_count<T: ?Sized>(data: *const T) {
// SAFETY: This method is called only on values that were constructed from an Rc
unsafe {
Rc::increment_strong_count(data);
// Black box avoids the compiler wrongly inferring that increment strong count does nothing since the data it was applied to can be traced to be borrowed
::std::hint::black_box(Rc::increment_strong_count(data));
}
}

impl <T: ?Sized> Object<T> {
// SAFETY: This function needs to be called from a reference obtained by calling read!(o) on an object
// We never inline this function, otherwise the compiler might figure out a way to remove the increment_strong_count
#[inline(never)]
pub fn from_ref(r: &T) -> Object<T> {
let pt = r as *const T as *const UnsafeCell<T>;
crate::increment_strong_count(pt);
// SAFETY: Not guaranteed unfortunately. But looking at the sources of from_raw as of today 10/24/2024
// it will will correctly rebuilt the Rc
let rebuilt = unsafe { Rc::from_raw(pt) };
let previous_strong_count = Rc::strong_count(&rebuilt);
::std::hint::black_box(crate::increment_strong_count(pt));
let new_strong_count = Rc::strong_count(&rebuilt);
assert_eq!(new_strong_count, previous_strong_count + 1); // Will panic if not
Object(Some(rebuilt))
}
}
Expand Down