Skip to content

Commit e58fffb

Browse files
SkiFire13james7132
authored andcommitted
Improve soundness of CommandQueue (bevyengine#4863)
# Objective This PR aims to improve the soundness of `CommandQueue`. In particular it aims to: - make it sound to store commands that contain padding or uninitialized bytes; - avoid uses of commands after moving them in the queue's buffer (`std::mem::forget` is technically a use of its argument); - remove useless checks: `self.bytes.as_mut_ptr().is_null()` is always `false` because even `Vec`s that haven't allocated use a dangling pointer. Moreover the same pointer was used to write the command, so it ought to be valid for reads if it was for writes. ## Solution - To soundly store padding or uninitialized bytes `CommandQueue` was changed to contain a `Vec<MaybeUninit<u8>>` instead of `Vec<u8>`; - To avoid uses of the command through `std::mem::forget`, `ManuallyDrop` was used. ## Other observations While writing this PR I noticed that `CommandQueue` doesn't seem to drop the commands that weren't applied. While this is a pretty niche case (you would have to be manually using `CommandQueue`/`std::mem::swap`ping one), I wonder if it should be documented anyway.
1 parent 6865179 commit e58fffb

File tree

1 file changed

+33
-28
lines changed

1 file changed

+33
-28
lines changed

crates/bevy_ecs/src/system/commands/command_queue.rs

+33-28
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
1+
use std::mem::{ManuallyDrop, MaybeUninit};
2+
13
use super::Command;
24
use crate::world::World;
35

46
struct CommandMeta {
57
offset: usize,
6-
func: unsafe fn(value: *mut u8, world: &mut World),
8+
func: unsafe fn(value: *mut MaybeUninit<u8>, world: &mut World),
79
}
810

911
/// A queue of [`Command`]s
1012
//
11-
// NOTE: [`CommandQueue`] is implemented via a `Vec<u8>` over a `Vec<Box<dyn Command>>`
13+
// NOTE: [`CommandQueue`] is implemented via a `Vec<MaybeUninit<u8>>` over a `Vec<Box<dyn Command>>`
1214
// as an optimization. Since commands are used frequently in systems as a way to spawn
1315
// entities/components/resources, and it's not currently possible to parallelize these
1416
// due to mutable [`World`] access, maximizing performance for [`CommandQueue`] is
1517
// preferred to simplicity of implementation.
1618
#[derive(Default)]
1719
pub struct CommandQueue {
18-
bytes: Vec<u8>,
20+
bytes: Vec<MaybeUninit<u8>>,
1921
metas: Vec<CommandMeta>,
2022
}
2123

@@ -35,7 +37,7 @@ impl CommandQueue {
3537
/// SAFE: This function is only every called when the `command` bytes is the associated
3638
/// [`Commands`] `T` type. Also this only reads the data via `read_unaligned` so unaligned
3739
/// accesses are safe.
38-
unsafe fn write_command<T: Command>(command: *mut u8, world: &mut World) {
40+
unsafe fn write_command<T: Command>(command: *mut MaybeUninit<u8>, world: &mut World) {
3941
let command = command.cast::<T>().read_unaligned();
4042
command.write(world);
4143
}
@@ -48,25 +50,30 @@ impl CommandQueue {
4850
func: write_command::<C>,
4951
});
5052

53+
// Use `ManuallyDrop` to forget `command` right away, avoiding
54+
// any use of it after the `ptr::copy_nonoverlapping`.
55+
let command = ManuallyDrop::new(command);
56+
5157
if size > 0 {
5258
self.bytes.reserve(size);
5359

5460
// SAFE: The internal `bytes` vector has enough storage for the
55-
// command (see the call the `reserve` above), and the vector has
56-
// its length set appropriately.
57-
// Also `command` is forgotten at the end of this function so that
58-
// when `apply` is called later, a double `drop` does not occur.
61+
// command (see the call the `reserve` above), the vector has
62+
// its length set appropriately and can contain any kind of bytes.
63+
// In case we're writing a ZST and the `Vec` hasn't allocated yet
64+
// then `as_mut_ptr` will be a dangling (non null) pointer, and
65+
// thus valid for ZST writes.
66+
// Also `command` is forgotten so that when `apply` is called
67+
// later, a double `drop` does not occur.
5968
unsafe {
6069
std::ptr::copy_nonoverlapping(
61-
&command as *const C as *const u8,
70+
&*command as *const C as *const MaybeUninit<u8>,
6271
self.bytes.as_mut_ptr().add(old_len),
6372
size,
6473
);
6574
self.bytes.set_len(old_len + size);
6675
}
6776
}
68-
69-
std::mem::forget(command);
7077
}
7178

7279
/// Execute the queued [`Command`]s in the world.
@@ -81,27 +88,12 @@ impl CommandQueue {
8188
// unnecessary allocations.
8289
unsafe { self.bytes.set_len(0) };
8390

84-
let byte_ptr = if self.bytes.as_mut_ptr().is_null() {
85-
// SAFE: If the vector's buffer pointer is `null` this mean nothing has been pushed to its bytes.
86-
// This means either that:
87-
//
88-
// 1) There are no commands so this pointer will never be read/written from/to.
89-
//
90-
// 2) There are only zero-sized commands pushed.
91-
// According to https://doc.rust-lang.org/std/ptr/index.html
92-
// "The canonical way to obtain a pointer that is valid for zero-sized accesses is NonNull::dangling"
93-
// therefore it is safe to call `read_unaligned` on a pointer produced from `NonNull::dangling` for
94-
// zero-sized commands.
95-
unsafe { std::ptr::NonNull::dangling().as_mut() }
96-
} else {
97-
self.bytes.as_mut_ptr()
98-
};
99-
10091
for meta in self.metas.drain(..) {
10192
// SAFE: The implementation of `write_command` is safe for the according Command type.
93+
// It's ok to read from `bytes.as_mut_ptr()` because we just wrote to it in `push`.
10294
// The bytes are safely cast to their original type, safely read, and then dropped.
10395
unsafe {
104-
(meta.func)(byte_ptr.add(meta.offset), world);
96+
(meta.func)(self.bytes.as_mut_ptr().add(meta.offset), world);
10597
}
10698
}
10799
}
@@ -234,4 +226,17 @@ mod test {
234226
fn test_command_is_send() {
235227
assert_is_send(SpawnCommand);
236228
}
229+
230+
struct CommandWithPadding(u8, u16);
231+
impl Command for CommandWithPadding {
232+
fn write(self, _: &mut World) {}
233+
}
234+
235+
#[cfg(miri)]
236+
#[test]
237+
fn test_uninit_bytes() {
238+
let mut queue = CommandQueue::default();
239+
queue.push(CommandWithPadding(0, 0));
240+
let _ = format!("{:?}", queue.bytes);
241+
}
237242
}

0 commit comments

Comments
 (0)