wasm_memory (wasm v0.16.0)

View Source

Linear memory backed by chunked atomics arrays.

You reach this through wasm:read_memory/3 and wasm:write_memory/3; read the module itself when you want to know what a store costs you. The representation is the one the benchmarks chose. Per store, on this machine:

  atomics, raw 64-bit word        6.1 ns
  atomics, masked i32 store      22.1 ns
  ETS, one row per word          41.6 ns
  ETS, 4 KB chunk rebuild       278   ns
  binary rebuild, 64 KiB       1201   ns

Binaries are immutable, so every store rebuilds the whole page. At 1.2 us per store they are unusable as mutable memory however good they are at reads. atomics is mutable in place, and it is an OTP built-in resource rather than a NIF this project ships, so linear memory needs no native code of its own to be viable. That is the single biggest reason a pure-Erlang runtime is practical at all.

Where things are

you wantlook at
a new memory, standalone or for an instancenew/1, new/2, new_shared/1, create/2, create/4
how large a chunk ischunk_shift/1, single_chunk_shift/2
releasing a memory, and adding a holderfree/1, acquire/3, release/2
memory.growgrow/2, extend/3
scalar loads and storesload/3, store/4
atomic access and cmpxchgatomic_load/3, atomic_store/4, atomic_rmw/5, atomic_cmpxchg/5
byte ranges, as wasm:read_memory/3 uses themload_bytes/3, store_bytes/3, to_binary/1
memory.fill, memory.copy, memory.initfill/4, copy/4, copy/5, init/5
restoring over an image without copying itwith_image/4
the first write to an image pageensure_private/2, fault/2
capturing a memory as an imageimage/1

How it is built

Chunking. Memory is a tuple of atomics arrays, so memory.grow appends a chunk instead of reallocating and copying. A single flat array would make growth O(size), and growing to 64 MiB one page at a time would copy about a thousand times more than it allocates. A chunk is sized to the memory's initial size, between one 64 KiB page and 1 MiB, rounded up to a power of two (chunk_shift/1), so a one-page module does not pay for a megabyte. A memory that can never grow, because its maximum is its size, is one chunk when that size is a power of two above 1 MiB (single_chunk_shift/2): nothing is ever appended to it, and compiled code then reaches all of it through one cache entry.

Restored memories. A memory restored from a snapshot image does not copy the image. Its lower region reads the image's immutable 64 KiB binaries, shared by every memory restored from it, through a page table with one entry per 4 KiB page. The first write to such a page copies those 4 KiB into a private slot in an arena of atomics chunks and records the slot in the table; later accesses go to the slot. Addresses above the image region use ordinary chunks. docs/snapshots.md has the user's side.

Alignment. atomics granularity is 64 bits, so an aligned i64 store is one put while an i32 store is a read-modify-write. Accesses that span two words take a slower path again. The value is assembled little-endian because that is what WebAssembly specifies, independent of host byte order.

Accounting. atomics memory is off-heap and invisible to max_heap_size, so every page is reserved before it is allocated. Without that, a module could exhaust your node without its owning process's heap ever growing. Reserving, growing and releasing are wasm_keeper transactions, which is also what records who holds the memory and releases it when they are all gone.

Summary

Functions

Add a holder to this memory, for an instance importing it.

Replace the value at Addr only if it is Expected, answering what was there.

Apply Fun to the value at Addr indivisibly, answering the old value.

Copy between two distinct memories.

Create a memory, saying who holds it and whether its size is observable.

Where each field of a memory handle lives, by index.

Whether a write of Nbytes at Addr would be in bounds, as a value.

Release this handle's claim on the memory.

Grow by Delta pages, returning the previous size.

A stable identity for this memory, for keying the wait queue.

The memory as an image: one immutable binary per 64 KiB page, or zero.

memory.init: copy from a passive data segment.

Whether a term is a memory handle.

Whether this memory was declared shared, which wait requires.

