Memory in wasmtime - Rust (original) (raw)


#[repr(C)]

pub struct Memory { /* private fields */ }

Available on crate feature runtime only.

Expand description

A WebAssembly linear memory.

WebAssembly memories represent a contiguous array of bytes that have a size that is always a multiple of the WebAssembly page size, currently 64 kilobytes.

WebAssembly memory is used for global data (not to be confused with wasmglobal items), statics in C/C++/Rust, shadow stack memory, etc. Accessing wasm memory is generally quite fast.

Memories, like other wasm items, are owned by a Store.

§Memory and Safety

Linear memory is a lynchpin of safety for WebAssembly. In Wasmtime there are safe methods of interacting with a Memory:

Note that all of these consider the entire store context as borrowed for the duration of the call or the duration of the returned slice. This largely means that while the function is running you’ll be unable to borrow anything else from the store. This includes getting access to the T onStore, but it also means that you can’t recursively call into WebAssembly for instance.

If you’d like to dip your toes into handling Memory in a more raw fashion (e.g. by using raw pointers or raw slices), then there’s a few important points to consider when doing so:

As a general rule of thumb it’s recommended to stick to the safe methods ofMemory if you can. It’s not advised to use raw pointers or unsafeoperations because of how easy it is to accidentally get things wrong.

Some examples of safely interacting with memory are:

use wasmtime::{Memory, Store, MemoryAccessError};

// Memory can be read and written safely with the `Memory::read` and
// `Memory::write` methods.
// An error is returned if the copy did not succeed.
fn safe_examples(mem: Memory, store: &mut Store<()>) -> Result<(), MemoryAccessError> {
    let offset = 5;
    mem.write(&mut *store, offset, b"hello")?;
    let mut buffer = [0u8; 5];
    mem.read(&store, offset, &mut buffer)?;
    assert_eq!(b"hello", &buffer);

    // Note that while this is safe care must be taken because the indexing
    // here may panic if the memory isn't large enough.
    assert_eq!(&mem.data(&store)[offset..offset + 5], b"hello");
    mem.data_mut(&mut *store)[offset..offset + 5].copy_from_slice(b"bye!!");

    Ok(())
}

It’s worth also, however, covering some examples of incorrect,unsafe usages of Memory. Do not do these things!

use wasmtime::{Memory, Store};

// NOTE: All code in this function is not safe to execute and may cause
// segfaults/undefined behavior at runtime. Do not copy/paste these examples
// into production code!
unsafe fn unsafe_examples(mem: Memory, store: &mut Store<()>) -> Result<()> {
    // First and foremost, any borrow can be invalidated at any time via the
    // `Memory::grow` function. This can relocate memory which causes any
    // previous pointer to be possibly invalid now.
    unsafe {
        let pointer: &u8 = &*mem.data_ptr(&store);
        mem.grow(&mut *store, 1)?; // invalidates `pointer`!
        // println!("{}", *pointer); // FATAL: use-after-free
    }

    // Note that the use-after-free also applies to slices, whether they're
    // slices of bytes or strings.
    unsafe {
        let mem_slice = std::slice::from_raw_parts(
            mem.data_ptr(&store),
            mem.data_size(&store),
        );
        let slice: &[u8] = &mem_slice[0x100..0x102];
        mem.grow(&mut *store, 1)?; // invalidates `slice`!
        // println!("{:?}", slice); // FATAL: use-after-free
    }

    // The `Memory` type may be stored in other locations, so if you hand
    // off access to the `Store` then those locations may also call
    // `Memory::grow` or similar, so it's not enough to just audit code for
    // calls to `Memory::grow`.
    unsafe {
        let pointer: &u8 = &*mem.data_ptr(&store);
        some_other_function(store); // may invalidate `pointer` through use of `store`
        // println!("{:?}", pointer); // FATAL: maybe a use-after-free
    }

    // An especially subtle aspect of accessing a wasm instance's memory is
    // that you need to be extremely careful about aliasing. Anyone at any
    // time can call `data_unchecked()` or `data_unchecked_mut()`, which
    // means you can easily have aliasing mutable references:
    unsafe {
        let ref1: &u8 = &*mem.data_ptr(&store).add(0x100);
        let ref2: &mut u8 = &mut *mem.data_ptr(&store).add(0x100);
        // *ref2 = *ref1; // FATAL: violates Rust's aliasing rules
    }

    Ok(())
}

Overall there’s some general rules of thumb when unsafely working withMemory and getting raw pointers inside of it:

At this point it’s worth reiterating again that unsafely working withMemory is pretty tricky and not recommended! It’s highly recommended to use the safe methods to interact with Memory whenever possible.

§Memory Safety and Threads

Currently the wasmtime crate does not implement the wasm threads proposal, but it is planned to do so. It may be interesting to readers to see how this affects memory safety and what was previously just discussed as well.

Once threads are added into the mix, all of the above rules still apply. There’s an additional consideration that all reads and writes can happen concurrently, though. This effectively means that any borrow into wasm memory are virtually never safe to have.

Mutable pointers are fundamentally unsafe to have in a concurrent scenario in the face of arbitrary wasm code. Only if you dynamically know for sure that wasm won’t access a region would it be safe to construct a mutable pointer. Additionally even shared pointers are largely unsafe because their underlying contents may change, so unless UnsafeCell in one form or another is used everywhere there’s no safety.

