Skip to content

Commit

Permalink
review: handle underfill of temporary buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
abrown committed Jan 3, 2023
1 parent f3c4c51 commit 652988f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
17 changes: 13 additions & 4 deletions crates/wasi-common/src/snapshots/preview_1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1111,15 +1111,24 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
buf: &GuestPtr<'a, u8>,
buf_len: types::Size,
) -> Result<(), Error> {
let buf = buf.as_array(buf_len).as_unsafe_slice_mut()?;
let buf = buf.as_array(buf_len);
if buf.is_shared_memory() {
// If the Wasm memory is shared, copy to an intermediate buffer to
// avoid Rust unsafety (i.e., the called function could rely on
// `&mut [u8]`'s exclusive ownership which is not guaranteed due to
// potential access from other threads).
let mut tmp = vec![0; buf.len().min(MAX_SHARED_BUFFER_SIZE)];
self.random.try_fill_bytes(&mut tmp)?;
buf.copy_from_slice(&tmp)?;
let mut copied: u32 = 0;
while copied < buf.len() {
let len = (buf.len() - copied).min(MAX_SHARED_BUFFER_SIZE as u32);
let mut tmp = vec![0; len as usize];
self.random.try_fill_bytes(&mut tmp)?;
let dest = buf
.get_range(copied..copied + len)
.unwrap()
.as_unsafe_slice_mut()?;
dest.copy_from_slice(&tmp)?;
copied += len;
}
} else {
// If the Wasm memory is non-shared, copy directly into the linear
// memory.
Expand Down
5 changes: 5 additions & 0 deletions crates/wiggle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,11 @@ impl<'a, T: ?Sized + Pointee> GuestPtr<'a, T> {
{
GuestPtr::new(self.mem, (self.pointer, elems))
}

/// Check if this pointer references WebAssembly shared memory.
pub fn is_shared_memory(&self) -> bool {
self.mem.is_shared_memory()
}
}

impl<'a, T> GuestPtr<'a, [T]> {
Expand Down

0 comments on commit 652988f

Please sign in to comment.