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

[Merged by Bors] - Fix unsoundness in EntityMut::world_scope #7387

Closed
wants to merge 17 commits into from
Closed
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix unsoundness
  • Loading branch information
JoJoJet committed Jan 27, 2023
commit bb59e54f0ad14d708998ff877b6a1cf319ff64e2
16 changes: 15 additions & 1 deletion crates/bevy_ecs/src/world/entity_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,8 +541,22 @@ impl<'w> EntityMut<'w> {

/// Gives mutable access to this `EntityMut`'s [`World`] in a temporary scope.
pub fn world_scope(&mut self, f: impl FnOnce(&mut World)) {
// Erase the lifetime of self, so we can get around the borrow checker.
let this_ptr = self as *mut Self;
JoJoJet marked this conversation as resolved.
Show resolved Hide resolved

// Update the stored `EntityLocation` for this instance.
// This will get called at the end of this scope, even if the closure `f` unwinds.
let _on_drop = bevy_utils::OnDrop::new(|| {
// SAFETY:
// - This will only be invoked at the end of the outer scope, at which point
// `self` will no longer be borrowed, which ensures the references don't alias.
// - The pointer must otherwise be safe to dereference, since it was obtained
// from a mutable reference.
let this = unsafe { &mut *this_ptr };
this.update_location();
});

f(self.world);
self.update_location();
}

/// Updates the internal entity location to match the current location in the internal
Expand Down