wasmtime: clarify Memory::{read,write} behavior with out-of-bounds ranges

This documents that we will never do partial reads/writes, and expands our
existing tests to assert this.
This commit is contained in:
Nick Fitzgerald
2021-01-26 10:11:29 -08:00
parent 0cdc80fbf8
commit 4f3bc1d5d4
2 changed files with 12 additions and 4 deletions

View File

@@ -304,8 +304,8 @@ impl Memory {
/// ///
/// The entire buffer will be filled. /// The entire buffer will be filled.
/// ///
/// If offset + buffer length exceed the current memory capacity, /// If offset + buffer length exceed the current memory capacity, then the
/// a [`MemoryAccessError`] is returned. /// buffer is left untouched and a [`MemoryAccessError`] is returned.
pub fn read(&self, offset: usize, buffer: &mut [u8]) -> Result<(), MemoryAccessError> { pub fn read(&self, offset: usize, buffer: &mut [u8]) -> Result<(), MemoryAccessError> {
unsafe { unsafe {
let slice = self let slice = self
@@ -320,8 +320,9 @@ impl Memory {
/// Safely writes contents of a buffer to this memory at the given offset. /// Safely writes contents of a buffer to this memory at the given offset.
/// ///
/// If the offset + buffer length exceed current memory capacity, a /// If the offset + buffer length exceed current memory capacity, then none
/// [`MemoryAccessError`] is returned. /// of the buffer is written to memory and a [`MemoryAccessError`] is
/// returned.
pub fn write(&self, offset: usize, buffer: &[u8]) -> Result<(), MemoryAccessError> { pub fn write(&self, offset: usize, buffer: &[u8]) -> Result<(), MemoryAccessError> {
unsafe { unsafe {
self.data_unchecked_mut() self.data_unchecked_mut()

View File

@@ -363,11 +363,18 @@ fn read_write_memory_via_api() {
let res = mem.write(mem.data_size() - value.len() + 1, value); let res = mem.write(mem.data_size() - value.len() + 1, value);
assert!(res.is_err()); assert!(res.is_err());
assert_ne!(
unsafe { mem.data_unchecked()[mem.data_size() - value.len() + 1] },
value[0],
"no data is written",
);
// Out of bounds read. // Out of bounds read.
buffer[0] = 0x42;
let res = mem.read(mem.data_size() - buffer.len() + 1, &mut buffer); let res = mem.read(mem.data_size() - buffer.len() + 1, &mut buffer);
assert!(res.is_err()); assert!(res.is_err());
assert_eq!(buffer[0], 0x42, "no data is read");
// Read offset overflow. // Read offset overflow.
let res = mem.read(usize::MAX, &mut buffer); let res = mem.read(usize::MAX, &mut buffer);