Skip to content

Commit

Permalink
add test for when read count exceeds total size
Browse files Browse the repository at this point in the history
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 <fandree@amazon.com>
  • Loading branch information
andreeaflorescu committed Jan 3, 2023
1 parent cb3825f commit e083e9a
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/volatile_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1375,6 +1375,8 @@ mod tests {
use super::*;

use std::fs::File;
use std::io::Cursor;
use std::mem;
use std::mem::size_of_val;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
Expand Down Expand Up @@ -1905,6 +1907,30 @@ mod tests {
assert_eq!(buf, sample_buf);
}

#[test]
fn test_read_from_exceeds_size() {
#[derive(Debug, Default, Copy, Clone)]
struct BytesToRead {
_val1: u128, // 16 bytes
_val2: u128, // 16 bytes
}
unsafe impl ByteValued for BytesToRead {}
let cursor_size = 20;
let mut image = Cursor::new(vec![1u8; cursor_size]);

// Trying to read more bytes than we have available in the cursor should
// make the read_from function return maximum cursor size (i.e. 20).
let mut bytes_to_read = BytesToRead::default();
let size_of_bytes = mem::size_of_val(&bytes_to_read);
assert_eq!(
bytes_to_read
.as_bytes()
.read_from(0, &mut image, size_of_bytes)
.unwrap(),
cursor_size
);
}

#[test]
fn ref_array_from_slice() {
let mut a = [2, 4, 6, 8, 10];
Expand Down

0 comments on commit e083e9a

Please sign in to comment.