TExcelTAD
Home › WebAssembly › Memory, Table & Global from JS

Memory, Table & Global from JS

Memories, tables and globals aren't only created inside modules. JavaScript can create them with constructors, pass them in as imports, and read or change them while the module runs. This is how a host sets up shared state, and how several modules can share one memory.

Constructor Key members
new WebAssembly.Memory({ initial, maximum?, shared? }) .buffer (an ArrayBuffer), .grow(pages)
new WebAssembly.Table({ element: 'anyfunc' | 'externref', initial, maximum? }) .get(i), .set(i, v), .grow(n), .length
new WebAssembly.Global({ value: 'i32' | 'i64' | 'f32' | 'f64' | …, mutable? }, init) .value

The module for this lesson

All examples use one module, which imports all three kinds of object from the host:

wat
(module
  (import "env" "mem" (memory 1))
  (import "env" "counter" (global $c (mut i32)))
  (import "env" "tbl" (table 2 funcref))
  (func $fortytwo (result i32) i32.const 42)
  (elem (i32.const 0) $fortytwo)                     ;; puts $fortytwo into tbl[0]
  (func (export "inc") (global.set $c (i32.add (global.get $c) (i32.const 1))))
  (func (export "firstByte") (result i32) (i32.load8_u (i32.const 0)))
  (func (export "grow") (param i32) (result i32) (memory.grow (local.get 0))))

Memory, Global and Table together

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  // type section: ()->i32, ()->(), (i32)->i32
  0x01, 0x0d, 0x03, 0x60, 0x00, 0x01, 0x7f, 0x60, 0x00, 0x00, 0x60, 0x01, 0x7f, 0x01, 0x7f,
  // import section: env.mem (memory, min 1), env.counter (mutable i32 global), env.tbl (funcref table, min 2)
  0x02, 0x27, 0x03,
  0x03, 0x65, 0x6e, 0x76, 0x03, 0x6d, 0x65, 0x6d, 0x02, 0x00, 0x01,
  0x03, 0x65, 0x6e, 0x76, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x03, 0x7f, 0x01,
  0x03, 0x65, 0x6e, 0x76, 0x03, 0x74, 0x62, 0x6c, 0x01, 0x70, 0x00, 0x02,
  // function section: 4 functions
  0x03, 0x05, 0x04, 0x00, 0x01, 0x00, 0x02,
  // export section: inc = 1, firstByte = 2, grow = 3
  0x07, 0x1a, 0x03, 0x03, 0x69, 0x6e, 0x63, 0x00, 0x01,
  0x09, 0x66, 0x69, 0x72, 0x73, 0x74, 0x42, 0x79, 0x74, 0x65, 0x00, 0x02,
  0x04, 0x67, 0x72, 0x6f, 0x77, 0x00, 0x03,
  // element section: table 0 at offset 0 gets function 0
  0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01, 0x00,
  // code section
  0x0a, 0x1f, 0x04,
  0x04, 0x00, 0x41, 0x2a, 0x0b,                                     // i32.const 42
  0x09, 0x00, 0x23, 0x00, 0x41, 0x01, 0x6a, 0x24, 0x00, 0x0b,       // counter += 1
  0x07, 0x00, 0x41, 0x00, 0x2d, 0x00, 0x00, 0x0b,                   // i32.load8_u at 0
  0x06, 0x00, 0x20, 0x00, 0x40, 0x00, 0x0b,                         // memory.grow
]);

const mem = new WebAssembly.Memory({ initial: 1, maximum: 4 });
const counter = new WebAssembly.Global({ value: 'i32', mutable: true }, 10);
const tbl = new WebAssembly.Table({ element: 'anyfunc', initial: 2 });

const { instance } = await WebAssembly.instantiate(bytes, { env: { mem, counter, tbl } });
const { inc, firstByte } = instance.exports;

// Global: Wasm and JS see the same value
inc(); inc();
console.log('counter after 2 incs:', counter.value);
counter.value = 100;
inc();
console.log('counter after JS set + inc:', counter.value);

// Memory: JS writes, Wasm reads
new Uint8Array(mem.buffer)[0] = 77;
console.log('firstByte:', firstByte(), 'memory size:', mem.buffer.byteLength);

// Table: the element segment put a Wasm function in slot 0
console.log('tbl[0]():', tbl.get(0)(), 'tbl[1]:', tbl.get(1), 'length:', tbl.length);
tbl.set(1, inc);                          // store an exported function in the table
tbl.get(1)();
console.log('counter via table:', counter.value);
counter after 2 incs: 12
counter after JS set + inc: 101
firstByte: 77 memory size: 65536
tbl[0](): 42 tbl[1]: null length: 2
counter via table: 102

