wiggle::wasmtime_crate

Struct SharedMemory

pub struct SharedMemory { /* private fields */ }
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§

§

impl SharedMemory

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

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

pub fn ty(&self) -> MemoryType

Return the type of the shared memory.

pub fn size(&self) -> u64

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

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.

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.

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.

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

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.

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.

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.

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§

§

impl Clone for SharedMemory

§

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
§

impl Debug for SharedMemory

§

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

Formats the value using the given formatter. Read more
§

impl From<SharedMemory> for Extern

§

fn from(r: SharedMemory) -> Extern

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 u8)

🔬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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Pointee for T

Source§

type Pointer = u32

Source§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_>, ) -> Result<(), Error>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more