Make WasmRef/WasmSlice access uniform

This commit is contained in:
Syrus Akbary
2023-03-06 20:42:14 -08:00
parent 07eb2f6ad7
commit 0a31d66c95
6 changed files with 462 additions and 1254 deletions

View File

@@ -167,30 +167,6 @@ where
}
}
impl<'a, T> WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,
{
/// Reads the address pointed to by this `WasmPtr` in a memory.
#[inline]
#[allow(clippy::clone_on_copy)]
pub fn read(&self) -> T
where
T: Clone,
{
self.as_ref().clone()
}
/// Writes to the address pointed to by this `WasmPtr` in a memory.
#[inline]
pub fn write(&mut self, val: T) {
// Note: Zero padding is not required here as its a typed copy which does
// not leak the bytes into the memory
// https://stackoverflow.com/questions/61114026/does-stdptrwrite-transfer-the-uninitialized-ness-of-the-bytes-it-writes
*(self.as_mut()) = val;
}
}
impl<'a, T> Drop for WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,

View File

@@ -27,20 +27,6 @@ pub struct Instance {
pub exports: Exports,
}
#[cfg(test)]
mod send_test {
use super::*;
fn is_send<T: Send>() -> bool {
true
}
#[test]
fn instance_is_send() {
assert!(is_send::<Instance>());
}
}
impl Instance {
/// Creates a new `Instance` from a WebAssembly [`Module`] and a
/// set of imports using [`Imports`] or the [`imports`] macro helper.

View File

@@ -1,429 +1,13 @@
use crate::access::{RefCow, SliceCow, WasmRefAccess};
use crate::js::externals::memory::MemoryBuffer;
use crate::WasmSliceAccess;
use crate::{Memory32, Memory64, MemoryView, RuntimeError, WasmPtr};
use std::{
convert::TryInto,
fmt,
marker::PhantomData,
mem::{self, MaybeUninit},
ops::Range,
slice,
string::FromUtf8Error,
};
use thiserror::Error;
use wasmer_types::{MemorySize, ValueType};
/// Error for invalid [`Memory`] access.
#[derive(Clone, Copy, Debug, Error)]
#[non_exhaustive]
pub enum MemoryAccessError {
/// Memory access is outside heap bounds.
#[error("memory access out of bounds")]
HeapOutOfBounds,
/// Address calculation overflow.
#[error("address calculation overflow")]
Overflow,
/// String is not valid UTF-8.
#[error("string is not valid utf-8")]
NonUtf8String,
}
impl From<MemoryAccessError> for RuntimeError {
fn from(err: MemoryAccessError) -> Self {
RuntimeError::new(err.to_string())
}
}
impl From<FromUtf8Error> for MemoryAccessError {
fn from(_err: FromUtf8Error) -> Self {
MemoryAccessError::NonUtf8String
}
}
/// Reference to a value in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmRef<'a, T: ValueType> {
buffer: MemoryBuffer<'a>,
offset: u64,
marker: PhantomData<*mut T>,
}
impl<'a, T: ValueType> WasmRef<'a, T> {
/// Creates a new `WasmRef` at the given offset in a memory.
#[inline]
pub fn new(view: &'a MemoryView, offset: u64) -> Self {
Self {
buffer: view.buffer().0,
offset,
marker: PhantomData,
}
}
/// Get the offset into Wasm linear memory for this `WasmRef`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
/// Get a `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
/// Get a `WasmPtr` fror this `WasmRef`.
#[inline]
pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
let offset: M::Offset = self
.offset
.try_into()
.map_err(|_| "invalid offset into memory")
.unwrap();
WasmPtr::<T, M>::new(offset)
}
/// Reads the location pointed to by this `WasmRef`.
#[inline]
pub fn read(self) -> Result<T, MemoryAccessError> {
let mut out = MaybeUninit::uninit();
let buf =
unsafe { slice::from_raw_parts_mut(out.as_mut_ptr() as *mut u8, mem::size_of::<T>()) };
self.buffer.read(self.offset, buf)?;
Ok(unsafe { out.assume_init() })
}
/// Writes to the location pointed to by this `WasmRef`.
#[inline]
pub fn write(self, val: T) -> Result<(), MemoryAccessError> {
let mut data = MaybeUninit::new(val);
let data = unsafe {
slice::from_raw_parts_mut(
data.as_mut_ptr() as *mut MaybeUninit<u8>,
mem::size_of::<T>(),
)
};
val.zero_padding_bytes(data);
let data = unsafe { slice::from_raw_parts(data.as_ptr() as *const _, data.len()) };
self.buffer.write(self.offset, data)
}
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmRefAccess<'a, T>, MemoryAccessError> {
WasmRefAccess::new(self)
}
}
impl<'a, T: ValueType> fmt::Debug for WasmRef<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmRef(offset: {}, pointer: {:#x})",
self.offset, self.offset
)
}
}
/// Reference to an array of values in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmSlice<'a, T: ValueType> {
buffer: MemoryBuffer<'a>,
offset: u64,
len: u64,
marker: PhantomData<*mut T>,
}
impl<'a, T: ValueType> WasmSlice<'a, T> {
/// Creates a new `WasmSlice` starting at the given offset in memory and
/// with the given number of elements.
///
/// Returns a `MemoryAccessError` if the slice length overflows.
#[inline]
pub fn new(memory: &'a MemoryView, offset: u64, len: u64) -> Result<Self, MemoryAccessError> {
let total_len = len
.checked_mul(mem::size_of::<T>() as u64)
.ok_or(MemoryAccessError::Overflow)?;
offset
.checked_add(total_len)
.ok_or(MemoryAccessError::Overflow)?;
Ok(Self {
buffer: memory.buffer().0,
offset,
len,
marker: PhantomData,
})
}
/// Get the offset into Wasm linear memory for this `WasmSlice`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
/// Get a 32-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
/// Get the number of elements in this slice.
#[inline]
pub fn len(self) -> u64 {
self.len
}
/// Return if the slice is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Get a `WasmRef` to an element in the slice.
#[inline]
pub fn index(self, idx: u64) -> WasmRef<'a, T> {
if idx >= self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + idx * mem::size_of::<T>() as u64;
WasmRef {
buffer: self.buffer,
offset,
marker: PhantomData,
}
}
/// Get a `WasmSlice` for a subslice of this slice.
#[inline]
pub fn subslice(self, range: Range<u64>) -> WasmSlice<'a, T> {
if range.start > range.end || range.end > self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + range.start * mem::size_of::<T>() as u64;
Self {
buffer: self.buffer,
offset,
len: range.end - range.start,
marker: PhantomData,
}
}
/// Get an iterator over the elements in this slice.
#[inline]
pub fn iter(self) -> WasmSliceIter<'a, T> {
WasmSliceIter { slice: self }
}
/// Reads an element of this slice.
#[inline]
pub fn read(self, idx: u64) -> Result<T, MemoryAccessError> {
self.index(idx).read()
}
/// Writes to an element of this slice.
#[inline]
pub fn write(self, idx: u64, val: T) -> Result<(), MemoryAccessError> {
self.index(idx).write(val)
}
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmSliceAccess<'a, T>, MemoryAccessError> {
WasmSliceAccess::new(self)
}
/// Reads the entire slice into the given buffer.
///
/// The length of the buffer must match the length of the slice.
#[inline]
pub fn read_slice(self, buf: &mut [T]) -> Result<(), MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(())
}
/// Reads the entire slice into the given uninitialized buffer.
///
/// The length of the buffer must match the length of the slice.
///
/// This method returns an initialized view of the buffer.
#[inline]
pub fn read_slice_uninit(
self,
buf: &mut [MaybeUninit<T>],
) -> Result<&mut [T], MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut T, buf.len()) })
}
/// Write the given slice into this `WasmSlice`.
///
/// The length of the slice must match the length of the `WasmSlice`.
#[inline]
pub fn write_slice(self, data: &[T]) -> Result<(), MemoryAccessError> {
assert_eq!(
data.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * mem::size_of::<T>())
};
self.buffer.write(self.offset, bytes)
}
/// Reads this `WasmSlice` into a `slice`.
#[inline]
pub fn read_to_slice<'b>(
self,
buf: &'b mut [MaybeUninit<u8>],
) -> Result<usize, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
self.buffer.read_uninit(self.offset, buf)?;
Ok(len)
}
/// Reads this `WasmSlice` into a `Vec`.
#[inline]
pub fn read_to_vec(self) -> Result<Vec<T>, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut vec = Vec::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
vec.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
vec.set_len(len);
}
Ok(vec)
}
/// Reads this `WasmSlice` into a `BytesMut`
#[inline]
pub fn read_to_bytes(self) -> Result<bytes::BytesMut, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut ret = bytes::BytesMut::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
ret.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
ret.set_len(len);
}
Ok(ret)
}
}
impl<'a, T: ValueType> fmt::Debug for WasmSlice<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmSlice(offset: {}, len: {}, pointer: {:#x})",
self.offset, self.len, self.offset
)
}
}
/// Iterator over the elements of a `WasmSlice`.
pub struct WasmSliceIter<'a, T: ValueType> {
slice: WasmSlice<'a, T>,
}
impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> {
type Item = WasmRef<'a, T>;
fn next(&mut self) -> Option<Self::Item> {
if self.slice.len() != 0 {
let elem = self.slice.index(0);
self.slice = self.slice.subslice(1..self.slice.len());
Some(elem)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0..self.slice.len()).size_hint()
}
}
impl<'a, T: ValueType> DoubleEndedIterator for WasmSliceIter<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.slice.len() != 0 {
let elem = self.slice.index(self.slice.len() - 1);
self.slice = self.slice.subslice(0..self.slice.len() - 1);
Some(elem)
} else {
None
}
}
}
impl<'a, T: ValueType> ExactSizeIterator for WasmSliceIter<'a, T> {}
use crate::access::{RefCow, SliceCow, WasmRefAccess, WasmSliceAccess};
use crate::{MemoryAccessError, WasmRef, WasmSlice};
use std::mem::{self, MaybeUninit};
use std::slice;
impl<'a, T> WasmSliceAccess<'a, T>
where
T: wasmer_types::ValueType,
{
fn new(slice: WasmSlice<'a, T>) -> Result<Self, MemoryAccessError> {
pub(crate) fn new(slice: WasmSlice<'a, T>) -> Result<Self, MemoryAccessError> {
let buf = slice.read_to_vec()?;
Ok(Self {
slice,
@@ -436,11 +20,46 @@ impl<'a, T> WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,
{
fn new(ptr: WasmRef<'a, T>) -> Result<Self, MemoryAccessError> {
let val = ptr.read()?;
pub(crate) fn new(ptr: WasmRef<'a, T>) -> Result<Self, MemoryAccessError> {
let mut out = MaybeUninit::uninit();
let buf =
unsafe { slice::from_raw_parts_mut(out.as_mut_ptr() as *mut u8, mem::size_of::<T>()) };
ptr.buffer.read(ptr.offset, buf)?;
let val = unsafe { out.assume_init() };
Ok(Self {
ptr,
buf: RefCow::Owned(val, false),
})
}
}
impl<'a, T> WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,
{
/// Reads the address pointed to by this `WasmPtr` in a memory.
#[inline]
#[allow(clippy::clone_on_copy)]
pub fn read(&self) -> T
where
T: Clone,
{
self.as_ref().clone()
}
/// Writes to the address pointed to by this `WasmPtr` in a memory.
#[inline]
pub fn write(&mut self, val: T) {
let mut data = MaybeUninit::new(val);
let data = unsafe {
slice::from_raw_parts_mut(
data.as_mut_ptr() as *mut MaybeUninit<u8>,
mem::size_of::<T>(),
)
};
val.zero_padding_bytes(data);
let data = unsafe { slice::from_raw_parts(data.as_ptr() as *const _, data.len()) };
self.ptr.buffer.write(self.ptr.offset, data).unwrap()
}
}

View File

@@ -1,415 +1,409 @@
#[cfg(feature = "js")]
pub use crate::js::mem_access::{MemoryAccessError, WasmRef, WasmSlice, WasmSliceIter};
use crate::access::WasmRefAccess;
use crate::externals::memory::MemoryBuffer;
use crate::{Memory32, Memory64, MemorySize, MemoryView, WasmPtr};
use crate::{RuntimeError, WasmSliceAccess};
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, MaybeUninit};
use std::ops::Range;
use std::slice;
use std::string::FromUtf8Error;
use thiserror::Error;
use wasmer_types::ValueType;
#[cfg(feature = "sys")]
pub use crate::sys::mem_access::{MemoryAccessError, WasmRef, WasmSlice, WasmSliceIter};
/// Error for invalid [`Memory`] access.
#[derive(Clone, Copy, Debug, Error)]
#[non_exhaustive]
pub enum MemoryAccessError {
/// Memory access is outside heap bounds.
#[error("memory access out of bounds")]
HeapOutOfBounds,
/// Address calculation overflow.
#[error("address calculation overflow")]
Overflow,
/// String is not valid UTF-8.
#[error("string is not valid utf-8")]
NonUtf8String,
}
// use crate::access::WasmRefAccess;
// use crate::externals::memory::MemoryBuffer;
// use crate::{Memory32, Memory64, MemorySize, MemoryView, WasmPtr};
// use crate::{RuntimeError, WasmSliceAccess};
// use std::convert::TryInto;
// use std::fmt;
// use std::marker::PhantomData;
// use std::mem::{self, MaybeUninit};
// use std::ops::Range;
// use std::slice;
// use std::string::FromUtf8Error;
// use thiserror::Error;
// use wasmer_types::ValueType;
impl From<MemoryAccessError> for RuntimeError {
fn from(err: MemoryAccessError) -> Self {
Self::new(err.to_string())
}
}
impl From<FromUtf8Error> for MemoryAccessError {
fn from(_err: FromUtf8Error) -> Self {
Self::NonUtf8String
}
}
// /// Error for invalid [`Memory`] access.
// #[derive(Clone, Copy, Debug, Error)]
// #[non_exhaustive]
// pub enum MemoryAccessError {
// /// Memory access is outside heap bounds.
// #[error("memory access out of bounds")]
// HeapOutOfBounds,
// /// Address calculation overflow.
// #[error("address calculation overflow")]
// Overflow,
// /// String is not valid UTF-8.
// #[error("string is not valid utf-8")]
// NonUtf8String,
// }
/// Reference to a value in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmRef<'a, T: ValueType> {
#[allow(unused)]
pub(crate) buffer: MemoryBuffer<'a>,
pub(crate) offset: u64,
marker: PhantomData<*mut T>,
}
// impl From<MemoryAccessError> for RuntimeError {
// fn from(err: MemoryAccessError) -> Self {
// Self::new(err.to_string())
// }
// }
// impl From<FromUtf8Error> for MemoryAccessError {
// fn from(_err: FromUtf8Error) -> Self {
// Self::NonUtf8String
// }
// }
impl<'a, T: ValueType> WasmRef<'a, T> {
/// Creates a new `WasmRef` at the given offset in a memory.
#[inline]
pub fn new(view: &'a MemoryView, offset: u64) -> Self {
Self {
buffer: view.buffer(),
offset,
marker: PhantomData,
}
}
// /// Reference to a value in Wasm memory.
// ///
// /// The type of the value must satisfy the requirements of the `ValueType`
// /// trait which guarantees that reading and writing such a value to untrusted
// /// memory is safe.
// ///
// /// The address is not required to be aligned: unaligned accesses are fully
// /// supported.
// ///
// /// This wrapper safely handles concurrent modifications of the data by another
// /// thread.
// #[derive(Clone, Copy)]
// pub struct WasmRef<'a, T: ValueType> {
// #[allow(unused)]
// pub(crate) buffer: MemoryBuffer<'a>,
// pub(crate) offset: u64,
// marker: PhantomData<*mut T>,
// }
/// Get the offset into Wasm linear memory for this `WasmRef`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
// impl<'a, T: ValueType> WasmRef<'a, T> {
// /// Creates a new `WasmRef` at the given offset in a memory.
// #[inline]
// pub fn new(view: &'a MemoryView, offset: u64) -> Self {
// Self {
// buffer: view.buffer(),
// offset,
// marker: PhantomData,
// }
// }
/// Get a `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
// /// Get the offset into Wasm linear memory for this `WasmRef`.
// #[inline]
// pub fn offset(self) -> u64 {
// self.offset
// }
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
// /// Get a `WasmPtr` for this `WasmRef`.
// #[inline]
// pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
// WasmPtr::new(self.offset as u32)
// }
/// Get a `WasmPtr` fror this `WasmRef`.
#[inline]
pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
let offset: M::Offset = self
.offset
.try_into()
.map_err(|_| "invalid offset into memory")
.unwrap();
WasmPtr::<T, M>::new(offset)
}
// /// Get a 64-bit `WasmPtr` for this `WasmRef`.
// #[inline]
// pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
// WasmPtr::new(self.offset)
// }
/// Reads the location pointed to by this `WasmRef`.
#[inline]
pub fn read(self) -> Result<T, MemoryAccessError> {
let mut out = MaybeUninit::uninit();
let buf =
unsafe { slice::from_raw_parts_mut(out.as_mut_ptr() as *mut u8, mem::size_of::<T>()) };
self.buffer.read(self.offset, buf)?;
Ok(unsafe { out.assume_init() })
// Ok(self.access()?.read())
}
// /// Get a `WasmPtr` fror this `WasmRef`.
// #[inline]
// pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
// let offset: M::Offset = self
// .offset
// .try_into()
// .map_err(|_| "invalid offset into memory")
// .unwrap();
// WasmPtr::<T, M>::new(offset)
// }
/// Writes to the location pointed to by this `WasmRef`.
#[inline]
pub fn write(self, val: T) -> Result<(), MemoryAccessError> {
self.access()?.write(val);
Ok(())
}
// /// Reads the location pointed to by this `WasmRef`.
// #[inline]
// pub fn read(self) -> Result<T, MemoryAccessError> {
// let mut out = MaybeUninit::uninit();
// let buf =
// unsafe { slice::from_raw_parts_mut(out.as_mut_ptr() as *mut u8, mem::size_of::<T>()) };
// self.buffer.read(self.offset, buf)?;
// Ok(unsafe { out.assume_init() })
// // Ok(self.access()?.read())
// }
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmRefAccess<'a, T>, MemoryAccessError> {
WasmRefAccess::new(self)
}
}
// /// Writes to the location pointed to by this `WasmRef`.
// #[inline]
// pub fn write(self, val: T) -> Result<(), MemoryAccessError> {
// self.access()?.write(val);
// Ok(())
// }
impl<'a, T: ValueType> fmt::Debug for WasmRef<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmRef(offset: {}, pointer: {:#x})",
self.offset, self.offset
)
}
}
// /// Gains direct access to the memory of this slice
// #[inline]
// pub fn access(self) -> Result<WasmRefAccess<'a, T>, MemoryAccessError> {
// WasmRefAccess::new(self)
// }
// }
/// Reference to an array of values in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmSlice<'a, T: ValueType> {
pub(crate) buffer: MemoryBuffer<'a>,
pub(crate) offset: u64,
pub(crate) len: u64,
marker: PhantomData<*mut T>,
}
// impl<'a, T: ValueType> fmt::Debug for WasmRef<'a, T> {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!(
// f,
// "WasmRef(offset: {}, pointer: {:#x})",
// self.offset, self.offset
// )
// }
// }
impl<'a, T: ValueType> WasmSlice<'a, T> {
/// Creates a new `WasmSlice` starting at the given offset in memory and
/// with the given number of elements.
///
/// Returns a `MemoryAccessError` if the slice length overflows.
#[inline]
pub fn new(view: &'a MemoryView, offset: u64, len: u64) -> Result<Self, MemoryAccessError> {
let total_len = len
.checked_mul(mem::size_of::<T>() as u64)
.ok_or(MemoryAccessError::Overflow)?;
offset
.checked_add(total_len)
.ok_or(MemoryAccessError::Overflow)?;
Ok(Self {
buffer: view.buffer(),
offset,
len,
marker: PhantomData,
})
}
// /// Reference to an array of values in Wasm memory.
// ///
// /// The type of the value must satisfy the requirements of the `ValueType`
// /// trait which guarantees that reading and writing such a value to untrusted
// /// memory is safe.
// ///
// /// The address is not required to be aligned: unaligned accesses are fully
// /// supported.
// ///
// /// This wrapper safely handles concurrent modifications of the data by another
// /// thread.
// #[derive(Clone, Copy)]
// pub struct WasmSlice<'a, T: ValueType> {
// pub(crate) buffer: MemoryBuffer<'a>,
// pub(crate) offset: u64,
// pub(crate) len: u64,
// marker: PhantomData<*mut T>,
// }
/// Get the offset into Wasm linear memory for this `WasmSlice`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
// impl<'a, T: ValueType> WasmSlice<'a, T> {
// /// Creates a new `WasmSlice` starting at the given offset in memory and
// /// with the given number of elements.
// ///
// /// Returns a `MemoryAccessError` if the slice length overflows.
// #[inline]
// pub fn new(view: &'a MemoryView, offset: u64, len: u64) -> Result<Self, MemoryAccessError> {
// let total_len = len
// .checked_mul(mem::size_of::<T>() as u64)
// .ok_or(MemoryAccessError::Overflow)?;
// offset
// .checked_add(total_len)
// .ok_or(MemoryAccessError::Overflow)?;
// Ok(Self {
// buffer: view.buffer(),
// offset,
// len,
// marker: PhantomData,
// })
// }
/// Get a 32-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
// /// Get the offset into Wasm linear memory for this `WasmSlice`.
// #[inline]
// pub fn offset(self) -> u64 {
// self.offset
// }
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
// /// Get a 32-bit `WasmPtr` for this `WasmRef`.
// #[inline]
// pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
// WasmPtr::new(self.offset as u32)
// }
/// Get the number of elements in this slice.
#[inline]
pub fn len(self) -> u64 {
self.len
}
// /// Get a 64-bit `WasmPtr` for this `WasmRef`.
// #[inline]
// pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
// WasmPtr::new(self.offset)
// }
/// Returns `true` if the number of elements is 0.
#[inline]
pub fn is_empty(self) -> bool {
self.len == 0
}
// /// Get the number of elements in this slice.
// #[inline]
// pub fn len(self) -> u64 {
// self.len
// }
/// Get a `WasmRef` to an element in the slice.
#[inline]
pub fn index(self, idx: u64) -> WasmRef<'a, T> {
if idx >= self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + idx * mem::size_of::<T>() as u64;
WasmRef {
buffer: self.buffer,
offset,
marker: PhantomData,
}
}
// /// Returns `true` if the number of elements is 0.
// #[inline]
// pub fn is_empty(self) -> bool {
// self.len == 0
// }
/// Get a `WasmSlice` for a subslice of this slice.
#[inline]
pub fn subslice(self, range: Range<u64>) -> WasmSlice<'a, T> {
if range.start > range.end || range.end > self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + range.start * mem::size_of::<T>() as u64;
Self {
buffer: self.buffer,
offset,
len: range.end - range.start,
marker: PhantomData,
}
}
// /// Get a `WasmRef` to an element in the slice.
// #[inline]
// pub fn index(self, idx: u64) -> WasmRef<'a, T> {
// if idx >= self.len {
// panic!("WasmSlice out of bounds");
// }
// let offset = self.offset + idx * mem::size_of::<T>() as u64;
// WasmRef {
// buffer: self.buffer,
// offset,
// marker: PhantomData,
// }
// }
/// Get an iterator over the elements in this slice.
#[inline]
pub fn iter(self) -> WasmSliceIter<'a, T> {
WasmSliceIter { slice: self }
}
// /// Get a `WasmSlice` for a subslice of this slice.
// #[inline]
// pub fn subslice(self, range: Range<u64>) -> WasmSlice<'a, T> {
// if range.start > range.end || range.end > self.len {
// panic!("WasmSlice out of bounds");
// }
// let offset = self.offset + range.start * mem::size_of::<T>() as u64;
// Self {
// buffer: self.buffer,
// offset,
// len: range.end - range.start,
// marker: PhantomData,
// }
// }
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmSliceAccess<'a, T>, MemoryAccessError> {
WasmSliceAccess::new(self)
}
// /// Get an iterator over the elements in this slice.
// #[inline]
// pub fn iter(self) -> WasmSliceIter<'a, T> {
// WasmSliceIter { slice: self }
// }
/// Reads an element of this slice.
#[inline]
pub fn read(self, idx: u64) -> Result<T, MemoryAccessError> {
self.index(idx).read()
}
// /// Gains direct access to the memory of this slice
// #[inline]
// pub fn access(self) -> Result<WasmSliceAccess<'a, T>, MemoryAccessError> {
// WasmSliceAccess::new(self)
// }
/// Writes to an element of this slice.
#[inline]
pub fn write(self, idx: u64, val: T) -> Result<(), MemoryAccessError> {
self.index(idx).write(val)
}
// /// Reads an element of this slice.
// #[inline]
// pub fn read(self, idx: u64) -> Result<T, MemoryAccessError> {
// self.index(idx).read()
// }
/// Reads the entire slice into the given buffer.
///
/// The length of the buffer must match the length of the slice.
#[inline]
pub fn read_slice(self, buf: &mut [T]) -> Result<(), MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(())
}
// /// Writes to an element of this slice.
// #[inline]
// pub fn write(self, idx: u64, val: T) -> Result<(), MemoryAccessError> {
// self.index(idx).write(val)
// }
/// Reads the entire slice into the given uninitialized buffer.
///
/// The length of the buffer must match the length of the slice.
///
/// This method returns an initialized view of the buffer.
#[inline]
pub fn read_slice_uninit(
self,
buf: &mut [MaybeUninit<T>],
) -> Result<&mut [T], MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut T, buf.len()) })
}
// /// Reads the entire slice into the given buffer.
// ///
// /// The length of the buffer must match the length of the slice.
// #[inline]
// pub fn read_slice(self, buf: &mut [T]) -> Result<(), MemoryAccessError> {
// assert_eq!(
// buf.len() as u64,
// self.len,
// "slice length doesn't match WasmSlice length"
// );
// let bytes = unsafe {
// slice::from_raw_parts_mut(
// buf.as_mut_ptr() as *mut MaybeUninit<u8>,
// buf.len() * mem::size_of::<T>(),
// )
// };
// self.buffer.read_uninit(self.offset, bytes)?;
// Ok(())
// }
/// Write the given slice into this `WasmSlice`.
///
/// The length of the slice must match the length of the `WasmSlice`.
#[inline]
pub fn write_slice(self, data: &[T]) -> Result<(), MemoryAccessError> {
assert_eq!(
data.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * mem::size_of::<T>())
};
self.buffer.write(self.offset, bytes)
}
// /// Reads the entire slice into the given uninitialized buffer.
// ///
// /// The length of the buffer must match the length of the slice.
// ///
// /// This method returns an initialized view of the buffer.
// #[inline]
// pub fn read_slice_uninit(
// self,
// buf: &mut [MaybeUninit<T>],
// ) -> Result<&mut [T], MemoryAccessError> {
// assert_eq!(
// buf.len() as u64,
// self.len,
// "slice length doesn't match WasmSlice length"
// );
// let bytes = unsafe {
// slice::from_raw_parts_mut(
// buf.as_mut_ptr() as *mut MaybeUninit<u8>,
// buf.len() * mem::size_of::<T>(),
// )
// };
// self.buffer.read_uninit(self.offset, bytes)?;
// Ok(unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut T, buf.len()) })
// }
/// Reads this `WasmSlice` into a `slice`.
#[inline]
pub fn read_to_slice(self, buf: &mut [MaybeUninit<u8>]) -> Result<usize, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
self.buffer.read_uninit(self.offset, buf)?;
Ok(len)
}
// /// Write the given slice into this `WasmSlice`.
// ///
// /// The length of the slice must match the length of the `WasmSlice`.
// #[inline]
// pub fn write_slice(self, data: &[T]) -> Result<(), MemoryAccessError> {
// assert_eq!(
// data.len() as u64,
// self.len,
// "slice length doesn't match WasmSlice length"
// );
// let bytes = unsafe {
// slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * mem::size_of::<T>())
// };
// self.buffer.write(self.offset, bytes)
// }
/// Reads this `WasmSlice` into a `Vec`.
#[inline]
pub fn read_to_vec(self) -> Result<Vec<T>, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut vec = Vec::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
vec.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
vec.set_len(len);
}
Ok(vec)
}
// /// Reads this `WasmSlice` into a `slice`.
// #[inline]
// pub fn read_to_slice(self, buf: &mut [MaybeUninit<u8>]) -> Result<usize, MemoryAccessError> {
// let len = self.len.try_into().expect("WasmSlice length overflow");
// self.buffer.read_uninit(self.offset, buf)?;
// Ok(len)
// }
/// Reads this `WasmSlice` into a `BytesMut`
#[inline]
pub fn read_to_bytes(self) -> Result<bytes::BytesMut, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut ret = bytes::BytesMut::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
ret.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
ret.set_len(len);
}
Ok(ret)
}
}
// /// Reads this `WasmSlice` into a `Vec`.
// #[inline]
// pub fn read_to_vec(self) -> Result<Vec<T>, MemoryAccessError> {
// let len = self.len.try_into().expect("WasmSlice length overflow");
// let mut vec = Vec::with_capacity(len);
// let bytes = unsafe {
// slice::from_raw_parts_mut(
// vec.as_mut_ptr() as *mut MaybeUninit<u8>,
// len * mem::size_of::<T>(),
// )
// };
// self.buffer.read_uninit(self.offset, bytes)?;
// unsafe {
// vec.set_len(len);
// }
// Ok(vec)
// }
impl<'a, T: ValueType> fmt::Debug for WasmSlice<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmSlice(offset: {}, len: {}, pointer: {:#x})",
self.offset, self.len, self.offset
)
}
}
// /// Reads this `WasmSlice` into a `BytesMut`
// #[inline]
// pub fn read_to_bytes(self) -> Result<bytes::BytesMut, MemoryAccessError> {
// let len = self.len.try_into().expect("WasmSlice length overflow");
// let mut ret = bytes::BytesMut::with_capacity(len);
// let bytes = unsafe {
// slice::from_raw_parts_mut(
// ret.as_mut_ptr() as *mut MaybeUninit<u8>,
// len * mem::size_of::<T>(),
// )
// };
// self.buffer.read_uninit(self.offset, bytes)?;
// unsafe {
// ret.set_len(len);
// }
// Ok(ret)
// }
// }
/// Iterator over the elements of a `WasmSlice`.
pub struct WasmSliceIter<'a, T: ValueType> {
slice: WasmSlice<'a, T>,
}
// impl<'a, T: ValueType> fmt::Debug for WasmSlice<'a, T> {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!(
// f,
// "WasmSlice(offset: {}, len: {}, pointer: {:#x})",
// self.offset, self.len, self.offset
// )
// }
// }
impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> {
type Item = WasmRef<'a, T>;
// /// Iterator over the elements of a `WasmSlice`.
// pub struct WasmSliceIter<'a, T: ValueType> {
// slice: WasmSlice<'a, T>,
// }
fn next(&mut self) -> Option<Self::Item> {
if !self.slice.is_empty() {
let elem = self.slice.index(0);
self.slice = self.slice.subslice(1..self.slice.len());
Some(elem)
} else {
None
}
}
// impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> {
// type Item = WasmRef<'a, T>;
fn size_hint(&self) -> (usize, Option<usize>) {
(0..self.slice.len()).size_hint()
}
}
// fn next(&mut self) -> Option<Self::Item> {
// if !self.slice.is_empty() {
// let elem = self.slice.index(0);
// self.slice = self.slice.subslice(1..self.slice.len());
// Some(elem)
// } else {
// None
// }
// }
impl<'a, T: ValueType> DoubleEndedIterator for WasmSliceIter<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if !self.slice.is_empty() {
let elem = self.slice.index(self.slice.len() - 1);
self.slice = self.slice.subslice(0..self.slice.len() - 1);
Some(elem)
} else {
None
}
}
}
// fn size_hint(&self) -> (usize, Option<usize>) {
// (0..self.slice.len()).size_hint()
// }
// }
// impl<'a, T: ValueType> DoubleEndedIterator for WasmSliceIter<'a, T> {
// fn next_back(&mut self) -> Option<Self::Item> {
// if !self.slice.is_empty() {
// let elem = self.slice.index(self.slice.len() - 1);
// self.slice = self.slice.subslice(0..self.slice.len() - 1);
// Some(elem)
// } else {
// None
// }
// }
// }
// impl<'a, T: ValueType> ExactSizeIterator for WasmSliceIter<'a, T> {}
impl<'a, T: ValueType> ExactSizeIterator for WasmSliceIter<'a, T> {}

