init: Wasm memory instruction
The memory.init memory instruction manually copies the bytes from a passive data definition into a memory.
Try it
(module
(memory (export "memory") 1)
(data $greeting "Hello World")
(func (export "init")
i32.const 0 ;; destination offset in memory
i32.const 0 ;; offset into the data segment
i32.const 11 ;; number of bytes to copy
memory.init $greeting
data.drop $greeting
)
)
WebAssembly.instantiateStreaming(fetch("{%wasm-url%}")).then((result) => {
result.instance.exports.init();
const memBuffer = result.instance.exports.memory.buffer;
const memArray = new Uint8Array(memBuffer, 0, 11);
console.log(new TextDecoder().decode(memArray));
});
In the above example, we specify a data definition with the identifier $greeting, containing the string "Hello World". In the init() function, the data segment is written to memory using the memory.init instruction; we then drop the data segment using data.drop, as it is no longer needed.
In the JavaScript, we call the exported init() function to write the data definition into memory, then decode the exported memory buffer and log the result to the console.
Syntax
memory.init memory_identifier data_identifier
memory.init-
The
memory.initinstruction type. Must always be included first. memory_identifierOptional-
The identifier for the
memoryyou want to copy thedatainto. This can be one of the following:name-
An identifying name set for the
memorywhen it was first defined. This must begin with a$symbol, for example$my_mem. index-
The
memory's index number, for example0for the firstmemoryin the wasm module,1for the second, etc.
If omitted,
memory_identifierdefaults to0. data_identifier-
The identifier for the
datadefinition you want to copy data from. This can be one of the following:name-
An identifying name set for the
datawhen it was first defined. This must begin with a$symbol, for example$my_data. index-
The
data's index number, for example0for the firstdatain the wasm module,1for the second, etc.
Type
[dest_offset source_offset length] -> []
dest_offset-
An integer representing the offset to start writing the copied data to, in the destination memory. This will be an
i32or ani64, to match theaddress_typethememorywas defined with. source_offset-
An
i32representing the byte offset in thedatasegment to start reading data from. length-
An
i32representing the number of bytes to copy.
Traps
The memory.init instruction traps if:
- The
dest_offsetplus thelengthexceeds the size of thememory. - The
source_offsetplus thelengthexceeds the size of thedatasegment. - The
data.dropinstruction was previously called on thedatasegment referenced indata_identifier.
Binary encoding
| Instruction | Binary format | Example text => binary |
|---|---|---|
memory.init |
0xfc 8:u32 x:memidx x:dataidx |
memory.init 0 0 => 0xfc 0x08 0x00 0x00 |
Specifications
| Specification |
|---|
| WebAssembly Core Specification> # -hrefsyntax-instr-memorymathsfmemoryinitxy> |