wasmtime

Struct SharedMemory

source
pub struct SharedMemory { /* private fields */ }
Available on crate feature runtime only.
Expand description

A constructor for externally-created shared memory.

The threads proposal adds the concept of “shared memory” to WebAssembly. This is much the same as a Wasm linear memory (i.e., Memory), but can be used concurrently by multiple agents. Because these agents may execute in different threads, SharedMemory must be thread-safe.

When the threads proposal is enabled, there are multiple ways to construct shared memory:

  1. for imported shared memory, e.g., (import "env" "memory" (memory 1 1 shared)), the user must supply a SharedMemory with the externally-created memory as an import to the instance–e.g., shared_memory.into().
  2. for private or exported shared memory, e.g., (export "env" "memory" (memory 1 1 shared)), Wasmtime will create the memory internally during instantiation–access using Instance::get_shared_memory().

§Examples

let mut config = Config::new();
config.wasm_threads(true);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());

let shared_memory = SharedMemory::new(&engine, MemoryType::shared(1, 2))?;
let module = Module::new(&engine, r#"(module (memory (import "" "") 1 2 shared))"#)?;
let instance = Instance::new(&mut store, &module, &[shared_memory.into()])?;
// ...

Implementations§

source§

impl SharedMemory

source

pub fn new(engine: &Engine, ty: MemoryType) -> Result<Self>

Available on crate feature threads only.

Construct a SharedMemory by providing both the minimum and maximum number of 64K-sized pages. This call allocates the necessary pages on the system.

source

pub fn ty(&self) -> MemoryType

Return the type of the shared memory.

source

pub fn size(&self) -> u64

Returns the size, in WebAssembly pages, of this wasm memory.

source

pub fn page_size(&self) -> u32

Returns the size of a page, in bytes, for this memory.

By default this is 64KiB (aka 0x10000, 2**16, 1<<16, or 65536) but the custom-page-sizes proposal allows opting into a page size of 1. Future extensions might allow any power of two as a page size.

source

pub fn data_size(&self) -> usize

Returns the byte length of this memory.

The returned value will be a multiple of the wasm page size, 64k.

For more information and examples see the documentation on the Memory type.

source

pub fn data(&self) -> &[UnsafeCell<u8>]

Return access to the available portion of the shared memory.

The slice returned represents the region of accessible memory at the time that this function was called. The contents of the returned slice will reflect concurrent modifications happening on other threads.

§Safety

The returned slice is valid for the entire duration of the lifetime of this instance of SharedMemory. The base pointer of a shared memory does not change. This SharedMemory may grow further after this function has been called, but the slice returned will not grow.

Concurrent modifications may be happening to the data returned on other threads. The UnsafeCell<u8> represents that safe access to the contents of the slice is not possible through normal loads and stores.

The memory returned must be accessed safely through the Atomic* types in the std::sync::atomic module. Casting to those types must currently be done unsafely.

source

pub fn grow(&self, delta: u64) -> Result<u64>

Grows this WebAssembly memory by delta pages.

This will attempt to add delta more pages of memory on to the end of this Memory instance. If successful this may relocate the memory and cause Memory::data_ptr to return a new value. Additionally any unsafely constructed slices into this memory may no longer be valid.

On success returns the number of pages this memory previously had before the growth succeeded.

§Errors

Returns an error if memory could not be grown, for example if it exceeds the maximum limits of this memory. A ResourceLimiter is another example of preventing a memory to grow.

source

pub fn atomic_notify(&self, addr: u64, count: u32) -> Result<u32, Trap>

Equivalent of the WebAssembly memory.atomic.notify instruction for this shared memory.

This method allows embedders to notify threads blocked on the specified addr, an index into wasm linear memory. Threads could include wasm threads blocked on a memory.atomic.wait* instruction or embedder threads blocked on SharedMemory::atomic_wait32, for example.

The count argument is the number of threads to wake up.

This function returns the number of threads awoken.

§Errors

This function will return an error if addr is not within bounds or not aligned to a 4-byte boundary.

source

pub fn atomic_wait32( &self, addr: u64, expected: u32, timeout: Option<Duration>, ) -> Result<WaitResult, Trap>

Equivalent of the WebAssembly memory.atomic.wait32 instruction for this shared memory.

This method allows embedders to block the current thread until notified via the memory.atomic.notify instruction or the SharedMemory::atomic_notify method, enabling synchronization with the wasm guest as desired.

The expected argument is the expected 32-bit value to be stored at the byte address addr specified. The addr specified is an index into this linear memory.

The optional timeout argument is the maximum amount of time to block the current thread. If not specified the thread may sleep indefinitely.

This function returns one of three possible values:

  • WaitResult::Ok - this function, loaded the value at addr, found it was equal to expected, and then blocked (all as one atomic operation). The thread was then awoken with a memory.atomic.notify instruction or the SharedMemory::atomic_notify method.
  • WaitResult::Mismatch - the value at addr was loaded but was not equal to expected so the thread did not block and immediately returned.
  • WaitResult::TimedOut - all the steps of Ok happened, except this thread was woken up due to a timeout.

This function will not return due to spurious wakeups.

§Errors

This function will return an error if addr is not within bounds or not aligned to a 4-byte boundary.

source

pub fn atomic_wait64( &self, addr: u64, expected: u64, timeout: Option<Duration>, ) -> Result<WaitResult, Trap>

Equivalent of the WebAssembly memory.atomic.wait64 instruction for this shared memory.

For more information see SharedMemory::atomic_wait32.

§Errors

Returns the same error as SharedMemory::atomic_wait32 except that the specified address must be 8-byte aligned instead of 4-byte aligned.

Trait Implementations§

source§

impl Clone for SharedMemory

source§

fn clone(&self) -> SharedMemory

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for SharedMemory

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<SharedMemory> for Extern

source§

fn from(r: SharedMemory) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

source§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.