Architecture

View Source

This page is the map of the runtime: what the hundred and three modules are, which ones depend on which, and where to start reading. Read it before you change anything. Each module documents itself, but no module describes how they fit together.

Everything here is computed from the compiled modules, not written from memory, and test/wasm_architecture_SUITE.erl computes it again on every test run. If this page and the code disagree, that suite fails.

Where to start reading

Read in this order. You can understand each step if you have read the steps before it.

  1. wasm is the front door. Every public operation is here, and each one is a few lines that delegate. Read it to learn the vocabulary: module, instance, extern, limits.
  2. wasm_decode turns bytes into a #module{}. Start at module/1 and follow one section.
  3. wasm_validate decides whether that module is well typed. wasm_validate_code is where the operand stack lives.
  4. wasm_instance turns a validated module into something executable. This is where imports get resolved and memories, tables and globals get created.
  5. wasm_exec is the interpreter. Go to the dispatch section and read three or four instructions.
  6. wasm_jit and wasm_core are the compiled tier. Read the compiled tier first, then its internals and wasm_jit:entry/3.

wasi_preview1 is a separate part that sits on top of all of this. You can ignore it unless you are working on WASI.

Where things are

Where things are has the rest of the map: every directory and module with what it does, and for each area of the runtime its entry point, modules, configuration, extension point, suites and page. Start there when you know what you want to change but not where it lives.

The supervision tree

This is what application:ensure_all_started(wasm) starts. Each subsystem has its own supervisor. So a subsystem that keeps crashing uses up only its own restart limit, not the limit of the others. The wasm_sup module doc says why.

wasm_sup                one_for_one
  +-- wasm_store_sup    the long-lived ETS tables          wasm_store
  +-- wasm_engine_sup   the node-wide page budget          wasm_engine
  +-- wasm_keeper_sup   who holds each shared resource     wasm_keeper
  +-- wasm_code_sup     generated code, the compilers      wasm_code_slots, wasm_jit_sup
  +-- wasm_cache_sup    modules by content hash, and       wasm_module_cache,
                        the images workers share           wasm_worker_images
  +-- wasm_actor_sup    forgets an actor that died         wasm_actor_registry
  +-- wasm_worker_sup   request cleanup for workers        wasm_cleanup_steward_sup,
                                                           wasm_cleanup_manager,
                                                           wasm_worker_reaper

There is no instance supervisor. An instance belongs to the process that made it, and your application decides what shape those processes take.

The layers

This map is for changing the runtime, not for using it. A level says which modules a module may call. It says nothing about how you use them. If you run WebAssembly and do not change the runtime, start at Getting started instead.

There are twelve levels (L0 to L11), computed from the code and not drawn by hand. A module sits one level above the highest module it calls. The modules of each of the four cycles below share one level. So a module only ever calls downward, and level 0 depends on nothing else in the project: you can start reading there and understand it completely. The worker modules, in src/worker/, sit on top of the runtime they use: the adapters at L10, the kernel below them.

The folders follow the same split. src/ is the core runtime: the front end, instances, the interpreter, memory, snapshots and the compiled tier. src/component/ is the Component Model, src/wasi/ is WASI preview 1, 0.2 with HTTP, and 0.3, and src/worker/ is the workers. A folder is for finding a module, not a namespace: names stay wasm_* and wasi_*.

L11 wasi_http_listener
L10 wasm_javascript  wasm_javascript_command  wasm_python
    wasm_python_command  wasm_lua  wasm_adapter_conformance  wasi_preview3
    wasi_p3_filesystem  wasi_p3_sockets  wasi_p3_http
L9  wasi  wasm_script_worker  wasm_actor  wasi_preview2  wasi_p2_filesystem  wasi_p2_sockets
    wasi_http  wasi_http_transport  wasi_http_h1  wasi_http_h2  wasi_nn
L8  wasi_preview1  wasm_snapshot_store  wasm_instance_worker
    wasm_component  wasm_component_link  wasm_canon  wasm_async  wasm_component_types
    wasm_worker_images
L7  wasm  wasm_module_cache  wasm_snapshot_owner  wasm_jit_sup
L6  wasm_exec  wasm_core  wasm_jit  wasm_snapshot
L5  wasm_instance  wasm_wat
L4  wasm_validate  wasm_wat_instr  wasm_encode  wasm_encode_code
    wasm_encode_simd  wasm_encode_gc  wasm_encode_atomic
L3  wasm_memory  wasm_table  wasm_global  wasm_heap  wasm_store
    wasm_validate_code  wasm_wast  wasm_worker_sup
L2  wasm_decode  wasm_decode_code  wasm_decode_simd  wasm_decode_gc
    wasm_decode_atomic  wasm_keeper  wasm_simd  wasm_types  wasm_wait
    wasm_wat_sexp  wasm_app  wasm_cleanup_manager  wasm_cleanup_steward