Load Nbytes at Addr as an unsigned little-endian integer.

Read a byte range as a binary, for host functions and WASI.

The all-ones mask for an access of N bytes.

A standalone memory, held by the calling process.

A memory whose size is visible to other instances.

ok, or {refresh, Mem} when arena chunks were published that this handle has not seen.

Remove a named holder, whatever this handle's own token is.

This memory's registry identity.

The shift of a memory of Pages pages that may grow to Max, when it is one chunk, and undefined when it is not.

Store, and answer ok, or {refresh, Mem} when the write published arena chunks this handle has not seen.

Whole-memory snapshot. Diagnostics and tests only: it materialises the entire memory as a binary.

Types

mem()

-opaque mem()

Functions

acquire/3

-spec acquire(mem(), wasm_keeper:token(), pid() | none) ->
                 ok | {error, gone | instance_limit | keeper_unavailable}.

Add a holder to this memory, for an instance importing it.

{error, gone} means the last holder released it first, which has to be a link failure rather than a memory the importer goes on to use.

atomic_cmpxchg(M, Addr, Nbytes, Expected, Replacement)

-spec atomic_cmpxchg(mem(), non_neg_integer(), 1..8, integer(), integer()) -> non_neg_integer().

Replace the value at Addr only if it is Expected, answering what was there.

The answer is the old value either way, so a caller compares it with what it expected to find out whether the exchange happened. That is the specified interface, and it is why this cannot be built from a load and a store.

atomic_load(M, Addr, Nbytes)

-spec atomic_load(mem(), non_neg_integer(), 1..8) -> non_neg_integer().

Atomic access.

An atomic load or store is naturally aligned, which validation enforces exactly, so it never straddles two of the 64-bit words the memory is made of. That makes a load one atomics:get and an aligned eight-byte store one atomics:put.

Anything narrower is a part of a word, so writing it means reading the word, replacing a field and writing it back. That is three operations and another process can write the same word between them, so it goes through atomics:compare_exchange and retries. A read-modify-write is the same loop with the arithmetic inside it, which is what makes i32.atomic.rmw.add a single indivisible step rather than a load and a store that usually work.

atomic_rmw(M, Addr, Nbytes, Op, Operand)

-spec atomic_rmw(mem(), non_neg_integer(), 1..8, atom(), integer()) -> non_neg_integer().

Apply Fun to the value at Addr indivisibly, answering the old value.

atomic_store/4

-spec atomic_store(mem(), non_neg_integer(), 1..8, integer()) -> ok.

copy(M, Dst, Src, Len)

-spec copy(mem(), non_neg_integer(), non_neg_integer(), non_neg_integer()) -> ok.

copy(DstMem, Dst, SrcMem, Src, Len)

-spec copy(mem(), non_neg_integer(), mem(), non_neg_integer(), non_neg_integer()) -> ok.

Copy between two distinct memories.

There is no overlap to worry about, so the source range is read out as one binary and written back as one binary. Both ranges are bounds-checked before anything is written, which is what the specification requires: a memory.copy that traps must leave the destination untouched.

A zero-length copy is checked too. Returning early on Len = 0 looks harmless and is not: the specification admits an address exactly at the end of a memory and requires a trap one byte beyond it, whatever the length. The same-memory copy/4 above already checks before it looks at the length, and memory_copy1.wast asserts both directions.

create/2

-spec create(#limits{min :: non_neg_integer(),
                     max :: undefined | non_neg_integer(),
                     shared :: boolean(),
                     index_type :: i32 | i64},
             map()) ->
                {ok, mem()} | {error, term()}.

Create a memory, saying who holds it and whether its size is observable.

observable is the linking sense: another instance can see this memory grow, so its size and chunk tuple are published rather than kept in the handle. holder is a {Token, Owner} pair naming the registry entry to create and the process whose death removes it; leave it out and the memory belongs to the calling process, or to nobody at all if it is thread-shared.

field_indices()

