bevy/crates/bevy_ecs/src
JoJoJet 209f6f8e83 Fix unsoundness in EntityMut::world_scope (#7387)
# Objective

Found while working on #7385.

The struct `EntityMut` has the safety invariant that it's cached `EntityLocation` must always accurately specify where the entity is stored. Thus, any time its location might be invalidated (such as by calling `EntityMut::world_mut` and moving archetypes), the cached location *must* be updated by calling `EntityMut::update_location`.

The method `world_scope` encapsulates this pattern in safe API by requiring world mutations to be done in a closure, after which `update_location` will automatically be called. However, this method has a soundness hole: if a panic occurs within the closure, then `update_location` will never get called. If the panic is caught in an outer scope, then the `EntityMut` will be left with an outdated location, which is undefined behavior.

An example of this can be seen in the unit test `entity_mut_world_scope_panic`, which has been added to this PR as a regression test. Without the other changes in this PR, that test will invoke undefined behavior in safe code.

## Solution

Call `EntityMut::update_location()` from within a `Drop` impl, which ensures that it will get executed even if `EntityMut::world_scope` unwinds.
2023-01-29 00:10:45 +00:00
..
entity Make EntityRef::new unsafe (#7222) 2023-01-16 22:10:51 +00:00
query Basic adaptive batching for parallel query iteration (#4777) 2023-01-20 08:47:20 +00:00
schedule Fix minor typos in code and docs (#7378) 2023-01-27 12:12:53 +00:00
schedule_v3 Fix minor typos in code and docs (#7378) 2023-01-27 12:12:53 +00:00
storage Add World::clear_resources & World::clear_all (#3212) 2023-01-17 04:20:42 +00:00
system Speed up CommandQueue by storing commands more densely (#6391) 2023-01-28 01:15:51 +00:00
world Fix unsoundness in EntityMut::world_scope (#7387) 2023-01-29 00:10:45 +00:00
archetype.rs Fix minor typos in code and docs (#7378) 2023-01-27 12:12:53 +00:00
bundle.rs Fix beta clippy lints (#7154) 2023-01-11 09:51:22 +00:00
change_detection.rs Add a method for converting MutUntyped -> Mut<T> (#7113) 2023-01-11 17:47:54 +00:00
component.rs Added resource_id and changed init_resource and init_non_send_resource to return ComponentId (#7284) 2023-01-20 19:08:04 +00:00
event.rs Rework manual event iterator so we can actually name the type (#5735) 2022-12-25 00:39:27 +00:00
lib.rs Add Ref to the prelude (#7392) 2023-01-28 09:28:47 +00:00
reflect.rs add UnsafeWorldCell abstraction (#6404) 2023-01-27 00:12:13 +00:00