L1  wasm_code_cache  wasm_engine  wasm_leb128  wasm_num_float
    wasm_num_trunc  wasm_sup  wasm_wat_lex  wasm_wat_num  wasi_fs  wasi_sock
    wasm_worker_reaper  wasm_script_v1  wasm_cleanup_steward_sup
L0  wasm_error  wasm_num  wasm_limits  wasm_code_slots  wasm_file_cache
    wasm_snapshot_file  wasm_subsup  wasm_validate_simd  wasm_validate_atomic
    wasi_path  wasi_net  wasi_sock2  wasi_file_nif  wasm_worker_error
    wasm_worker_adapter  wasm_recipe  wasm_worker_fs  wasm_resources
    wasm_lifetime  wasm_actor_registry  wasm_unit_file

test/wasm_architecture_SUITE.erl asserts that this block names every module in the application and nothing else. That check was added after seven modules went missing from the block while the cycles below were kept up to date by hand. The seven were the four snapshot modules, wasm_file_cache, wasm_store and wasm_subsup.

Read it as three stacks that meet at the top. The front end goes wasm_leb128 to wasm_decode to wasm_validate, or wasm_wat_lex to wasm_wat for the text format, and both produce the same #module{}. The runtime goes wasm_keeper to wasm_memory and its siblings to wasm_instance to wasm_exec. The tier goes wasm_code_slots to wasm_core to wasm_jit. wasm sits over all three. The snapshot modules are at three different levels of the runtime. wasm_snapshot_file is at the bottom, because a file format needs nothing. wasm_snapshot is in the middle, because it copies instance state. wasm_snapshot_owner is at the top, because it holds a claim on a module; that is why it is in a cycle with the facade.

      script workers: wasm_script_worker, wasm_instance_worker, adapters
                                  |
      WASI and components: wasi_preview1, wasm_component, wasi_preview2,
                           wasi_http
                                  |
                                wasm                the facade
                                  |
          +-----------------------+-----------------------+
          |                       |                       |
      front end               runtime                   tier
      wasm_wat                wasm_exec                 wasm_jit
      wasm_validate           wasm_instance             wasm_core
      wasm_decode             wasm_memory, siblings     wasm_code_slots
      wasm_leb128             wasm_keeper
          |                       ^                       |
          +------ #module{} ------+----- compiled code ---+

The front end hands the runtime a #module{}, and the tier hands it compiled functions to run in place of interpreted ones. The layers above wasm are built on it, and the level listing above says which lower modules each may also call directly.

The four cycles

There are exactly four cycles, and each one is only a few calls.

The decoder, five modules. wasm_decode_code and the opcode-space modules wasm_decode_simd, wasm_decode_gc and wasm_decode_atomic call each other. A SIMD immediate can contain a memory argument and a GC instruction can contain a block type. The recursion comes from the binary format itself; it is not a mistake in the layers.

The encoder, five modules. The decoder's cycle run backwards. wasm_encode writes a global's initialiser through wasm_encode_code:expr/1, wasm_encode_code writes a block type through wasm_encode:valtype/1, and the opcode-space modules wasm_encode_simd, wasm_encode_gc and wasm_encode_atomic write a memory argument through wasm_encode_code. The modules are split exactly as the decoder's are, so that each reads against its decoder line for line.

The tier, three modules. Two edges, one function each. wasm_core calls wasm_exec:load_spec/1 and store_spec/1 at generation time, so that the interpreted and generated paths cannot describe a load differently. wasm_exec calls wasm_jit:reentered/0 on the way back into generated code.

The facade, the cache and the snapshot owner, three modules. wasm_module_cache calls wasm:compile/2 when a module is not in the cache. That is one line, and for a long time it was the whole cycle.

wasm_snapshot_owner was added to it on purpose. An initialized runtime snapshot holds a module's layout. So it needs a claim on that module that lives longer than the process that captured it, and only the process that holds a claim can give it back. Any process that lives long enough to do this calls the cache, and the cache calls the facade. So the cycle cannot be avoided; you can only choose which module is in it. The choice was wasm_snapshot_owner, fifty lines whose only job is to hold a claim. The mechanism, wasm_snapshot, stays out of the cycle: it is what a capture copies and what a restore writes back.

Cycles are allowed here. What is not allowed is a fifth cycle that appears without anyone noticing. You cannot see a cycle by reading one module. Everything else about wasm_memory you learn inside wasm_memory, but a cycle you only find by reading all hundred and two.

It is easy to add one by mistake. One call from wasm_error, at level 0, up into wasm would merge fourteen modules into one cycle, and only the test would tell you.

The path of a call