Memory growth detaches old buffers

When memory grows, either from JS (mem.grow(n)) or from Wasm (memory.grow), the old ArrayBuffer is detached: its length becomes 0 and every typed array on it becomes empty. Always take a fresh mem.buffer after anything that may grow memory:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x0d, 0x03, 0x60, 0x00, 0x01, 0x7f, 0x60, 0x00, 0x00, 0x60, 0x01, 0x7f, 0x01, 0x7f,
  0x02, 0x27, 0x03,
  0x03, 0x65, 0x6e, 0x76, 0x03, 0x6d, 0x65, 0x6d, 0x02, 0x00, 0x01,
  0x03, 0x65, 0x6e, 0x76, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x03, 0x7f, 0x01,
  0x03, 0x65, 0x6e, 0x76, 0x03, 0x74, 0x62, 0x6c, 0x01, 0x70, 0x00, 0x02,
  0x03, 0x05, 0x04, 0x00, 0x01, 0x00, 0x02,
  0x07, 0x1a, 0x03, 0x03, 0x69, 0x6e, 0x63, 0x00, 0x01,
  0x09, 0x66, 0x69, 0x72, 0x73, 0x74, 0x42, 0x79, 0x74, 0x65, 0x00, 0x02,
  0x04, 0x67, 0x72, 0x6f, 0x77, 0x00, 0x03,
  0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01, 0x00,
  0x0a, 0x1f, 0x04, 0x04, 0x00, 0x41, 0x2a, 0x0b, 0x09, 0x00, 0x23, 0x00, 0x41, 0x01, 0x6a, 0x24, 0x00, 0x0b,
  0x07, 0x00, 0x41, 0x00, 0x2d, 0x00, 0x00, 0x0b, 0x06, 0x00, 0x20, 0x00, 0x40, 0x00, 0x0b,
]);
const mem = new WebAssembly.Memory({ initial: 1, maximum: 4 });
const env = {
  mem,
  counter: new WebAssembly.Global({ value: 'i32', mutable: true }, 0),
  tbl: new WebAssembly.Table({ element: 'anyfunc', initial: 2 }),
};
const { instance } = await WebAssembly.instantiate(bytes, { env });

const view = new Uint8Array(mem.buffer);
view[0] = 9;
console.log('before:', view.length, 'bytes');

console.log('wasm grow returned', instance.exports.grow(1));      // old size in pages
console.log('old view now:', view.length, 'bytes');                // detached!

const fresh = new Uint8Array(mem.buffer);
console.log('fresh view:', fresh.length, 'bytes, first byte', fresh[0]);

console.log('JS grow returned', mem.grow(2), '->', mem.buffer.byteLength / 65536, 'pages');
console.log('over the maximum:', instance.exports.grow(5));
try {
  mem.grow(5);
} catch (err) {
  console.log(err.constructor.name);
}
before: 65536 bytes
wasm grow returned 1
old view now: 0 bytes
fresh view: 131072 bytes, first byte 9
JS grow returned 2 -> 4 pages
over the maximum: -1
RangeError

From Wasm, failure is -1; from JavaScript, Memory.grow beyond the maximum throws a RangeError.

Globals of other types

WebAssembly.Global supports every value type. An i64 global's value is a BigInt, and an immutable global can't be changed from JS either:

js · try it yourself
const big = new WebAssembly.Global({ value: 'i64', mutable: true }, 5n);
big.value = big.value * 1_000_000_000_000n;
console.log(big.value, typeof big.value);

const ratio = new WebAssembly.Global({ value: 'f32' }, 0.1);
console.log(ratio.value);                    // rounded to single precision

try {
  ratio.value = 1;
} catch (err) {
  console.log(err.constructor.name);
}
console.log(new WebAssembly.Global({ value: 'i32' }, 4.9).value);   // ToInt32
5000000000000n bigint
0.10000000149011612
TypeError
4

Typical uses

  • Shared memory between modules: two modules import the same Memory, so data written by one is visible to the other (dynamic linking in Emscripten works like this).
  • Plug-ins: the host keeps a Table and adds functions from several modules to it, so they can call each other through call_indirect.
  • Configuration: immutable imported globals (e.g. a stack base or a feature flag) set by the host before instantiation.

Test yourself

What happens to existing typed arrays when a memory grows?

  1. They grow too
  2. They keep working on the old size
  3. Their ArrayBuffer is detached and they become empty
  4. They throw on every access

How do you read a Wasm global from JavaScript?

  1. global.get()
  2. global.value
  3. instance.globals[0]
  4. You can't

What does mem.grow(n) do in JS when it would exceed the maximum?

  1. Returns -1
  2. Throws a RangeError
  3. Grows to the maximum
  4. Ignores the maximum