-spec field_indices() -> #{atom() => pos_integer()}.

Where each field of a memory handle lives, by index.

Generated code reads a handle directly rather than calling in for every access, so it needs these, and a header of literals that silently disagreed with the record would corrupt memory rather than fail. wasm_core_SUITE asserts this answer equals include/wasm_memory.hrl, so adding a field breaks a test.

fill(M, Addr, Byte, Len)

-spec fill(mem(), non_neg_integer(), byte(), non_neg_integer()) -> ok.

fits(M, Addr, Nbytes)

-spec fits(mem(), non_neg_integer(), non_neg_integer()) -> boolean().

Whether a write of Nbytes at Addr would be in bounds, as a value.

For a caller that has to make the specification's bounds decision without performing the write. wasm_instance uses it to keep an active data segment's instantiation-time trap when a restore is about to overwrite whatever the segment would have written.

free/1

-spec free(mem()) -> ok.

Release this handle's claim on the memory.

Idempotent, and safe to call on a handle that holds no claim: a memory an instance created or imported is released by destroying that instance, so free/1 on a handle you got from wasm:extern/2 does nothing rather than pulling the memory out from under it.

The pages that go back are the size the memory is now, taken from the registry, not the size this handle was made at. A grown memory used to return only its original pages and leave the rest charged for the life of the node.

grow/2

-spec grow(mem(), non_neg_integer()) -> {ok, non_neg_integer(), mem()} | {error, term()}.

Grow by Delta pages, returning the previous size.

Returns {error, _} rather than trapping: memory.grow is specified to push -1 on failure, so refusal is a value the module observes, not a fault.

Growth is serialised per memory, in two stages. The keeper validates the request against the authoritative size, reserves the budget and hands out the right to grow; the caller allocates the chunks, which is the expensive half and so must not happen inside the serialised callback; the keeper then publishes the chunk tuple and the new size together.

Two agents growing one shared memory used to each build a tuple from its own view and publish both cells independently, so one could publish a size backed by the other's shorter tuple. A single compare-and-exchange cannot fix that, because there are two cells to move.

id/1

-spec id(mem()) -> term().

A stable identity for this memory, for keying the wait queue.

Two handles on the same shared memory must agree, and a private memory must not collide with anyone. The registry identity is both: minted once per memory and copied into every handle on it.

image(M)

-spec image(mem()) -> tuple().

The memory as an image: one immutable binary per 64 KiB page, or zero.

A page of the image no write reached is the image's own binary, shared rather than copied; every other page is read into a binary of its own. Nothing in the answer refers to an array, so it cannot change when the memory does.

init(M, Dst, Segment, SrcOff, Len)

-spec init(mem(), non_neg_integer(), binary(), non_neg_integer(), non_neg_integer()) -> ok.

memory.init: copy from a passive data segment.

is_mem/1

-spec is_mem(term()) -> boolean().

Whether a term is a memory handle.

Needed because an embedder hands over bare terms: a module importing a memory may be given a table, a function or a number, and that has to come back as a link error rather than as a function_clause from inside the runtime.

is_shared/1

-spec is_shared(mem()) -> boolean().

Whether this memory was declared shared, which wait requires.

limits/1

-spec limits(mem()) ->
                #limits{min :: non_neg_integer(),
                        max :: undefined | non_neg_integer(),
                        shared :: boolean(),
                        index_type :: i32 | i64}.

load(M, Addr, Nbytes)

-spec load(mem(), non_neg_integer(), 1..8) -> non_neg_integer().

Load Nbytes at Addr as an unsigned little-endian integer.

Bounds are checked against the whole access, and the addition is done in Erlang's arbitrary-precision integers, so an offset near 2^32 cannot wrap around into a valid address the way it would in C.

load_bytes(M, Addr, Len)

-spec load_bytes(mem(), non_neg_integer(), non_neg_integer()) -> binary().

Read a byte range as a binary, for host functions and WASI.

