Add initial support for fused adapter trampolines (#4501)
* Add initial support for fused adapter trampolines This commit lands a significant new piece of functionality to Wasmtime's implementation of the component model in the form of the implementation of fused adapter trampolines. Internally within a component core wasm modules can communicate with each other by having their exports `canon lift`'d to get `canon lower`'d into a different component. This signifies that two components are communicating through a statically known interface via the canonical ABI at this time. Previously Wasmtime was able to identify that this communication was happening but it simply panicked with `unimplemented!` upon seeing it. This commit is the beginning of filling out this panic location with an actual implementation. The implementation route chosen here for fused adapters is to use a WebAssembly module itself for the implementation. This means that, at compile time of a component, Wasmtime is generating core WebAssembly modules which then get recursively compiled within Wasmtime as well. The choice to use WebAssembly itself as the implementation of fused adapters stems from a few motivations: * This does not represent a significant increase in the "trusted compiler base" of Wasmtime. Getting the Wasm -> CLIF translation correct once is hard enough much less for an entirely different IR to CLIF. By generating WebAssembly no new interactions with Cranelift are added which drastically reduces the possibilities for mistakes. * Using WebAssembly means that component adapters are insulated from miscompilations and mistakes. If something goes wrong it's defined well within the WebAssembly specification how it goes wrong and what happens as a result. This means that the "blast zone" for a wrong adapter is the component instance but not the entire host itself. Accesses to linear memory are guaranteed to be in-bounds and otherwise handled via well-defined traps. * A fully-finished fused adapter compiler is expected to be a significant and quite complex component of Wasmtime. Functionality along these lines is expected to be needed for Web-based polyfills of the component model and by using core WebAssembly it provides the opportunity to share code between Wasmtime and these polyfills for the component model. * Finally the runtime implementation of managing WebAssembly modules is already implemented and quite easy to integrate with, so representing fused adapters with WebAssembly results in very little extra support necessary for the runtime implementation of instantiating and managing a component. The compiler added in this commit is dubbed Wasmtime's Fused Adapter Compiler of Trampolines (FACT) because who doesn't like deriving a name from an acronym. Currently the trampoline compiler is limited in its support for interface types and only supports a few primitives. I plan on filing future PRs to flesh out the support here for all the variants of `InterfaceType`. For now this PR is primarily focused on all of the other infrastructure for the addition of a trampoline compiler. With the choice to use core WebAssembly to implement fused adapters it means that adapters need to be inserted into a module. Unfortunately adapters cannot all go into a single WebAssembly module because adapters themselves have dependencies which may be provided transitively through instances that were instantiated with other adapters. This means that a significant chunk of this PR (`adapt.rs`) is dedicated to determining precisely which adapters go into precisely which adapter modules. This partitioning process attempts to make large modules wherever it can to cut down on core wasm instantiations but is likely not optimal as it's just a simple heuristic today. With all of this added together it's now possible to start writing `*.wast` tests that internally have adapted modules communicating with one another. A `fused.wast` test suite was added as part of this PR which is the beginning of tests for the support of the fused adapter compiler added in this PR. Currently this is primarily testing some various topologies of adapters along with direct/indirect modes. This will grow many more tests over time as more types are supported. Overall I'm not 100% satisfied with the testing story of this PR. When a test fails it's very difficult to debug since everything is written in the text format of WebAssembly meaning there's no "conveniences" to print out the state of the world when things go wrong and easily debug. I think this will become even more apparent as more tests are written for more types in subsequent PRs. At this time though I know of no better alternative other than leaning pretty heavily on fuzz-testing to ensure this is all exercised. * Fix an unused field warning * Fix tests in `wasmtime-runtime` * Add some more tests for compiled trampolines * Remap exports when injecting adapters The exports of a component were accidentally left unmapped which meant that they indexed the instance indexes pre-adapter module insertion. * Fix typo * Rebase conflicts
This commit is contained in:
@@ -45,8 +45,9 @@
|
||||
//! side-effectful initializers are emitted to the `GlobalInitializer` list in the
|
||||
//! final `Component`.
|
||||
|
||||
use crate::component::translate::adapt::{Adapter, AdapterOptions, Adapters};
|
||||
use crate::component::translate::*;
|
||||
use crate::{ModuleTranslation, PrimaryMap, SignatureIndex};
|
||||
use crate::{PrimaryMap, SignatureIndex};
|
||||
use indexmap::IndexMap;
|
||||
|
||||
pub(super) fn run(
|
||||
@@ -54,12 +55,13 @@ pub(super) fn run(
|
||||
result: &Translation<'_>,
|
||||
nested_modules: &PrimaryMap<StaticModuleIndex, ModuleTranslation<'_>>,
|
||||
nested_components: &PrimaryMap<StaticComponentIndex, Translation<'_>>,
|
||||
) -> Result<Component> {
|
||||
) -> Result<(Component, Adapters)> {
|
||||
let mut inliner = Inliner {
|
||||
types,
|
||||
nested_modules,
|
||||
nested_components,
|
||||
result: Component::default(),
|
||||
adapters: Adapters::default(),
|
||||
import_path_interner: Default::default(),
|
||||
runtime_realloc_interner: Default::default(),
|
||||
runtime_post_return_interner: Default::default(),
|
||||
@@ -106,7 +108,7 @@ pub(super) fn run(
|
||||
}
|
||||
inliner.result.exports = export_map;
|
||||
|
||||
Ok(inliner.result)
|
||||
Ok((inliner.result, inliner.adapters))
|
||||
}
|
||||
|
||||
struct Inliner<'a> {
|
||||
@@ -133,6 +135,9 @@ struct Inliner<'a> {
|
||||
/// inliner.
|
||||
result: Component,
|
||||
|
||||
/// Metadata about fused adapters identified throughout inlining.
|
||||
adapters: Adapters,
|
||||
|
||||
// Maps used to "intern" various runtime items to only save them once at
|
||||
// runtime instead of multiple times.
|
||||
import_path_interner: HashMap<ImportPath<'a>, RuntimeImportIndex>,
|
||||
@@ -270,7 +275,7 @@ enum ComponentFuncDef<'a> {
|
||||
Lifted {
|
||||
ty: TypeFuncIndex,
|
||||
func: CoreDef,
|
||||
options: CanonicalOptions,
|
||||
options: AdapterOptions,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -392,7 +397,7 @@ impl<'a> Inliner<'a> {
|
||||
let canonical_abi = frame.translation.funcs[frame.funcs.next_key()];
|
||||
let lower_ty = frame.translation.component_funcs[*func];
|
||||
|
||||
let options_lower = self.canonical_options(frame, options);
|
||||
let options_lower = self.adapter_options(frame, options);
|
||||
let func = match &frame.component_funcs[*func] {
|
||||
// If this component function was originally a host import
|
||||
// then this is a lowered host function which needs a
|
||||
@@ -402,13 +407,14 @@ impl<'a> Inliner<'a> {
|
||||
let index = LoweredIndex::from_u32(self.result.num_lowerings);
|
||||
self.result.num_lowerings += 1;
|
||||
let import = self.runtime_import(path);
|
||||
let options = self.canonical_options(options_lower);
|
||||
self.result
|
||||
.initializers
|
||||
.push(GlobalInitializer::LowerImport(LowerImport {
|
||||
canonical_abi,
|
||||
import,
|
||||
index,
|
||||
options: options_lower,
|
||||
options,
|
||||
}));
|
||||
CoreDef::Lowered(index)
|
||||
}
|
||||
@@ -464,33 +470,43 @@ impl<'a> Inliner<'a> {
|
||||
// component is different than the source component means
|
||||
// that a "fused adapter" was just identified.
|
||||
//
|
||||
// This is the location where, when this is actually
|
||||
// implemented, we'll record metadata about this fused
|
||||
// adapter to get compiled later during the compilation
|
||||
// process. The fused adapter here will be generated by
|
||||
// cranelift and will perfom argument validation when
|
||||
// called, copy the arguments from `options_lower` to
|
||||
// `options_lift` and then call the `func` specified for the
|
||||
// lifted options.
|
||||
// Metadata about this fused adapter is recorded in the
|
||||
// `Adapters` output of this compilation pass. Currently the
|
||||
// implementation of fused adapters is to generate a core
|
||||
// wasm module which is instantiated with relevant imports
|
||||
// and the exports are used as the fused adapters. At this
|
||||
// time we don't know when precisely the instance will be
|
||||
// created but we do know that the result of this will be an
|
||||
// export from a previously-created instance.
|
||||
//
|
||||
// When the `func` returns the canonical adapter will verify
|
||||
// the return values, copy them from `options_lift` to
|
||||
// `options_lower`, and then return.
|
||||
// To model this the result of this arm is a
|
||||
// `CoreDef::Export`. The actual indices listed within the
|
||||
// export are "fake indices" in the sense of they're not
|
||||
// resolved yet. This resolution will happen at a later
|
||||
// compilation phase. Any usages of the `CoreDef::Export`
|
||||
// here will be detected and rewritten to an actual runtime
|
||||
// instance created.
|
||||
//
|
||||
// The `instance` field of the `CoreExport` has a marker
|
||||
// which indicates that it's a fused adapter. The `item` is
|
||||
// a function where the function index corresponds to the
|
||||
// `adapter_idx` which contains the metadata about this
|
||||
// adapter being created. The metadata is used to learn
|
||||
// about the dependencies and when the adapter module can
|
||||
// be instantiated.
|
||||
ComponentFuncDef::Lifted {
|
||||
ty: lift_ty,
|
||||
func,
|
||||
options: options_lift,
|
||||
} => {
|
||||
// These are the various compilation options for lifting
|
||||
// and lowering.
|
||||
drop(lift_ty); // type used when lifting the core function
|
||||
drop(lower_ty); // type used when lowering the core function
|
||||
drop(func); // original core wasm function that was lifted
|
||||
drop(options_lift); // options during `canon lift`
|
||||
drop(options_lower); // options during `canon lower`
|
||||
drop(canonical_abi); // type signature of created core wasm function
|
||||
|
||||
unimplemented!("lowering a lifted function")
|
||||
let adapter_idx = self.adapters.adapters.push(Adapter {
|
||||
lift_ty: *lift_ty,
|
||||
lift_options: options_lift.clone(),
|
||||
lower_ty,
|
||||
lower_options: options_lower,
|
||||
func: func.clone(),
|
||||
});
|
||||
CoreDef::Adapter(adapter_idx)
|
||||
}
|
||||
};
|
||||
frame.funcs.push(func);
|
||||
@@ -500,7 +516,7 @@ impl<'a> Inliner<'a> {
|
||||
// some metadata about the lifting is simply recorded. This'll get
|
||||
// plumbed through to exports or a fused adapter later on.
|
||||
Lift(ty, func, options) => {
|
||||
let options = self.canonical_options(frame, options);
|
||||
let options = self.adapter_options(frame, options);
|
||||
frame.component_funcs.push(ComponentFuncDef::Lifted {
|
||||
ty: *ty,
|
||||
func: frame.funcs[*func].clone(),
|
||||
@@ -639,7 +655,7 @@ impl<'a> Inliner<'a> {
|
||||
frame.tables.push(
|
||||
match self.core_def_of_module_instance_export(frame, *instance, *name) {
|
||||
CoreDef::Export(e) => e,
|
||||
CoreDef::Lowered(_) | CoreDef::AlwaysTrap(_) => unreachable!(),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -648,7 +664,7 @@ impl<'a> Inliner<'a> {
|
||||
frame.globals.push(
|
||||
match self.core_def_of_module_instance_export(frame, *instance, *name) {
|
||||
CoreDef::Export(e) => e,
|
||||
CoreDef::Lowered(_) | CoreDef::AlwaysTrap(_) => unreachable!(),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -657,7 +673,7 @@ impl<'a> Inliner<'a> {
|
||||
frame.memories.push(
|
||||
match self.core_def_of_module_instance_export(frame, *instance, *name) {
|
||||
CoreDef::Export(e) => e,
|
||||
CoreDef::Lowered(_) | CoreDef::AlwaysTrap(_) => unreachable!(),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -795,19 +811,34 @@ impl<'a> Inliner<'a> {
|
||||
|
||||
/// Translates a `LocalCanonicalOptions` which indexes into the `frame`
|
||||
/// specified into a runtime representation.
|
||||
///
|
||||
/// This will "intern" repeatedly reused memories or functions to avoid
|
||||
/// storing them in multiple locations at runtime.
|
||||
fn canonical_options(
|
||||
fn adapter_options(
|
||||
&mut self,
|
||||
frame: &InlinerFrame<'a>,
|
||||
options: &LocalCanonicalOptions,
|
||||
) -> CanonicalOptions {
|
||||
) -> AdapterOptions {
|
||||
let memory = options.memory.map(|i| {
|
||||
let export = frame.memories[i].clone().map_index(|i| match i {
|
||||
frame.memories[i].clone().map_index(|i| match i {
|
||||
EntityIndex::Memory(i) => i,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
})
|
||||
});
|
||||
let realloc = options.realloc.map(|i| frame.funcs[i].clone());
|
||||
let post_return = options.post_return.map(|i| frame.funcs[i].clone());
|
||||
AdapterOptions {
|
||||
instance: frame.instance,
|
||||
string_encoding: options.string_encoding,
|
||||
memory,
|
||||
realloc,
|
||||
post_return,
|
||||
}
|
||||
}
|
||||
|
||||
/// Translatees an `AdapterOptions` into a `CanonicalOptions` where
|
||||
/// memories/functions are inserted into the global initializer list for
|
||||
/// use at runtime. This is only used for lowered host functions and lifted
|
||||
/// functions exported to the host.
|
||||
fn canonical_options(&mut self, options: AdapterOptions) -> CanonicalOptions {
|
||||
let memory = options.memory.map(|export| {
|
||||
*self
|
||||
.runtime_memory_interner
|
||||
.entry(export.clone())
|
||||
@@ -823,8 +854,7 @@ impl<'a> Inliner<'a> {
|
||||
index
|
||||
})
|
||||
});
|
||||
let realloc = options.realloc.map(|i| {
|
||||
let def = frame.funcs[i].clone();
|
||||
let realloc = options.realloc.map(|def| {
|
||||
*self
|
||||
.runtime_realloc_interner
|
||||
.entry(def.clone())
|
||||
@@ -840,8 +870,7 @@ impl<'a> Inliner<'a> {
|
||||
index
|
||||
})
|
||||
});
|
||||
let post_return = options.post_return.map(|i| {
|
||||
let def = frame.funcs[i].clone();
|
||||
let post_return = options.post_return.map(|def| {
|
||||
*self
|
||||
.runtime_post_return_interner
|
||||
.entry(def.clone())
|
||||
@@ -859,7 +888,7 @@ impl<'a> Inliner<'a> {
|
||||
})
|
||||
});
|
||||
CanonicalOptions {
|
||||
instance: frame.instance,
|
||||
instance: options.instance,
|
||||
string_encoding: options.string_encoding,
|
||||
memory,
|
||||
realloc,
|
||||
@@ -896,6 +925,7 @@ impl<'a> Inliner<'a> {
|
||||
// component then the configured options are plumbed through
|
||||
// here.
|
||||
ComponentFuncDef::Lifted { ty, func, options } => {
|
||||
let options = self.canonical_options(options);
|
||||
Export::LiftedFunction { ty, func, options }
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user