One important point about concurrency is that while Memory::grow can happen concurrently it will never relocate the base pointer. Shared memories must always have a maximum size and they will be preallocated such that growth will never relocate the base pointer. The current size of the memory may still change over time though.

Overall the general rule of thumb for shared memories is that you must atomically read and write everything. Nothing can be borrowed and everything must be eagerly copied out. This means that Memory::data andMemory::data_mut won’t work in the future (they’ll probably return an error) for shared memories when they’re implemented. When possible it’s recommended to use Memory::read and Memory::write which will still be provided.

Source§

Source

Creates a new WebAssembly memory given the configuration of ty.

The store argument will be the owner of the returned Memory. All WebAssembly memory is initialized to zero.

§Panics

This function will panic if the Store has aResourceLimiterAsync (see also:Store::limiter_async). When using an async resource limiter, use Memory::new_async instead.

§Examples
let engine = Engine::default();
let mut store = Store::new(&engine, ());

let memory_ty = MemoryType::new(1, None);
let memory = Memory::new(&mut store, memory_ty)?;

let module = Module::new(&engine, "(module (memory (import \"\" \"\") 1))")?;
let instance = Instance::new(&mut store, &module, &[memory.into()])?;
// ...

Source

Available on crate feature async only.

Source

Returns the underlying type of this memory.

§Panics

Panics if this memory doesn’t belong to store.

§Examples
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(&engine, "(module (memory (export \"mem\") 1))")?;
let instance = Instance::new(&mut store, &module, &[])?;
let memory = instance.get_memory(&mut store, "mem").unwrap();
let ty = memory.ty(&store);
assert_eq!(ty.minimum(), 1);

Source

Safely reads memory contents at the given offset into a buffer.

The entire buffer will be filled.

If offset + buffer.len() exceed the current memory capacity, then the buffer is left untouched and a MemoryAccessError is returned.

§Panics

Panics if this memory doesn’t belong to store.

Source

Safely writes contents of a buffer to this memory at the given offset.

If the offset + buffer.len() exceeds the current memory capacity, then none of the buffer is written to memory and a MemoryAccessError is returned.

§Panics

Panics if this memory doesn’t belong to store.

Source

Returns this memory as a native Rust slice.

Note that this method will consider the entire store context provided as borrowed for the duration of the lifetime of the returned slice.

§Panics

Panics if this memory doesn’t belong to store.

Source

Returns this memory as a native Rust mutable slice.

Note that this method will consider the entire store context provided as borrowed for the duration of the lifetime of the returned slice.

§Panics

Panics if this memory doesn’t belong to store.

Source

Same as Memory::data_mut, but also returns the T from theStoreContextMut.

This method can be used when you want to simultaneously work with theT in the store as well as the memory behind this Memory. UsingMemory::data_mut would consider the entire store borrowed, whereas this method allows the Rust compiler to see that the borrow of this memory and the borrow of T are disjoint.

§Panics

Panics if this memory doesn’t belong to store.

Source

Returns the base pointer, in the host’s address space, that the memory is located at.

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

§Panics

Panics if this memory doesn’t belong to store.

Source

Returns the byte length of this memory.

WebAssembly memories are made up of a whole number of pages, so the byte size returned will always be a multiple of this memory’s page size. Note that different Wasm memories may have different page sizes. You can get a memory’s page size via the Memory::page_size method.

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

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

§Panics

Panics if this memory doesn’t belong to store.

Source

Returns the size, in units of pages, of this Wasm memory.

WebAssembly memories are made up of a whole number of pages, so the byte size returned will always be a multiple of this memory’s page size. Note that different Wasm memories may have different page sizes. You can get a memory’s page size via the Memory::page_size method.

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

§Panics

Panics if this memory doesn’t belong to store.

Source

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

WebAssembly memories are made up of a whole number of pages, so the byte size (as returned by Memory::data_size) will always be a multiple of their page size. Different Wasm memories may have different page sizes.

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 of1. Future extensions might allow any power of two as a page size.

Source

Returns the log2 of this memory’s page size, in bytes.

WebAssembly memories are made up of a whole number of pages, so the byte size (as returned by Memory::data_size) will always be a multiple of their page size. Different Wasm memories may have different page sizes.

By default the page size is 64KiB (aka 0x10000, 2**16, 1<<16, or65536) 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

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.

Note that, by default, a WebAssembly memory’s page size is 64KiB (aka 65536 or 216). The custom-page-sizes proposal allows Wasm memories to opt into a page size of one byte (and this may be further relaxed to any power of two in a future extension).

§Errors

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

§Panics

Panics if this memory doesn’t belong to store.

This function will panic if the Store has aResourceLimiterAsync (see also:Store::limiter_async. When using an async resource limiter, use Memory::grow_async instead.

§Examples
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(&engine, "(module (memory (export \"mem\") 1 2))")?;
let instance = Instance::new(&mut store, &module, &[])?;
let memory = instance.get_memory(&mut store, "mem").unwrap();

assert_eq!(memory.size(&store), 1);
assert_eq!(memory.grow(&mut store, 1)?, 1);
assert_eq!(memory.size(&store), 2);
assert!(memory.grow(&mut store, 1).is_err());
assert_eq!(memory.size(&store), 2);
assert_eq!(memory.grow(&mut store, 0)?, 2);

Source

Available on crate feature async only.

§

§

§

§

§

§