Skip to content

Commit

Permalink
fix #120603 by adding a check in default_read_buf
Browse files Browse the repository at this point in the history
  • Loading branch information
conradludgate committed Feb 3, 2024
1 parent bf3c6c5 commit a27e45a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,13 @@ where
F: FnOnce(&mut [u8]) -> Result<usize>,
{
let n = read(cursor.ensure_init().init_mut())?;
assert!(
n <= cursor.capacity(),
"read should not return more bytes than there is capacity for in the read buffer"
);
unsafe {
// SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to.
// SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to
// and we have checked that the read amount is not over capacity (see #120603)
cursor.advance(n);
}
Ok(())
Expand Down
16 changes: 16 additions & 0 deletions library/std/src/io/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -652,3 +652,19 @@ fn bench_take_read_buf(b: &mut test::Bencher) {
[255; 128].take(64).read_buf(buf.unfilled()).unwrap();
});
}

// Issue #120603
#[test]
#[should_panic = "read should not return more bytes than there is capacity for in the read buffer"]
fn read_buf_broken_read() {
struct MalformedRead;

impl Read for MalformedRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
// broken length calculation
Ok(buf.len() + 1)
}
}

BufReader::new(MalformedRead).read(&mut [0; 4]).unwrap();
}

0 comments on commit a27e45a

Please sign in to comment.