Costs one atomics:get for each 64-bit word the range touches, because the bytes have to be assembled from atomic words. A range that does not start or end on a word costs a word at each end, not a read per byte.

mask/1

-spec mask(pos_integer()) -> non_neg_integer().

The all-ones mask for an access of N bytes.

Exported because wasm_core needs it at generation time to build the same mask into compiled code, and one table of widths is the point: see wasm_exec:load_spec/1, which is read the same way and for the same reason.

new/1

-spec new(non_neg_integer() |
          #limits{min :: non_neg_integer(),
                  max :: undefined | non_neg_integer(),
                  shared :: boolean(),
                  index_type :: i32 | i64}) ->
             {ok, mem()} | {error, term()}.

A standalone memory, held by the calling process.

Observable, because a standalone memory exists to be handed to instances: two of them importing it must see each other grow it, and a handle is an immutable record that cannot learn a new size on its own. Only a memory an instance defined and neither imports nor exports keeps its size in the handle, which is the case the fast path was measured for.

new(Pages, Max)

-spec new(non_neg_integer(), undefined | non_neg_integer()) -> {ok, mem()} | {error, term()}.

new_shared(Limits)

-spec new_shared(#limits{min :: non_neg_integer(),
                         max :: undefined | non_neg_integer(),
                         shared :: boolean(),
                         index_type :: i32 | i64}) ->
                    {ok, mem()} | {error, term()}.

A memory whose size is visible to other instances.

Used for a memory that is imported or exported: growing it through one handle has to be seen through all of them, and the handle is an immutable record.

refresh/1

-spec refresh(mem()) -> ok | {refresh, mem()}.

ok, or {refresh, Mem} when arena chunks were published that this handle has not seen.

Any write can publish them, through this handle or another one on the same memory: a bulk operation, a host function, wasm:write_memory/3. A handle that has not seen a chunk still reads it correctly, through the published cell, but generated code then leaves the inline path for every access to it.

release/2

-spec release(mem(), wasm_keeper:token()) -> ok.

Remove a named holder, whatever this handle's own token is.

resource/1

-spec resource(mem()) -> wasm_keeper:resource().

This memory's registry identity.

single_chunk_shift/2

-spec single_chunk_shift(non_neg_integer(), undefined | non_neg_integer()) -> undefined | 21..32.

The shift of a memory of Pages pages that may grow to Max, when it is one chunk, and undefined when it is not.

A memory that can never grow, because its maximum is its size, is one chunk when that size is a power of two above 1 MiB and at most 4 GiB. Nothing is ever appended to it, so the reason for chunks does not apply. Compiled code then covers the whole memory with one translation cache entry: wasm_jit asks this of memory 0's declared type, and generated code uses the answer when the memory it finds has that shift (wasm_core, tag_bindings/4).

The answer is above 20, and no chunk of any other memory is: chunk_shift/1 clamps at 1 MiB. So a shift above 20 means one chunk of exactly the memory's size that nothing will ever append to, which is what generated code relies on.

size_bytes(M)

-spec size_bytes(mem()) -> non_neg_integer().

size_pages/1

-spec size_pages(mem()) -> non_neg_integer().

store(M, Addr, Nbytes, Value)

-spec store(mem(), non_neg_integer(), 1..8, integer()) -> ok.

store_bytes(M, Addr, Bin)

-spec store_bytes(mem(), non_neg_integer(), binary()) -> ok.

store_r/4

-spec store_r(mem(), non_neg_integer(), 1..8, integer()) -> ok | {refresh, mem()}.

Store, and answer ok, or {refresh, Mem} when the write published arena chunks this handle has not seen.

For the store paths that keep their handle: taking the refreshed one saves the published cell's lookup on every later access to those chunks. Ignoring it is always correct.

to_binary(M)

-spec to_binary(mem()) -> binary().

Whole-memory snapshot. Diagnostics and tests only: it materialises the entire memory as a binary.