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:
Alex Crichton
2022-07-25 18:13:26 -05:00
committed by GitHub
parent 78d3e0b693
commit 97894bc65e
33 changed files with 3182 additions and 170 deletions

View File

@@ -7,8 +7,8 @@
//! cranelift-compiled adapters, will use this `VMComponentContext` as well.
use crate::{
Store, VMCallerCheckedAnyfunc, VMFunctionBody, VMMemoryDefinition, VMOpaqueContext,
VMSharedSignatureIndex, ValRaw,
Store, VMCallerCheckedAnyfunc, VMFunctionBody, VMGlobalDefinition, VMMemoryDefinition,
VMOpaqueContext, VMSharedSignatureIndex, ValRaw,
};
use memoffset::offset_of;
use std::alloc::{self, Layout};
@@ -19,8 +19,7 @@ use std::ptr::{self, NonNull};
use wasmtime_environ::component::{
Component, LoweredIndex, RuntimeAlwaysTrapIndex, RuntimeComponentInstanceIndex,
RuntimeMemoryIndex, RuntimePostReturnIndex, RuntimeReallocIndex, StringEncoding,
VMComponentOffsets, VMCOMPONENT_FLAG_MAY_ENTER, VMCOMPONENT_FLAG_MAY_LEAVE,
VMCOMPONENT_FLAG_NEEDS_POST_RETURN, VMCOMPONENT_MAGIC,
VMComponentOffsets, FLAG_MAY_ENTER, FLAG_MAY_LEAVE, FLAG_NEEDS_POST_RETURN, VMCOMPONENT_MAGIC,
};
use wasmtime_environ::HostPtr;
@@ -75,7 +74,7 @@ pub struct ComponentInstance {
pub type VMLoweringCallee = extern "C" fn(
vmctx: *mut VMOpaqueContext,
data: *mut u8,
flags: *mut VMComponentFlags,
flags: InstanceFlags,
opt_memory: *mut VMMemoryDefinition,
opt_realloc: *mut VMCallerCheckedAnyfunc,
string_encoding: StringEncoding,
@@ -114,11 +113,6 @@ pub struct VMComponentContext {
_marker: marker::PhantomPinned,
}
/// Flags stored in a `VMComponentContext` with values defined by
/// `VMCOMPONENT_FLAG_*`
#[repr(transparent)]
pub struct VMComponentFlags(u8);
impl ComponentInstance {
/// Returns the layout corresponding to what would be an allocation of a
/// `ComponentInstance` for the `offsets` provided.
@@ -174,8 +168,8 @@ impl ComponentInstance {
/// Returns a pointer to the "may leave" flag for this instance specified
/// for canonical lowering and lifting operations.
pub fn flags(&self, instance: RuntimeComponentInstanceIndex) -> *mut VMComponentFlags {
unsafe { self.vmctx_plus_offset(self.offsets.flags(instance)) }
pub fn instance_flags(&self, instance: RuntimeComponentInstanceIndex) -> InstanceFlags {
unsafe { InstanceFlags(self.vmctx_plus_offset(self.offsets.instance_flags(instance))) }
}
/// Returns the store that this component was created with.
@@ -381,7 +375,9 @@ impl ComponentInstance {
*self.vmctx_plus_offset(self.offsets.store()) = store;
for i in 0..self.offsets.num_runtime_component_instances {
let i = RuntimeComponentInstanceIndex::from_u32(i);
*self.flags(i) = VMComponentFlags::new();
let mut def = VMGlobalDefinition::new();
*def.as_i32_mut() = FLAG_MAY_ENTER | FLAG_MAY_LEAVE;
*self.instance_flags(i).0 = def;
}
// In debug mode set non-null bad values to all "pointer looking" bits
@@ -569,52 +565,57 @@ impl VMOpaqueContext {
}
#[allow(missing_docs)]
impl VMComponentFlags {
fn new() -> VMComponentFlags {
VMComponentFlags(VMCOMPONENT_FLAG_MAY_LEAVE | VMCOMPONENT_FLAG_MAY_ENTER)
#[repr(transparent)]
pub struct InstanceFlags(*mut VMGlobalDefinition);
#[allow(missing_docs)]
impl InstanceFlags {
#[inline]
pub unsafe fn may_leave(&self) -> bool {
*(*self.0).as_i32() & FLAG_MAY_LEAVE != 0
}
#[inline]
pub fn may_leave(&self) -> bool {
self.0 & VMCOMPONENT_FLAG_MAY_LEAVE != 0
}
#[inline]
pub fn set_may_leave(&mut self, val: bool) {
pub unsafe fn set_may_leave(&mut self, val: bool) {
if val {
self.0 |= VMCOMPONENT_FLAG_MAY_LEAVE;
*(*self.0).as_i32_mut() |= FLAG_MAY_LEAVE;
} else {
self.0 &= !VMCOMPONENT_FLAG_MAY_LEAVE;
*(*self.0).as_i32_mut() &= !FLAG_MAY_LEAVE;
}
}
#[inline]
pub fn may_enter(&self) -> bool {
self.0 & VMCOMPONENT_FLAG_MAY_ENTER != 0
pub unsafe fn may_enter(&self) -> bool {
*(*self.0).as_i32() & FLAG_MAY_ENTER != 0
}
#[inline]
pub fn set_may_enter(&mut self, val: bool) {
pub unsafe fn set_may_enter(&mut self, val: bool) {
if val {
self.0 |= VMCOMPONENT_FLAG_MAY_ENTER;
*(*self.0).as_i32_mut() |= FLAG_MAY_ENTER;
} else {
self.0 &= !VMCOMPONENT_FLAG_MAY_ENTER;
*(*self.0).as_i32_mut() &= !FLAG_MAY_ENTER;
}
}
#[inline]
pub fn needs_post_return(&self) -> bool {
self.0 & VMCOMPONENT_FLAG_NEEDS_POST_RETURN != 0
pub unsafe fn needs_post_return(&self) -> bool {
*(*self.0).as_i32() & FLAG_NEEDS_POST_RETURN != 0
}
#[inline]
pub fn set_needs_post_return(&mut self, val: bool) {
pub unsafe fn set_needs_post_return(&mut self, val: bool) {
if val {
self.0 |= VMCOMPONENT_FLAG_NEEDS_POST_RETURN;
*(*self.0).as_i32_mut() |= FLAG_NEEDS_POST_RETURN;
} else {
self.0 &= !VMCOMPONENT_FLAG_NEEDS_POST_RETURN;
*(*self.0).as_i32_mut() &= !FLAG_NEEDS_POST_RETURN;
}
}
#[inline]
pub fn as_raw(&self) -> *mut VMGlobalDefinition {
self.0
}
}
#[cfg(test)]

View File

@@ -90,9 +90,6 @@ impl From<ExportMemory> for Export {
pub struct ExportGlobal {
/// The address of the global storage.
pub definition: *mut VMGlobalDefinition,
/// Pointer to a `VMContext` which has a lifetime at least as long as the
/// global. This may not be the `VMContext` which defines the global.
pub vmctx: *mut VMContext,
/// The global declaration, used for compatibilty checking.
pub global: Global,
}

View File

@@ -330,7 +330,6 @@ impl Instance {
} else {
self.imported_global(index).from
},
vmctx: self.vmctx_ptr(),
global: self.module().globals[index],
}
}

View File

@@ -334,7 +334,7 @@ mod test_vmglobal_definition {
use crate::externref::VMExternRef;
use more_asserts::assert_ge;
use std::mem::{align_of, size_of};
use wasmtime_environ::{Module, VMOffsets};
use wasmtime_environ::{Module, PtrSize, VMOffsets};
#[test]
fn check_vmglobal_definition_alignment() {
@@ -351,7 +351,7 @@ mod test_vmglobal_definition {
let offsets = VMOffsets::new(size_of::<*mut u8>() as u8, &module);
assert_eq!(
size_of::<VMGlobalDefinition>(),
usize::from(offsets.size_of_vmglobal_definition())
usize::from(offsets.ptr.size_of_vmglobal_definition())
);
}
@@ -676,7 +676,7 @@ pub struct VMInvokeArgument([u8; 16]);
mod test_vm_invoke_argument {
use super::VMInvokeArgument;
use std::mem::{align_of, size_of};
use wasmtime_environ::{Module, VMOffsets};
use wasmtime_environ::{Module, PtrSize, VMOffsets};
#[test]
fn check_vm_invoke_argument_alignment() {
@@ -689,7 +689,7 @@ mod test_vm_invoke_argument {
let offsets = VMOffsets::new(size_of::<*mut u8>() as u8, &module);
assert_eq!(
size_of::<VMInvokeArgument>(),
usize::from(offsets.size_of_vmglobal_definition())
usize::from(offsets.ptr.size_of_vmglobal_definition())
);
}
}