From a27e45a71bd9743cebfbac74ccd3d0f50cc1a190 Mon Sep 17 00:00:00 2001 From: Conrad Ludgate Date: Sat, 3 Feb 2024 11:30:26 +0000 Subject: [PATCH 1/2] fix #120603 by adding a check in default_read_buf --- library/std/src/io/mod.rs | 7 ++++++- library/std/src/io/tests.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 8fca66fa17c5e..d84b0766f363f 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -578,8 +578,13 @@ where F: FnOnce(&mut [u8]) -> Result, { 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(()) diff --git a/library/std/src/io/tests.rs b/library/std/src/io/tests.rs index bda5b721adc63..c0179f7f22783 100644 --- a/library/std/src/io/tests.rs +++ b/library/std/src/io/tests.rs @@ -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 { + // broken length calculation + Ok(buf.len() + 1) + } + } + + BufReader::new(MalformedRead).read(&mut [0; 4]).unwrap(); +} From 4c694db25270243597657ec73ec9912f2ddfb0cc Mon Sep 17 00:00:00 2001 From: Conrad Ludgate Date: Sat, 3 Feb 2024 11:44:13 +0000 Subject: [PATCH 2/2] add another test to make sure it still works with full reads --- library/std/src/io/tests.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/library/std/src/io/tests.rs b/library/std/src/io/tests.rs index c0179f7f22783..33e9d8efed511 100644 --- a/library/std/src/io/tests.rs +++ b/library/std/src/io/tests.rs @@ -1,6 +1,6 @@ use super::{repeat, BorrowedBuf, Cursor, SeekFrom}; use crate::cmp::{self, min}; -use crate::io::{self, IoSlice, IoSliceMut}; +use crate::io::{self, IoSlice, IoSliceMut, DEFAULT_BUF_SIZE}; use crate::io::{BufRead, BufReader, Read, Seek, Write}; use crate::mem::MaybeUninit; use crate::ops::Deref; @@ -666,5 +666,18 @@ fn read_buf_broken_read() { } } - BufReader::new(MalformedRead).read(&mut [0; 4]).unwrap(); + let _ = BufReader::new(MalformedRead).fill_buf(); +} + +#[test] +fn read_buf_full_read() { + struct FullRead; + + impl Read for FullRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + Ok(buf.len()) + } + } + + assert_eq!(BufReader::new(FullRead).fill_buf().unwrap().len(), DEFAULT_BUF_SIZE); }