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] - prevent memory leak when dropping ParallelSystemContainer #2176

Closed
wants to merge 1 commit into from
Closed
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
16 changes: 8 additions & 8 deletions crates/bevy_ecs/src/schedule/system_container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
},
system::{ExclusiveSystem, System},
};
use std::{borrow::Cow, ptr::NonNull};
use std::{borrow::Cow, cell::UnsafeCell};

/// System metadata like its name, labels, order requirements and component access.
pub trait SystemContainer: GraphNode<BoxedSystemLabel> {
Expand Down Expand Up @@ -104,7 +104,7 @@ impl SystemContainer for ExclusiveSystemContainer {
}

pub struct ParallelSystemContainer {
system: NonNull<dyn System<In = (), Out = ()>>,
system: Box<UnsafeCell<dyn System<In = (), Out = ()>>>,
pub(crate) run_criteria_index: Option<usize>,
pub(crate) run_criteria_label: Option<BoxedRunCriteriaLabel>,
pub(crate) should_run: bool,
Expand All @@ -121,7 +121,8 @@ unsafe impl Sync for ParallelSystemContainer {}
impl ParallelSystemContainer {
pub(crate) fn from_descriptor(descriptor: ParallelSystemDescriptor) -> Self {
ParallelSystemContainer {
system: unsafe { NonNull::new_unchecked(Box::into_raw(descriptor.system)) },
// SAFE: it is fine to wrap inner value with UnsafeCell, as it is repr(transparent)
system: unsafe { Box::from_raw(Box::into_raw(descriptor.system) as *mut _) },
should_run: false,
run_criteria_index: None,
run_criteria_label: None,
Expand All @@ -138,20 +139,19 @@ impl ParallelSystemContainer {
}

pub fn system(&self) -> &dyn System<In = (), Out = ()> {
// SAFE: statically enforced shared access.
unsafe { self.system.as_ref() }
// SAFE: statically enforced shared access
unsafe { self.system.get().as_ref().unwrap() }
}

pub fn system_mut(&mut self) -> &mut dyn System<In = (), Out = ()> {
// SAFE: statically enforced exclusive access.
unsafe { self.system.as_mut() }
self.system.get_mut()
}

/// # Safety
/// Ensure no other borrows exist along with this one.
#[allow(clippy::mut_from_ref)]
pub unsafe fn system_mut_unsafe(&self) -> &mut dyn System<In = (), Out = ()> {
&mut *self.system.as_ptr()
self.system.get().as_mut().unwrap()
}

pub fn should_run(&self) -> bool {
Expand Down