Skip to content

Commit

Permalink
Fast fix possible uninit memory access in read_from
Browse files Browse the repository at this point in the history
  • Loading branch information
agerasev committed Jan 17, 2024
1 parent 447a156 commit dc694c2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
27 changes: 26 additions & 1 deletion src/tests/read_write.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::Rb;
use crate::{storage::Static, traits::*};
use std::io;
use std::io::{self, Read};

macro_rules! assert_eq_kind {
($left:expr, $right:expr) => {
Expand Down Expand Up @@ -107,3 +107,28 @@ fn count() {
assert_eq!(cons1.pop_slice(&mut tmp), 4);
assert_eq!(tmp[0..4], [3, 4, 5, 6]);
}

#[test]
fn read_from() {
struct Reader;

impl Read for Reader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
for b in buf.iter_mut() {
// Read buffer before writing to ensure its initialized.
*b = b.wrapping_add(1);
}
buf.fill(2);
Ok(buf.len())
}
}

let mut rb = Rb::<Static<u8, 4>>::default();
let (mut prod, mut cons) = rb.split_ref();
prod.try_push(1).unwrap();
assert_eq!(cons.try_pop().unwrap(), 1);

assert_eq!(prod.read_from(&mut Reader, None).unwrap().unwrap(), 3);

assert!(cons.pop_iter().eq([2; 3]));
}
7 changes: 6 additions & 1 deletion src/traits/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,12 @@ pub trait Producer: Observer {
if count == 0 {
return None;
}
let left_init = unsafe { slice_assume_init_mut(&mut left[..count]) };

let buf = &mut left[..count];
// Initialize memory before read. It's an overhead but there's no way to read to uninit buffer in stable Rust yet.
// TODO: Use `reader.read_buf` when it stabilized (see https://github.com/rust-lang/rust/issues/78485).
buf.fill(MaybeUninit::new(0));
let left_init = unsafe { slice_assume_init_mut(buf) };

let read_count = match reader.read(left_init) {
Ok(n) => n,
Expand Down

0 comments on commit dc694c2

Please sign in to comment.