Skip to content

Commit 8e04b55

Browse files
roypatandreeaflorescu
authored andcommitted
Replace impl VolatileMemory for &mut [u8]
Due to the API exposed by the VolatileMemory trait constructing a VolatileSlice from an immutable reference, this impl allowed mutation through an immutable reference. This is because the signature of `get_slice` has its first argument desugar to `&&mut [u8]` instead of `&mut [u8]` (note the double reference). This caused undefined behavior due to a cast from immutable reference to mutable pointer. The implementation has been replaced with `From<&mut [u8]> for VolatileSlice`, which is safe. Since this impl was only used in testing code, the impact of this breaking change should be low. For the same reasons, the `VecMem` struct in volatile_memory::tests has been removed. Signed-off-by: Patrick Roy <[email protected]>
1 parent 595b5a7 commit 8e04b55

File tree

2 files changed

+120
-136
lines changed

2 files changed

+120
-136
lines changed

benches/volatile.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,22 @@
44

55
pub use criterion::{black_box, Criterion};
66
use vm_memory::volatile_memory::VolatileMemory;
7+
use vm_memory::VolatileSlice;
78

89
pub fn benchmark_for_volatile(c: &mut Criterion) {
910
let mut a = [0xa5u8; 1024];
10-
let a_ref = &mut a[..];
11-
let v_ref8 = a_ref.get_slice(0, a_ref.len()).unwrap();
12-
let v_ref16 = a_ref.get_slice(0, a_ref.len() / 2).unwrap();
11+
let vslice = VolatileSlice::from(&mut a[..]);
12+
let v_ref8 = vslice.get_slice(0, vslice.len()).unwrap();
1313
let mut d8 = [0u8; 1024];
14-
let mut d16 = [0u16; 512];
1514

1615
// Check performance for read operations.
1716
c.bench_function("VolatileSlice::copy_to_u8", |b| {
1817
b.iter(|| v_ref8.copy_to(black_box(&mut d8[..])))
1918
});
19+
20+
let v_ref16 = vslice.get_slice(0, vslice.len() / 2).unwrap();
21+
let mut d16 = [0u16; 512];
22+
2023
c.bench_function("VolatileSlice::copy_to_u16", |b| {
2124
b.iter(|| v_ref16.copy_to(black_box(&mut d16[..])))
2225
});
@@ -33,11 +36,11 @@ pub fn benchmark_for_volatile(c: &mut Criterion) {
3336

3437
fn benchmark_volatile_copy_to_volatile_slice(c: &mut Criterion) {
3538
let mut a = [0xa5u8; 10240];
36-
let a_ref = &mut a[..];
37-
let a_slice = a_ref.get_slice(0, a_ref.len()).unwrap();
39+
let vslice = VolatileSlice::from(&mut a[..]);
40+
let a_slice = vslice.get_slice(0, vslice.len()).unwrap();
3841
let mut d = [0u8; 10240];
39-
let d_ref = &mut d[..];
40-
let d_slice = d_ref.get_slice(0, d_ref.len()).unwrap();
42+
let vslice2 = VolatileSlice::from(&mut d[..]);
43+
let d_slice = vslice2.get_slice(0, vslice2.len()).unwrap();
4144

4245
c.bench_function("VolatileSlice::copy_to_volatile_slice", |b| {
4346
b.iter(|| black_box(a_slice).copy_to_volatile_slice(d_slice))

0 commit comments

Comments
 (0)