wasm_component_link (wasm v0.16.0)

View Source

Read a component's wiring diagram and build its cores.

A component holds one or more core modules plus a wiring diagram (its core-instance, alias and canon sections) saying how each core gets its imports and which functions the component exposes. wasm_component runs a program by picking one core and binding its imports to our WASI host functions by name. That is enough when the program core asks for WASI directly, which every component we build ourselves does.

This module adds the missing case: a core whose imports are satisfied by another core's exports, not by a host function. It walks the top-level sections in order, building the core-instance graph, so a core can be instantiated with the exports of a core built before it (wasm:extern/2 carries an export across, and one shared store via #{link => ...} lets a memory or table of one core serve another).

It covers the preview1-to-preview2 adapter too: the startup cycle a shim table breaks, and the canon lower and canon lift functions between the cores, sync and async (wasm_async). A single-core program stays on wasm_component's direct path.

Where things are

you wantlook at
reading the section stream into a graphparse/1, fold_sections/3
rejecting a bad canon lift before any core runsvalidate_lifts/2
building every core in graph orderlink/4, fold/2, step/2
which core is the entryentry/1
one core instance: its imports and its instantiationinstantiate_core/3, imports_for/3, host_import/2
aliases into the index spacesalias_into/5, export_val/3, synthetic/2
decoding canon functions and their optionscanon/1, canonopts/1
a lowered host function, and the realloc it allocates throughlowered/4, bind_realloc/3
which component import a lowered function stands for, and a core's imports from outside the componentexternal_side/3, lowered_origin/2, externals/3
resource.drop and destructorsresource_drop/5, resource_dtor/2
what the component exports, and howexport_map/1, export_encodings/1, export_bindings/1
the exports with their function types, in binary order, for wasm_component:describe/1describe_exports/2, over export_func_list/1
a core's own importscore_imports/1
freeing the cores a failed link builtdestroy_built/1

Nothing here raises: a malformed section or an unresolved import is a returned error value carrying a kind and context, and no name a component supplies becomes an atom.

Summary

Functions

The {Module, Field} of every import in a core module.

Each function the component lifts and exports, in the order the binary exports it, for wasm_component:describe/1: [{Name, FuncType}], Name as wasm_component:call/4 takes it and FuncType as wasm_component_types:func_type/2 gives it, with async taken from the lift, which is what decides between call/4 and call_async/4. A function the component exports without lifting it, one it imports and exports again, is left out. A lift whose type is not a function type throws a malformed error with kind unsupported_type.

Each exported function's declared realloc and post-return, as core export names.

Each exported function's string encoding, when it is not the default UTF-8.

Map each component func export name to the core function that implements it.

Whether the largest-core fast path resolves every exported function correctly.

Fold Fun(Id, Content, Acc) over a component's top-level sections, in order.

Instantiate a component by interpreting its whole core-instance graph.

Compile or load a core module's bytes, as the instantiate options ask.

Parse a component's top-level sections into an ordered item list.

parse/1, for the readers that take its answer in place of the bytes: a component this parser cannot read, or one that makes it raise, is {error, _}, which each reader turns into the answer it gives for bytes it cannot read.

What the host boundary needs to check resource handles, read from the graph.

As resource_info/2, with the type space Types already built, and the graph as parsed/1 gives it in place of the bytes.

Skip the optional type ascription after an export's sortidx.

Statically check every canon lift against its declared component function type.

As validate_lifts/2, with the type space Types already built, and the graph as parsed/1 gives it in place of the bytes.

Types

async_mark()

-type async_mark() :: sync | {async, non_neg_integer() | none}.

async_target()

-type async_target() ::
          #{lift := {wasm:instance(), binary()}, callback := {wasm:instance(), binary()} | none}.

core_sort()

-type core_sort() :: func | table | memory | global.

graph()

-type graph() :: [item()].

intrinsic()

-type intrinsic() :: {new | drop | rep, non_neg_integer() | undefined}.

item()

