TExcelTAD
Home › WebAssembly › Tables & call_indirect

Tables & call_indirect

call $f always calls the same function, fixed when the module is compiled. But C function pointers, C++ virtual methods, Rust trait objects and JavaScript-style callbacks need to decide at runtime which function to call. WebAssembly solves this with tables.

A table is an array of references (here: references to functions). Code can't see function addresses; it only holds a table index, and call_indirect calls whatever function sits at that index, after checking its type.

text
table $ops:   index 0     index 1     index 2     index 3
             ┌─────────┬───────────┬───────────┬──────────┐
             │ $add    │ $subtract │ $multiply │ (null)   │
             └─────────┴───────────┴───────────┴──────────┘

Declaring and filling a table

text
(table $ops 4 funcref)                      ;; 4 slots of function references, initially null
(elem (i32.const 0) $add $subtract)          ;; active element segment: fill slots 0 and 1

An element segment is to tables what a data segment is to memory.

call_indirect

call_indirect (type $sig) pops a table index (the last operand) and calls the function there with the arguments below it. The type tells the validator what the call site expects:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (type $binop (func (param i32 i32) (result i32)))

  (func $add      (type $binop) (i32.add (local.get 0) (local.get 1)))
  (func $subtract (type $binop) (i32.sub (local.get 0) (local.get 1)))
  (func $multiply (type $binop) (i32.mul (local.get 0) (local.get 1)))

  (table $ops 4 funcref)
  (elem (table $ops) (i32.const 0) func $add $subtract $multiply)

  ;; apply operation number $op to a and b
  (func $apply (param $op i32) (param $a i32) (param $b i32) (result i32)
    (call_indirect $ops (type $binop) (local.get $a) (local.get $b) (local.get $op)))

  (func (export "main")
    (call $log (call $apply (i32.const 0) (i32.const 12) (i32.const 3)))
    (call $log (call $apply (i32.const 1) (i32.const 12) (i32.const 3)))
    (call $log (call $apply (i32.const 2) (i32.const 12) (i32.const 3)))))
15
9
36

$apply doesn't know which function it calls. That's exactly how C compiles int (*op)(int, int): the "function pointer" is just a table index.

Safety checks

Indirect calls are checked at runtime, so a bad index or a mismatched signature can't do damage. They trap:

Problem Trap message (V8)
index ≥ table size table index is out of bounds
slot is null null function or function signature mismatch
function has a different type null function or function signature mismatch
wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (type $binop (func (param i32 i32) (result i32)))
  (type $unop (func (param i32) (result i32)))
  (func $negate (type $unop) (i32.sub (i32.const 0) (local.get 0)))
  (table 4 funcref)
  (elem (i32.const 0) $negate)
  (func (export "main")
    (call $log (call_indirect (type $unop) (i32.const 5) (i32.const 0)))                ;; ok: -5
    (call $log (call_indirect (type $binop) (i32.const 5) (i32.const 6) (i32.const 0)))))  ;; wrong type
-5
RuntimeError: null function or function signature mismatch

This check is what makes it impossible to call a function with the wrong number or types of arguments, a classic exploit technique in native code.

A dispatch table: a tiny interpreter

Tables make dispatch easy. Here is a mini calculator that runs a "program" of opcodes stored in memory. Each opcode is used as a table index:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (memory 1)
  (type $op (func (param i32 i32) (result i32)))
  (func $add (type $op) (i32.add (local.get 0) (local.get 1)))
  (func $sub (type $op) (i32.sub (local.get 0) (local.get 1)))
  (func $mul (type $op) (i32.mul (local.get 0) (local.get 1)))
  (func $max (type $op)
    (select (local.get 0) (local.get 1) (i32.gt_s (local.get 0) (local.get 1))))
  (table 4 funcref)
  (elem (i32.const 0) $add $sub $mul $max)

  ;; program: pairs of (opcode, operand) bytes, starting value 1
  ;; add 4, mul 6, sub 2, max 50, mul 2   =>  ((1+4)*6-2) = 28, max(28,50) = 50, *2 = 100
  (data (i32.const 0) "\00\04\02\06\01\02\03\32\02\02")

  (func (export "main")
    (local $acc i32) (local $pc i32)
    (local.set $acc (i32.const 1))
    (loop $step
      (local.set $acc
        (call_indirect (type $op)
          (local.get $acc)
          (i32.load8_u offset=1 (local.get $pc))     ;; operand
          (i32.load8_u (local.get $pc))))           ;; opcode = table index
      (call $log (local.get $acc))
      (local.set $pc (i32.add (local.get $pc) (i32.const 2)))
      (br_if $step (i32.lt_u (local.get $pc) (i32.const 10))))))
5
30
28
50
100

Changing tables at runtime

With the reference-types feature (WebAssembly 2.0), tables can be read and modified by code:

Instruction Meaning
table.get $t / table.set $t read/write a slot
table.size $t / table.grow $t size in slots; grow (returns old size or -1)
table.fill $t / table.copy / table.init bulk operations, like their memory counterparts
ref.func $f a reference to function $f (must be declared in an element segment)
wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (type $unop (func (param i32) (result i32)))
  (func $double (type $unop) (i32.mul (local.get 0) (i32.const 2)))
  (func $square (type $unop) (i32.mul (local.get 0) (local.get 0)))
  (table $handlers 1 funcref)
  (elem declare func $double $square)          ;; allows ref.func on these

  (func $run (param $x i32) (result i32)
    (call_indirect $handlers (type $unop) (local.get $x) (i32.const 0)))

  (func (export "main")
    (table.set $handlers (i32.const 0) (ref.func $double))
    (call $log (call $run (i32.const 7)))
    (table.set $handlers (i32.const 0) (ref.func $square))   ;; swap the handler
    (call $log (call $run (i32.const 7)))
    (call $log (table.grow $handlers (ref.null func) (i32.const 3)))   ;; old size
    (call $log (table.size $handlers))))
14
49
1
4

The host can do the same through WebAssembly.Table (see Memory, Table & Global from JS), which is how dynamic linking and plugin systems add functions after instantiation.

Test yourself

What does call_indirect use to find the function it calls?

  1. A memory address
  2. An index into a table, popped from the stack
  3. The function's name
  4. A global

What happens when call_indirect finds a function of a different type than expected?

  1. Arguments are converted
  2. It traps
  3. It calls it anyway
  4. Validation fails

What fills a table at instantiation, just as a data segment fills memory?

  1. A global
  2. An element segment (elem)
  3. A start function
  4. A type section