One wasm:call/3 end to end, so you can put a breakpoint anywhere on it. Every hop names the function you would stop in.

wasm:call/3                      check per-call limits, if any were given
  wasm:call_1/4                  wasm_instance:export_kind/2 resolves the name
                                 to a function index, then checks the arguments
  wasm:invoke_with/5             enter/0 counts depth **per process**, not per
                                 instance, because a host import may call back
  wasm:leased_invoke/6           only at depth 0, and only on a snapshotable
                                 instance: wasm_instance:enter_call/1 refuses
                                 while a capture or a destroy is in progress
  wasm:invoke_at/6               takes the heap lease, opens the fuel budget,
                                 reads #mut{} once
     wasm_jit:entry/3            depth 0 only. Answers a compiled entry point
                                 if a slot is resident, otherwise the one it
                                 was given
  wasm_exec:call/5               the interpreter: dispatch in run/3, control
                                 flow in branch/3, calls in do_call/4, which
                                 runs a callee the unit holds compiled
  wasm:settle/2                  values out, or an error value

Three things about that shape are deliberate and easy to undo by accident.

The tier is chosen once a call, and entered at calls. wasm_jit:entry/3 runs at the outermost call only, and answers compiled code when the module has a unit loaded. When the export itself was not compiled, the interpreter runs it with that unit in hand, and do_call/4 runs every callee the unit holds as compiled code. An exception that leaves those compiled frames goes back into the interpreter's unwinding at that call (left_compiled/3). An interpreted call pays one comparison for this, in the clause head of do_call/4, and the dispatch path pays nothing: run/3 and branch/3 do not know the tier exists. Keep it that way. Three separate changes to run/3 and branch/3 each made QuickJS about 70% slower, while the small synthetic loop benchmark showed no change; test/audit/PERF.md records them. Entering compiled code only at the outermost call is not the answer either: everything below the first refused function or call_indirect then ran interpreted, as the comment above do_call/4 explains.

Depth is per process. A host function may call back into the instance that called it, so the count cannot live on the instance.

Only the outermost call takes the lease. Nested calls already run inside it. Taking a second lease would add two atomic operations to each nested call, with no benefit.

A request through the worker kernel takes a longer route to this path. wasm_script_worker starts a runner process for each request, the adapter's prepare/3 builds the imports, and a reactor restores an image before handle is called. Worker internals draws that route, and test/audit/PERF.md gives its cost for each phase.

How a function body gets ready to run

The interpreter does not run the binary format. It runs each function body in a lowered form, the IR, which wasm_instance builds. Read this before you change lowering, the module cache, or how processes share an instance.

  • A module with 256 functions or fewer is lowered when it is instantiated.
  • A larger module is lowered one body at a time, the first time a process calls it (wasm_instance:body_of/2). The body is kept in that process's dictionary, because reading it there copies nothing.
  • Several processes can call one instance, as a kernel's tasks or a component's threads do. If the module came from wasm:load/1, then once a second process takes a body, what they lower is published in persistent_term and the others take it instead of lowering it again. A garbage collection never copies a persistent_term value.
  • Bodies are published in batches, at most 32 per module, and all of them are erased when the module leaves the cache. The cap is there because erasing a persistent_term key makes the BEAM scan every process.

body_of/2's doc has the rules. wasm_scale_SUITE checks that a large module defers its lowering, wasm_module_cache_SUITE checks the sharing, and bench/paths/sharedbench.erl measures it.

Reading the graph yourself

{ok, S} = xref:start(arch),
{ok, _} = xref:add_directory(S, "_build/default/lib/wasm/ebin", [{warnings, false}]),
{ok, Calls} = xref:q(S, "XC"),
{ok, Mods} = xref:q(S, "AM"),
xref:stop(S).

Then build a digraph from Calls restricted to Mods and ask digraph_utils:strong_components/1. test/wasm_architecture_SUITE.erl does exactly this.

Do not derive the graph by grepping the sources. Module documentation refers to other modules as `wasm_exec:call/3` and a grep counts every one of those as a dependency. On this code that turns four cycles into one cycle of fourteen modules, which is completely wrong.

Short notes

  • Level 0 is a good place to make a change. Nothing in the project depends on its internals, so a change affects only what its callers use.
  • wasm_keeper decides how long anything that two instances can share stays alive. If you add a resource with a lifetime, it must go through the keeper. That includes a snapshot's image, which every memory restored from it holds, and each memory's charged pages: its page table, growth chunks and arena.
  • wasm_error is at level 0 on purpose. Every module may build an error, and building one must never call back into the runtime.
  • Adding a module means deciding its level. If it needs something above it, you are about to add a fifth cycle.

Read this next

The page for the part you are changing: Worker internals, Compiled tier internals, Component internals, Memory or Snapshots; then Design notes for the reasons behind the design.