-type item() ::
          {core_module, binary()} |
          {core_instance, {instantiate, non_neg_integer(), [{binary(), non_neg_integer()}]}} |
          {core_instance, {exports, [{binary(), core_sort(), non_neg_integer()}]}} |
          {core_alias, core_sort(), non_neg_integer(), binary()} |
          {comp_func_alias, non_neg_integer(), binary()} |
          {canon_lower, non_neg_integer(), non_neg_integer() | none, string_encoding(), async_mark()} |
          {canon_lift,
           non_neg_integer(),
           string_encoding(),
           async_mark(),
           non_neg_integer() | none,
           non_neg_integer() | none,
           non_neg_integer()} |
          {canon_async, atom(), map()} |
          {canon_resource, new | drop | rep, non_neg_integer()} |
          {comp_import_instance, binary()} |
          {comp_import_func, binary()} |
          {comp_export, binary(), byte(), non_neg_integer()}.

parsed()

-type parsed() :: {ok, graph()} | {error, term()}.

string_encoding()

-type string_encoding() :: utf8 | utf16 | latin1_utf16.

Functions

core_imports/1

-spec core_imports(binary()) -> [{binary(), binary()}].

The {Module, Field} of every import in a core module.

Bin is the core module's own bytes (a core preamble, not the component). The importing core names each import by module and field; resolution binds those names to host functions or, through the graph above, to another core's exports. Non-function imports are stepped over by their type so parsing reaches the next.

describe_exports(Graph, Types)

-spec describe_exports(graph(), map()) -> [{binary(), wasm_component_types:func_type()}].

Each function the component lifts and exports, in the order the binary exports it, for wasm_component:describe/1: [{Name, FuncType}], Name as wasm_component:call/4 takes it and FuncType as wasm_component_types:func_type/2 gives it, with async taken from the lift, which is what decides between call/4 and call_async/4. A function the component exports without lifting it, one it imports and exports again, is left out. A lift whose type is not a function type throws a malformed error with kind unsupported_type.

export_bindings/1

-spec export_bindings(binary() | parsed()) ->
                         #{binary() => #{realloc => binary() | none, post_return => binary() | none}}.

Each exported function's declared realloc and post-return, as core export names.

A canon lift names the allocator and cleanup the runtime must use; call/4 allocates through that realloc and runs that post-return rather than guessing cabi_realloc/ cabi_post_<export>. Returns #{ExportName => #{realloc => Name | none, post_return => Name | none}}, omitting exports whose lift declares neither.

export_encodings/1

-spec export_encodings(binary() | parsed()) -> #{binary() => string_encoding()}.

Each exported function's string encoding, when it is not the default UTF-8.

A component's canon lift carries a string-encoding option; call/4 marshals that export's strings with it. Returns #{ExportName => utf16 | latin1_utf16}, omitting UTF-8 exports (the default), so the common component adds nothing.

export_map/1

-spec export_map(binary() | parsed()) -> #{binary() => binary()}.

Map each component func export name to the core function that implements it.

Resolves the export section (name -> component-func index) through the graph (component-func index -> canon lift of a core-func index -> the core alias' export name), so an export renamed from its core function is callable by its component name. A function an exported interface holds is keyed <interface>#<function>. An export that does not resolve to a lifted core function (an imported function) is omitted, and the caller falls back to the name it was given.

exports_resolve_on_entry/3

-spec exports_resolve_on_entry(binary() | parsed(), non_neg_integer(), binary()) -> boolean().

Whether the largest-core fast path resolves every exported function correctly.

true only when every exported function's lift that names a core-func alias targets a core instance of the entry module EntryModIdx, except an interface function's lift on another core whose name the entry core (EntryBytes) does not export: called by name it is not found, rather than found in the wrong core. When it is false, the caller must interpret the full graph (build every core, dispatch each export to the instance its lift names) rather than call the largest core by export name. Tolerant: a graph it cannot read, or a lift it cannot pin to an alias, yields true (the fast path, unchanged).

fold_sections/3

-spec fold_sections(fun((byte(), binary(), Acc) -> Acc), Acc, binary()) ->
                       {ok, Acc} | {truncated, byte()}.

Fold Fun(Id, Content, Acc) over a component's top-level sections, in order.

Each section is a one-byte id, a u32 size, then that many content bytes. The one walk parse/1 and wasm_component:decode/1 share; each decides what a section means and what a truncated one is called.

link(Graph, EntryModIdx, HostResolve, Opts)

-spec link(graph(), non_neg_integer(), fun(([{binary(), binary()}]) -> map()), map()) ->
              {ok,
               #{core := wasm:instance(),
                 cores := [wasm:instance()],
                 export_targets := #{binary() => {wasm:instance(), binary()}},
                 async_targets := #{binary() => async_target()},
                 externals := [[{{binary(), binary()}, {binary(), binary()}}]]}} |
              {error, term()}.

