Path: blob/main/crates/environ/src/component/translate/adapt.rs
1692 views
//! Identification and creation of fused adapter modules in Wasmtime.1//!2//! A major piece of the component model is the ability for core wasm modules to3//! talk to each other through the use of lifted and lowered functions. For4//! example one core wasm module can export a function which is lifted. Another5//! component could import that lifted function, lower it, and pass it as the6//! import to another core wasm module. This is what Wasmtime calls "adapter7//! fusion" where two core wasm functions are coming together through the8//! component model.9//!10//! There are a few ingredients during adapter fusion:11//!12//! * A core wasm function which is "lifted".13//! * A "lift type" which is the type that the component model function had in14//! the original component15//! * A "lower type" which is the type that the component model function has16//! in the destination component (the one the uses `canon lower`)17//! * Configuration options for both the lift and the lower operations such as18//! memories, reallocs, etc.19//!20//! With these ingredients combined Wasmtime must produce a function which21//! connects the two components through the options specified. The fused adapter22//! performs tasks such as validation of passed values, copying data between23//! linear memories, etc.24//!25//! Wasmtime's current implementation of fused adapters is designed to reduce26//! complexity elsewhere as much as possible while also being suitable for being27//! used as a polyfill for the component model in JS environments as well. To28//! that end Wasmtime implements a fused adapter with another wasm module that29//! it itself generates on the fly. The usage of WebAssembly for fused adapters30//! has a number of advantages:31//!32//! * There is no need to create a raw Cranelift-based compiler. This is where33//! majority of "unsafety" lives in Wasmtime so reducing the need to lean on34//! this or audit another compiler is predicted to weed out a whole class of35//! bugs in the fused adapter compiler.36//!37//! * As mentioned above generation of WebAssembly modules means that this is38//! suitable for use in JS environments. For example a hypothetical tool which39//! polyfills a component onto the web today would need to do something for40//! adapter modules, and ideally the adapters themselves are speedy. While41//! this could all be written in JS the adapting process is quite nontrivial42//! so sharing code with Wasmtime would be ideal.43//!44//! * Using WebAssembly insulates the implementation to bugs to a certain45//! degree. While logic bugs are still possible it should be much more46//! difficult to have segfaults or things like that. With adapters exclusively47//! executing inside a WebAssembly sandbox like everything else the failure48//! modes to the host at least should be minimized.49//!50//! * Integration into the runtime is relatively simple, the adapter modules are51//! just another kind of wasm module to instantiate and wire up at runtime.52//! The goal is that the `GlobalInitializer` list that is processed at runtime53//! will have all of its `Adapter`-using variants erased by the time it makes54//! its way all the way up to Wasmtime. This means that the support in55//! Wasmtime prior to adapter modules is actually the same as the support56//! after adapter modules are added, keeping the runtime fiddly bits quite57//! minimal.58//!59//! This isn't to say that this approach isn't without its disadvantages of60//! course. For now though this seems to be a reasonable set of tradeoffs for61//! the development stage of the component model proposal.62//!63//! ## Creating adapter modules64//!65//! With WebAssembly itself being used to implement fused adapters, Wasmtime66//! still has the question of how to organize the adapter functions into actual67//! wasm modules.68//!69//! The first thing you might reach for is to put all the adapters into the same70//! wasm module. This cannot be done, however, because some adapters may depend71//! on other adapters (transitively) to be created. This means that if72//! everything were in the same module there would be no way to instantiate the73//! module. An example of this dependency is an adapter (A) used to create a74//! core wasm instance (M) whose exported memory is then referenced by another75//! adapter (B). In this situation the adapter B cannot be in the same module76//! as adapter A because B needs the memory of M but M is created with A which77//! would otherwise create a circular dependency.78//!79//! The second possibility of organizing adapter modules would be to place each80//! fused adapter into its own module. Each `canon lower` would effectively81//! become a core wasm module instantiation at that point. While this works it's82//! currently believed to be a bit too fine-grained. For example it would mean83//! that importing a dozen lowered functions into a module could possibly result84//! in up to a dozen different adapter modules. While this possibility could85//! work it has been ruled out as "probably too expensive at runtime".86//!87//! Thus the purpose and existence of this module is now evident -- this module88//! exists to identify what exactly goes into which adapter module. This will89//! evaluate the `GlobalInitializer` lists coming out of the `inline` pass and90//! insert `InstantiateModule` entries for where adapter modules should be91//! created.92//!93//! ## Partitioning adapter modules94//!95//! Currently this module does not attempt to be really all that fancy about96//! grouping adapters into adapter modules. The main idea is that most items97//! within an adapter module are likely to be close together since they're98//! theoretically going to be used for an instantiation of a core wasm module99//! just after the fused adapter was declared. With that in mind the current100//! algorithm is a one-pass approach to partitioning everything into adapter101//! modules.102//!103//! Adapters were identified in-order as part of the inlining phase of104//! translation where we're guaranteed that once an adapter is identified105//! it can't depend on anything identified later. The pass implemented here is106//! to visit all transitive dependencies of an adapter. If one of the107//! dependencies of an adapter is an adapter in the current adapter module108//! being built then the current module is finished and a new adapter module is109//! started. This should quickly partition adapters into contiugous chunks of110//! their index space which can be in adapter modules together.111//!112//! There's probably more general algorithms for this but for now this should be113//! fast enough as it's "just" a linear pass. As we get more components over114//! time this may want to be revisited if too many adapter modules are being115//! created.116117use crate::EntityType;118use crate::component::translate::*;119use crate::fact;120use std::collections::HashSet;121122/// Metadata information about a fused adapter.123#[derive(Debug, Clone, Hash, Eq, PartialEq)]124pub struct Adapter {125/// The type used when the original core wasm function was lifted.126///127/// Note that this could be different than `lower_ty` (but still matches128/// according to subtyping rules).129pub lift_ty: TypeFuncIndex,130/// Canonical ABI options used when the function was lifted.131pub lift_options: AdapterOptions,132/// The type used when the function was lowered back into a core wasm133/// function.134///135/// Note that this could be different than `lift_ty` (but still matches136/// according to subtyping rules).137pub lower_ty: TypeFuncIndex,138/// Canonical ABI options used when the function was lowered.139pub lower_options: AdapterOptions,140/// The original core wasm function which was lifted.141pub func: dfg::CoreDef,142}143144/// The data model for objects that are not unboxed in locals.145#[derive(Debug, Clone, Hash, Eq, PartialEq)]146pub enum DataModel {147/// Data is stored in GC objects.148Gc {},149150/// Data is stored in a linear memory.151LinearMemory {152/// An optional memory definition supplied.153memory: Option<dfg::CoreExport<MemoryIndex>>,154/// If `memory` is specified, whether it's a 64-bit memory.155memory64: bool,156/// An optional definition of `realloc` to used.157realloc: Option<dfg::CoreDef>,158},159}160161/// Configuration options which can be specified as part of the canonical ABI162/// in the component model.163#[derive(Debug, Clone, Hash, Eq, PartialEq)]164pub struct AdapterOptions {165/// The Wasmtime-assigned component instance index where the options were166/// originally specified.167pub instance: RuntimeComponentInstanceIndex,168/// How strings are encoded.169pub string_encoding: StringEncoding,170/// The async callback function used by these options, if specified.171pub callback: Option<dfg::CoreDef>,172/// An optional definition of a `post-return` to use.173pub post_return: Option<dfg::CoreDef>,174/// Whether to use the async ABI for lifting or lowering.175pub async_: bool,176/// The core function type that is being lifted from / lowered to.177pub core_type: ModuleInternedTypeIndex,178/// The data model used by this adapter: linear memory or GC objects.179pub data_model: DataModel,180}181182impl<'data> Translator<'_, 'data> {183/// This is the entrypoint of functionality within this module which184/// performs all the work of identifying adapter usages and organizing185/// everything into adapter modules.186///187/// This will mutate the provided `component` in-place and fill out the dfg188/// metadata for adapter modules.189pub(super) fn partition_adapter_modules(&mut self, component: &mut dfg::ComponentDfg) {190// Visit each adapter, in order of its original definition, during the191// partitioning. This allows for the guarantee that dependencies are192// visited in a topological fashion ideally.193let mut state = PartitionAdapterModules::default();194for (id, adapter) in component.adapters.iter() {195state.adapter(component, id, adapter);196}197state.finish_adapter_module();198199// Now that all adapters have been partitioned into modules this loop200// generates a core wasm module for each adapter module, translates201// the module using standard core wasm translation, and then fills out202// the dfg metadata for each adapter.203for (module_id, adapter_module) in state.adapter_modules.iter() {204let mut module =205fact::Module::new(self.types.types(), self.tunables.debug_adapter_modules);206let mut names = Vec::with_capacity(adapter_module.adapters.len());207for adapter in adapter_module.adapters.iter() {208let name = format!("adapter{}", adapter.as_u32());209module.adapt(&name, &component.adapters[*adapter]);210names.push(name);211}212let wasm = module.encode();213let imports = module.imports().to_vec();214215// Extend the lifetime of the owned `wasm: Vec<u8>` on the stack to216// a higher scope defined by our original caller. That allows to217// transform `wasm` into `&'data [u8]` which is much easier to work218// with here.219let wasm = &*self.scope_vec.push(wasm);220if log::log_enabled!(log::Level::Trace) {221match wasmprinter::print_bytes(wasm) {222Ok(s) => log::trace!("generated adapter module:\n{s}"),223Err(e) => log::trace!("failed to print adapter module: {e}"),224}225}226227// With the wasm binary this is then pushed through general228// translation, validation, etc. Note that multi-memory is229// specifically enabled here since the adapter module is highly230// likely to use that if anything is actually indirected through231// memory.232self.validator.reset();233let static_module_index = self.static_modules.next_key();234let translation = ModuleEnvironment::new(235self.tunables,236&mut self.validator,237self.types.module_types_builder(),238static_module_index,239)240.translate(Parser::new(0), wasm)241.expect("invalid adapter module generated");242243// Record, for each adapter in this adapter module, the module that244// the adapter was placed within as well as the function index of245// the adapter in the wasm module generated. Note that adapters are246// partitioned in-order so we're guaranteed to push the adapters247// in-order here as well. (with an assert to double-check)248for (adapter, name) in adapter_module.adapters.iter().zip(&names) {249let index = translation.module.exports[name];250let i = component.adapter_partitionings.push((module_id, index));251assert_eq!(i, *adapter);252}253254// Finally the metadata necessary to instantiate this adapter255// module is also recorded in the dfg. This metadata will be used256// to generate `GlobalInitializer` entries during the linearization257// final phase.258assert_eq!(imports.len(), translation.module.imports().len());259let args = imports260.iter()261.zip(translation.module.imports())262.map(|(arg, (_, _, ty))| fact_import_to_core_def(component, arg, ty))263.collect::<Vec<_>>();264let static_module_index2 = self.static_modules.push(translation);265assert_eq!(static_module_index, static_module_index2);266let id = component.adapter_modules.push((static_module_index, args));267assert_eq!(id, module_id);268}269}270}271272fn fact_import_to_core_def(273dfg: &mut dfg::ComponentDfg,274import: &fact::Import,275ty: EntityType,276) -> dfg::CoreDef {277fn unwrap_memory(def: &dfg::CoreDef) -> dfg::CoreExport<MemoryIndex> {278match def {279dfg::CoreDef::Export(e) => e.clone().map_index(|i| match i {280EntityIndex::Memory(i) => i,281_ => unreachable!(),282}),283_ => unreachable!(),284}285}286287let mut simple_intrinsic = |trampoline: dfg::Trampoline| {288let signature = ty.unwrap_func();289let index = dfg290.trampolines291.push((signature.unwrap_module_type_index(), trampoline));292dfg::CoreDef::Trampoline(index)293};294match import {295fact::Import::CoreDef(def) => def.clone(),296fact::Import::Transcode {297op,298from,299from64,300to,301to64,302} => {303let from = dfg.memories.push(unwrap_memory(from));304let to = dfg.memories.push(unwrap_memory(to));305let signature = ty.unwrap_func();306let index = dfg.trampolines.push((307signature.unwrap_module_type_index(),308dfg::Trampoline::Transcoder {309op: *op,310from,311from64: *from64,312to,313to64: *to64,314},315));316dfg::CoreDef::Trampoline(index)317}318fact::Import::ResourceTransferOwn => simple_intrinsic(dfg::Trampoline::ResourceTransferOwn),319fact::Import::ResourceTransferBorrow => {320simple_intrinsic(dfg::Trampoline::ResourceTransferBorrow)321}322fact::Import::ResourceEnterCall => simple_intrinsic(dfg::Trampoline::ResourceEnterCall),323fact::Import::ResourceExitCall => simple_intrinsic(dfg::Trampoline::ResourceExitCall),324fact::Import::PrepareCall { memory } => simple_intrinsic(dfg::Trampoline::PrepareCall {325memory: memory.as_ref().map(|v| dfg.memories.push(unwrap_memory(v))),326}),327fact::Import::SyncStartCall { callback } => {328simple_intrinsic(dfg::Trampoline::SyncStartCall {329callback: callback.clone().map(|v| dfg.callbacks.push(v)),330})331}332fact::Import::AsyncStartCall {333callback,334post_return,335} => simple_intrinsic(dfg::Trampoline::AsyncStartCall {336callback: callback.clone().map(|v| dfg.callbacks.push(v)),337post_return: post_return.clone().map(|v| dfg.post_returns.push(v)),338}),339fact::Import::FutureTransfer => simple_intrinsic(dfg::Trampoline::FutureTransfer),340fact::Import::StreamTransfer => simple_intrinsic(dfg::Trampoline::StreamTransfer),341fact::Import::ErrorContextTransfer => {342simple_intrinsic(dfg::Trampoline::ErrorContextTransfer)343}344}345}346347#[derive(Default)]348struct PartitionAdapterModules {349/// The next adapter module that's being created. This may be empty.350next_module: AdapterModuleInProgress,351352/// The set of items which are known to be defined which the adapter module353/// in progress is allowed to depend on.354defined_items: HashSet<Def>,355356/// Finished adapter modules that won't be added to.357///358/// In theory items could be added to preexisting modules here but to keep359/// this pass linear this is never modified after insertion.360adapter_modules: PrimaryMap<dfg::AdapterModuleId, AdapterModuleInProgress>,361}362363#[derive(Default)]364struct AdapterModuleInProgress {365/// The adapters which have been placed into this module.366adapters: Vec<dfg::AdapterId>,367}368369/// Items that adapters can depend on.370///371/// Note that this is somewhat of a flat list and is intended to mostly model372/// core wasm instances which are side-effectful unlike other host items like373/// lowerings or always-trapping functions.374#[derive(Copy, Clone, Hash, Eq, PartialEq)]375enum Def {376Adapter(dfg::AdapterId),377Instance(dfg::InstanceId),378}379380impl PartitionAdapterModules {381fn adapter(&mut self, dfg: &dfg::ComponentDfg, id: dfg::AdapterId, adapter: &Adapter) {382// Visit all dependencies of this adapter and if anything depends on383// the current adapter module in progress then a new adapter module is384// started.385self.adapter_options(dfg, &adapter.lift_options);386self.adapter_options(dfg, &adapter.lower_options);387self.core_def(dfg, &adapter.func);388389// With all dependencies visited this adapter is added to the next390// module.391//392// This will either get added the preexisting module if this adapter393// didn't depend on anything in that module itself or it will be added394// to a fresh module if this adapter depended on something that the395// current adapter module created.396log::debug!("adding {id:?} to adapter module");397self.next_module.adapters.push(id);398}399400fn adapter_options(&mut self, dfg: &dfg::ComponentDfg, options: &AdapterOptions) {401if let Some(def) = &options.callback {402self.core_def(dfg, def);403}404if let Some(def) = &options.post_return {405self.core_def(dfg, def);406}407match &options.data_model {408DataModel::Gc {} => {409// Nothing to do here yet.410}411DataModel::LinearMemory {412memory,413memory64: _,414realloc,415} => {416if let Some(memory) = memory {417self.core_export(dfg, memory);418}419if let Some(def) = realloc {420self.core_def(dfg, def);421}422}423}424}425426fn core_def(&mut self, dfg: &dfg::ComponentDfg, def: &dfg::CoreDef) {427match def {428dfg::CoreDef::Export(e) => self.core_export(dfg, e),429dfg::CoreDef::Adapter(id) => {430// If this adapter is already defined then we can safely depend431// on it with no consequences.432if self.defined_items.contains(&Def::Adapter(*id)) {433log::debug!("using existing adapter {id:?} ");434return;435}436437log::debug!("splitting module needing {id:?} ");438439// .. otherwise we found a case of an adapter depending on an440// adapter-module-in-progress meaning that the current adapter441// module must be completed and then a new one is started.442self.finish_adapter_module();443assert!(self.defined_items.contains(&Def::Adapter(*id)));444}445446// These items can't transitively depend on an adapter447dfg::CoreDef::Trampoline(_) | dfg::CoreDef::InstanceFlags(_) => {}448}449}450451fn core_export<T>(&mut self, dfg: &dfg::ComponentDfg, export: &dfg::CoreExport<T>) {452// When an adapter depends on an exported item it actually depends on453// the instance of that exported item. The caveat here is that the454// adapter not only depends on that particular instance, but also all455// prior instances to that instance as well because instance456// instantiation order is fixed and cannot change.457//458// To model this the instance index space is looped over here and while459// an instance hasn't been visited it's visited. Note that if an460// instance has already been visited then all prior instances have461// already been visited so there's no need to continue.462let mut instance = export.instance;463while self.defined_items.insert(Def::Instance(instance)) {464self.instance(dfg, instance);465if instance.as_u32() == 0 {466break;467}468instance = dfg::InstanceId::from_u32(instance.as_u32() - 1);469}470}471472fn instance(&mut self, dfg: &dfg::ComponentDfg, instance: dfg::InstanceId) {473log::debug!("visiting instance {instance:?}");474475// ... otherwise if this is the first timet he instance has been seen476// then the instances own arguments are recursively visited to find477// transitive dependencies on adapters.478match &dfg.instances[instance] {479dfg::Instance::Static(_, args) => {480for arg in args.iter() {481self.core_def(dfg, arg);482}483}484dfg::Instance::Import(_, args) => {485for (_, values) in args {486for (_, def) in values {487self.core_def(dfg, def);488}489}490}491}492}493494fn finish_adapter_module(&mut self) {495if self.next_module.adapters.is_empty() {496return;497}498499// Reset the state of the current module-in-progress and then flag all500// pending adapters as now defined since the current module is being501// committed.502let module = mem::take(&mut self.next_module);503for adapter in module.adapters.iter() {504let inserted = self.defined_items.insert(Def::Adapter(*adapter));505assert!(inserted);506}507let idx = self.adapter_modules.push(module);508log::debug!("finishing adapter module {idx:?}");509}510}511512513