Skip to content

Commit

Permalink
wiggle: allow wiggle to use shared memory
Browse files Browse the repository at this point in the history
`wiggle` looks for an exported `Memory` named `"memory"` to use for its
guest slices. This change allows it to use a `SharedMemory` if this is
the kind of memory used for the export.

It is `unsafe` to use shared memory in Wiggle because of broken Rust
guarantees: previously, Wiggle could hand out slices to WebAssembly
linear memory that could be concurrently modified by some other thread.
With the introduction of Wiggle's new `UnsafeGuestSlice` (bytecodealliance#5225, bytecodealliance#5229,
 bytecodealliance#5264), Wiggle should now correctly communicate its guarantees through
its API.
  • Loading branch information
abrown committed Nov 14, 2022
1 parent 72eda0c commit 8058157
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions crates/wiggle/generate/src/wasmtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,23 @@ fn generate_func(
};

let body = quote! {
let mem = match caller.get_export("memory") {
Some(#rt::wasmtime_crate::Extern::Memory(m)) => m,
let (mem, ctx, shared) = match caller.get_export("memory") {
Some(#rt::wasmtime_crate::Extern::Memory(m)) => {
let (mem, ctx) = m.data_and_store_mut(&mut caller);
let ctx = get_cx(ctx);
(mem, ctx, false)
}
Some(#rt::wasmtime_crate::Extern::SharedMemory(m)) => {
// SAFETY: `WasmtimeGuestMemory` never hands out the mutable
// slice and the `unsafe`-ness is propagated by the `shared`
// flag.
let mem = unsafe { std::mem::transmute::<&[std::cell::UnsafeCell<u8>], &mut [u8]>(m.data()) };
let ctx = get_cx(caller.data_mut());
(mem, ctx, true)
}
_ => #rt::anyhow::bail!("missing required memory export"),
};
let (mem , ctx) = mem.data_and_store_mut(&mut caller);
let ctx = get_cx(ctx);
let mem = #rt::wasmtime::WasmtimeGuestMemory::new(mem, false);
let mem = #rt::wasmtime::WasmtimeGuestMemory::new(mem, shared);
Ok(<#ret_ty>::from(#abi_func(ctx, &mem #(, #arg_names)*) #await_ ?))
};

Expand Down

0 comments on commit 8058157

Please sign in to comment.