Instantiate a component by interpreting its whole core-instance graph.

Graph is the parsed items; EntryModIdx the largest core's index (the entry for a program whose exports the caller calls directly, e.g. a reactor); HostResolve maps a core's [{Mod, Field}] imports to the host functions that satisfy them (version-normalised); Opts the loader and limits.

Every core instance is built in graph order: a core's imports come from the cores named in its with args (an extern() carried across a shared store) or, for a namespace of lowered host functions, from HostResolve. The entry is the core that exports wasi:cli/run...#run (a command) or, failing that, the largest core (a reactor). Returns {ok, #{core, cores}} -- core is the entry instance, cores every built instance for teardown -- or a named {error, _}.

load_core/2

-spec load_core(atom(), binary()) -> {ok, wasm:module_()} | {error, term()}.

Compile or load a core module's bytes, as the instantiate options ask.

parse(Bin)

-spec parse(binary()) -> {ok, graph()} | {error, term()}.

Parse a component's top-level sections into an ordered item list.

The component preamble (00 61 73 6d 0d 00 01 00) is already stripped by the caller; Bin is the section stream. A section the linker does not act on, such as a custom section, is stepped over by its declared size, so parsing always reaches the next section.

parsed(Sec)

-spec parsed(binary()) -> parsed().

parse/1, for the readers that take its answer in place of the bytes: a component this parser cannot read, or one that makes it raise, is {error, _}, which each reader turns into the answer it gives for bytes it cannot read.

resource_info(Sec, EntryModIdx)

-spec resource_info(binary(), non_neg_integer()) ->
                       #{sigs := #{binary() => wasm_component_types:sig()},
                         defined := [non_neg_integer()],
                         intrinsics := #{{binary(), binary()} => intrinsic()},
                         dtors := #{binary() => non_neg_integer()}}.

What the host boundary needs to check resource handles, read from the graph.

  • sigs: each lifted function's real signature, from the component's type space, keyed by its component export name and by the core function name it lifts (the name call/4 reaches it by). A handle crosses the boundary by these, whatever descriptor a caller passed.
  • defined: the resource types this component defines: those its type space defines, and those a canon resource.new or resource.rep names. Only their handles are this component's to check; an imported resource (a WASI stream) passes through as before.
  • intrinsics: for each resource built-in the entry core imports, {new | drop | rep, Rt}, with Rt undefined for a type defined elsewhere.
  • dtors: each destructor's export name (<prefix>[dtor]<res>) to its type, from the constructors and methods named after the same resource.

Tolerant: what it cannot read is left out, never raised.

resource_info/3

-spec resource_info(binary() | parsed(), non_neg_integer(), map()) -> map().

As resource_info/2, with the type space Types already built, and the graph as parsed/1 gives it in place of the bytes.

skip_export_desc/1

-spec skip_export_desc(binary()) -> binary().

Skip the optional type ascription after an export's sortidx.

0x00 is absent, which is all the standard toolchain emits. A present one (0x01 ...) is left for the next entry rather than misparsed; that shape has not been observed.

validate_lifts(Sec, CoreMods)

-spec validate_lifts(binary(), [binary()]) -> ok | {error, term()}.

Statically check every canon lift against its declared component function type.

For each lift the Canonical ABI derives a core signature from the component function type it declares (params flatten and, past 16 slots, spill to one pointer; a result of more than one core value returns through a pointer). That derived signature must equal the core function's own type, read from the module bytes without instantiating anything. {error, {invalid_lift_type, _}} when a lift declares a type its core function cannot have (e.g. lifting a core f64 as a component u32), so the component is rejected before any core runs. Tolerant: a graph, type or core it cannot read yields ok, leaving instantiation to fail (or succeed) as before rather than block on an unreadable input.

CoreMods is the component's core module bytes in module-index order.

validate_lifts/3

-spec validate_lifts(binary() | parsed(), [binary()], map()) -> ok | {error, term()}.

As validate_lifts/2, with the type space Types already built, and the graph as parsed/1 gives it in place of the bytes.