Sikau

WebAssembly · Day 11 · about 40 min

Tables and indirect calls

Store function references in a table and call them by number.

Function pointers without pointers

In C you can store a function pointer in an array and call ops[i](a, b). Wasm cannot expose real addresses of code, because that would let a module jump anywhere. Instead it has a table: an array of opaque function references. You call by index, and the engine checks the index and the signature every time.

This is how C++ virtual methods, Rust trait objects and callbacks are compiled. A calculator, a menu of actions or a plugin list can all live in a table, and a bad index becomes a controlled error rather than a security hole.

Creating and filling a table

From JavaScript you create a table with new WebAssembly.Table({ element: "anyfunc", initial: 3 }). The element type anyfunc (also called funcref) means each slot holds either null or a wasm function. Slots start out empty. table.set(i, fn) fills one, table.get(i) reads it back, and table.length tells you the size.

Only functions that come from WebAssembly modules may be stored. A plain JavaScript function is rejected with a TypeError, because the engine could not verify its parameter and result types. Wrap a JS function by importing it into a tiny module first if you need it in a table.

function makeCalculator() {
  const bytes = buildModule([
    { name: "add", params: 2, body: ADD },
    { name: "sub", params: 2, body: SUB },
    { name: "mul", params: 2, body: MUL },
  ]);
  const { add, sub, mul } = new WebAssembly.Instance(new WebAssembly.Module(bytes)).exports;
  const table = new WebAssembly.Table({ element: "anyfunc", initial: 3 });
  [add, sub, mul].forEach((fn, i) => table.set(i, fn));

  return {
    call(op, a, b) {
      if (!Number.isInteger(op) || op < 0 || op >= table.length) throw new Error(`No such operation: ${op}`);
      return table.get(op)(a, b); // an "indirect call": look the function up by number
    },
    register(fn) {
      const index = table.grow(1); // returns the old length = the new slot
      table.set(index, fn);        // TypeError unless fn is a wasm function
      return index;
    },
  };
}

The rest of this lesson

  • What the engine checksexplain
  • Read an empty slotpredict
  • Dispatch a call by indexorder
  • Tables and callsmatch
  • Build a dispatch tablewrite code
  • Badge quizquiz
  • What you learnedrecap