View File

@@ -12,6 +12,20 @@ pub struct Instance {
_handle: StoreHandle<VMInstance>,
}
#[cfg(test)]
mod send_test {
use super::*;
fn is_send<T: Send>() -> bool {
true
}
#[test]
fn instance_is_send() {
assert!(is_send::<Instance>());
}
}
impl From<wasmer_compiler::InstantiationError> for InstantiationError {
fn from(other: wasmer_compiler::InstantiationError) -> Self {
match other {

View File

@@ -1,417 +1,12 @@
use crate::sys::externals::memory::MemoryBuffer;
use crate::{
access::{RefCow, SliceCow, WasmRefAccess},
RuntimeError, WasmSliceAccess,
};
#[allow(unused_imports)]
use crate::{Memory, Memory32, Memory64, MemorySize, MemoryView, WasmPtr};
use std::{
convert::TryInto,
fmt,
marker::PhantomData,
mem::{self, MaybeUninit},
ops::Range,
slice,
string::FromUtf8Error,
};
use thiserror::Error;
use wasmer_types::ValueType;
/// Error for invalid [`Memory`] access.
#[derive(Clone, Copy, Debug, Error)]
#[non_exhaustive]
pub enum MemoryAccessError {
/// Memory access is outside heap bounds.
#[error("memory access out of bounds")]
HeapOutOfBounds,
/// Address calculation overflow.
#[error("address calculation overflow")]
Overflow,
/// String is not valid UTF-8.
#[error("string is not valid utf-8")]
NonUtf8String,
}
impl From<MemoryAccessError> for RuntimeError {
fn from(err: MemoryAccessError) -> Self {
Self::new(err.to_string())
}
}
impl From<FromUtf8Error> for MemoryAccessError {
fn from(_err: FromUtf8Error) -> Self {
Self::NonUtf8String
}
}
/// Reference to a value in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmRef<'a, T: ValueType> {
buffer: MemoryBuffer<'a>,
offset: u64,
marker: PhantomData<*mut T>,
}
impl<'a, T: ValueType> WasmRef<'a, T> {
/// Creates a new `WasmRef` at the given offset in a memory.
#[inline]
pub fn new(view: &'a MemoryView, offset: u64) -> Self {
Self {
buffer: view.buffer().0,
offset,
marker: PhantomData,
}
}
/// Get the offset into Wasm linear memory for this `WasmRef`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
/// Get a `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
/// Get a `WasmPtr` fror this `WasmRef`.
#[inline]
pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
let offset: M::Offset = self
.offset
.try_into()
.map_err(|_| "invalid offset into memory")
.unwrap();
WasmPtr::<T, M>::new(offset)
}
/// Reads the location pointed to by this `WasmRef`.
#[inline]
pub fn read(self) -> Result<T, MemoryAccessError> {
Ok(self.access()?.read())
}
/// Writes to the location pointed to by this `WasmRef`.
#[inline]
pub fn write(self, val: T) -> Result<(), MemoryAccessError> {
self.access()?.write(val);
Ok(())
}
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmRefAccess<'a, T>, MemoryAccessError> {
WasmRefAccess::new(self)
}
}
impl<'a, T: ValueType> fmt::Debug for WasmRef<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmRef(offset: {}, pointer: {:#x})",
self.offset, self.offset
)
}
}
/// Reference to an array of values in Wasm memory.
///
/// The type of the value must satisfy the requirements of the `ValueType`
/// trait which guarantees that reading and writing such a value to untrusted
/// memory is safe.
///
/// The address is not required to be aligned: unaligned accesses are fully
/// supported.
///
/// This wrapper safely handles concurrent modifications of the data by another
/// thread.
#[derive(Clone, Copy)]
pub struct WasmSlice<'a, T: ValueType> {
buffer: MemoryBuffer<'a>,
offset: u64,
len: u64,
marker: PhantomData<*mut T>,
}
impl<'a, T: ValueType> WasmSlice<'a, T> {
/// Creates a new `WasmSlice` starting at the given offset in memory and
/// with the given number of elements.
///
/// Returns a `MemoryAccessError` if the slice length overflows.
#[inline]
pub fn new(view: &'a MemoryView, offset: u64, len: u64) -> Result<Self, MemoryAccessError> {
let total_len = len
.checked_mul(mem::size_of::<T>() as u64)
.ok_or(MemoryAccessError::Overflow)?;
offset
.checked_add(total_len)
.ok_or(MemoryAccessError::Overflow)?;
Ok(Self {
buffer: view.buffer().0,
offset,
len,
marker: PhantomData,
})
}
/// Get the offset into Wasm linear memory for this `WasmSlice`.
#[inline]
pub fn offset(self) -> u64 {
self.offset
}
/// Get a 32-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr32(self) -> WasmPtr<T, Memory32> {
WasmPtr::new(self.offset as u32)
}
/// Get a 64-bit `WasmPtr` for this `WasmRef`.
#[inline]
pub fn as_ptr64(self) -> WasmPtr<T, Memory64> {
WasmPtr::new(self.offset)
}
/// Get the number of elements in this slice.
#[inline]
pub fn len(self) -> u64 {
self.len
}
/// Returns `true` if the number of elements is 0.
#[inline]
pub fn is_empty(self) -> bool {
self.len == 0
}
/// Get a `WasmRef` to an element in the slice.
#[inline]
pub fn index(self, idx: u64) -> WasmRef<'a, T> {
if idx >= self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + idx * mem::size_of::<T>() as u64;
WasmRef {
buffer: self.buffer,
offset,
marker: PhantomData,
}
}
/// Get a `WasmSlice` for a subslice of this slice.
#[inline]
pub fn subslice(self, range: Range<u64>) -> WasmSlice<'a, T> {
if range.start > range.end || range.end > self.len {
panic!("WasmSlice out of bounds");
}
let offset = self.offset + range.start * mem::size_of::<T>() as u64;
Self {
buffer: self.buffer,
offset,
len: range.end - range.start,
marker: PhantomData,
}
}
/// Get an iterator over the elements in this slice.
#[inline]
pub fn iter(self) -> WasmSliceIter<'a, T> {
WasmSliceIter { slice: self }
}
/// Gains direct access to the memory of this slice
#[inline]
pub fn access(self) -> Result<WasmSliceAccess<'a, T>, MemoryAccessError> {
WasmSliceAccess::new(self)
}
/// Reads an element of this slice.
#[inline]
pub fn read(self, idx: u64) -> Result<T, MemoryAccessError> {
self.index(idx).read()
}
/// Writes to an element of this slice.
#[inline]
pub fn write(self, idx: u64, val: T) -> Result<(), MemoryAccessError> {
self.index(idx).write(val)
}
/// Reads the entire slice into the given buffer.
///
/// The length of the buffer must match the length of the slice.
#[inline]
pub fn read_slice(self, buf: &mut [T]) -> Result<(), MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(())
}
/// Reads the entire slice into the given uninitialized buffer.
///
/// The length of the buffer must match the length of the slice.
///
/// This method returns an initialized view of the buffer.
#[inline]
pub fn read_slice_uninit(
self,
buf: &mut [MaybeUninit<T>],
) -> Result<&mut [T], MemoryAccessError> {
assert_eq!(
buf.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut MaybeUninit<u8>,
buf.len() * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
Ok(unsafe { slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut T, buf.len()) })
}
/// Write the given slice into this `WasmSlice`.
///
/// The length of the slice must match the length of the `WasmSlice`.
#[inline]
pub fn write_slice(self, data: &[T]) -> Result<(), MemoryAccessError> {
assert_eq!(
data.len() as u64,
self.len,
"slice length doesn't match WasmSlice length"
);
let bytes = unsafe {
slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * mem::size_of::<T>())
};
self.buffer.write(self.offset, bytes)
}
/// Reads this `WasmSlice` into a `slice`.
#[inline]
pub fn read_to_slice(self, buf: &mut [MaybeUninit<u8>]) -> Result<usize, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
self.buffer.read_uninit(self.offset, buf)?;
Ok(len)
}
/// Reads this `WasmSlice` into a `Vec`.
#[inline]
pub fn read_to_vec(self) -> Result<Vec<T>, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut vec = Vec::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
vec.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
vec.set_len(len);
}
Ok(vec)
}
/// Reads this `WasmSlice` into a `BytesMut`
#[inline]
pub fn read_to_bytes(self) -> Result<bytes::BytesMut, MemoryAccessError> {
let len = self.len.try_into().expect("WasmSlice length overflow");
let mut ret = bytes::BytesMut::with_capacity(len);
let bytes = unsafe {
slice::from_raw_parts_mut(
ret.as_mut_ptr() as *mut MaybeUninit<u8>,
len * mem::size_of::<T>(),
)
};
self.buffer.read_uninit(self.offset, bytes)?;
unsafe {
ret.set_len(len);
}
Ok(ret)
}
}
impl<'a, T: ValueType> fmt::Debug for WasmSlice<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WasmSlice(offset: {}, len: {}, pointer: {:#x})",
self.offset, self.len, self.offset
)
}
}
/// Iterator over the elements of a `WasmSlice`.
pub struct WasmSliceIter<'a, T: ValueType> {
slice: WasmSlice<'a, T>,
}
impl<'a, T: ValueType> Iterator for WasmSliceIter<'a, T> {
type Item = WasmRef<'a, T>;
fn next(&mut self) -> Option<Self::Item> {
if !self.slice.is_empty() {
let elem = self.slice.index(0);
self.slice = self.slice.subslice(1..self.slice.len());
Some(elem)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0..self.slice.len()).size_hint()
}
}
impl<'a, T: ValueType> DoubleEndedIterator for WasmSliceIter<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if !self.slice.is_empty() {
let elem = self.slice.index(self.slice.len() - 1);
self.slice = self.slice.subslice(0..self.slice.len() - 1);
Some(elem)
} else {
None
}
}
}
impl<'a, T: ValueType> ExactSizeIterator for WasmSliceIter<'a, T> {}
use crate::access::{RefCow, SliceCow, WasmRefAccess, WasmSliceAccess};
use crate::{MemoryAccessError, WasmRef, WasmSlice};
use std::mem;
impl<'a, T> WasmSliceAccess<'a, T>
where
T: wasmer_types::ValueType,
{
fn new(slice: WasmSlice<'a, T>) -> Result<Self, MemoryAccessError> {
pub(crate) fn new(slice: WasmSlice<'a, T>) -> Result<Self, MemoryAccessError> {
let total_len = slice
.len
.checked_mul(mem::size_of::<T>() as u64)
@@ -420,16 +15,16 @@ where
.offset
.checked_add(total_len)
.ok_or(MemoryAccessError::Overflow)?;
if end > slice.buffer.len as u64 {
if end > slice.buffer.0.len as u64 {
#[cfg(feature = "tracing")]
warn!(
"attempted to read ({} bytes) beyond the bounds of the memory view ({} > {})",
total_len, end, slice.buffer.len
total_len, end, slice.buffer.0.len
);
return Err(MemoryAccessError::HeapOutOfBounds);
}
let buf = unsafe {
let buf_ptr: *mut u8 = slice.buffer.base.add(slice.offset as usize);
let buf_ptr: *mut u8 = slice.buffer.0.base.add(slice.offset as usize);
let buf_ptr: *mut T = std::mem::transmute(buf_ptr);
std::slice::from_raw_parts_mut(buf_ptr, slice.len as usize)
};
@@ -444,22 +39,22 @@ impl<'a, T> WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,
{
fn new(ptr: WasmRef<'a, T>) -> Result<Self, MemoryAccessError> {
pub(crate) fn new(ptr: WasmRef<'a, T>) -> Result<Self, MemoryAccessError> {
let total_len = mem::size_of::<T>() as u64;
let end = ptr
.offset
.checked_add(total_len)
.ok_or(MemoryAccessError::Overflow)?;
if end > ptr.buffer.len as u64 {
if end > ptr.buffer.0.len as u64 {
#[cfg(feature = "tracing")]
warn!(
"attempted to read ({} bytes) beyond the bounds of the memory view ({} > {})",
total_len, end, ptr.buffer.len
total_len, end, ptr.buffer.0.len
);
return Err(MemoryAccessError::HeapOutOfBounds);
}
let val = unsafe {
let val_ptr: *mut u8 = ptr.buffer.base.add(ptr.offset as usize);
let val_ptr: *mut u8 = ptr.buffer.0.base.add(ptr.offset as usize);
let val_ptr: *mut T = std::mem::transmute(val_ptr);
&mut *val_ptr
};
@@ -469,3 +64,27 @@ where
})
}
}
impl<'a, T> WasmRefAccess<'a, T>
where
T: wasmer_types::ValueType,
{
/// Reads the address pointed to by this `WasmPtr` in a memory.
#[inline]
#[allow(clippy::clone_on_copy)]
pub fn read(&self) -> T
where
T: Clone,
{
self.as_ref().clone()
}
/// Writes to the address pointed to by this `WasmPtr` in a memory.
#[inline]
pub fn write(&mut self, val: T) {
// Note: Zero padding is not required here as its a typed copy which does
// not leak the bytes into the memory
// https://stackoverflow.com/questions/61114026/does-stdptrwrite-transfer-the-uninitialized-ness-of-the-bytes-it-writes
*(self.as_mut()) = val;
}
}