Skip to content

Commit e083e9a

Browse files
add test for when read count exceeds total size
We cannot mark the returned usize as must use unfortunately. This is what triggered the bug in linux-loader: rust-vmm/linux-loader#125. The least we can do is to validate that when there are more bytes requested than what the reader has available, we do return the correct number of the read. Unfortunately, when this result is not used it can lead to bugs. Signed-off-by: Andreea Florescu <[email protected]>
1 parent cb3825f commit e083e9a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/volatile_memory.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1375,6 +1375,8 @@ mod tests {
13751375
use super::*;
13761376

13771377
use std::fs::File;
1378+
use std::io::Cursor;
1379+
use std::mem;
13781380
use std::mem::size_of_val;
13791381
use std::path::Path;
13801382
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -1905,6 +1907,30 @@ mod tests {
19051907
assert_eq!(buf, sample_buf);
19061908
}
19071909

1910+
#[test]
1911+
fn test_read_from_exceeds_size() {
1912+
#[derive(Debug, Default, Copy, Clone)]
1913+
struct BytesToRead {
1914+
_val1: u128, // 16 bytes
1915+
_val2: u128, // 16 bytes
1916+
}
1917+
unsafe impl ByteValued for BytesToRead {}
1918+
let cursor_size = 20;
1919+
let mut image = Cursor::new(vec![1u8; cursor_size]);
1920+
1921+
// Trying to read more bytes than we have available in the cursor should
1922+
// make the read_from function return maximum cursor size (i.e. 20).
1923+
let mut bytes_to_read = BytesToRead::default();
1924+
let size_of_bytes = mem::size_of_val(&bytes_to_read);
1925+
assert_eq!(
1926+
bytes_to_read
1927+
.as_bytes()
1928+
.read_from(0, &mut image, size_of_bytes)
1929+
.unwrap(),
1930+
cursor_size
1931+
);
1932+
}
1933+
19081934
#[test]
19091935
fn ref_array_from_slice() {
19101936
let mut a = [2, 4, 6, 8, 10];

0 commit comments

Comments
 (0)