Implement AOT compilation for components (#5160)

* Pull `Module` out of `ModuleTextBuilder`

This commit is the first in what will likely be a number towards
preparing for serializing a compiled component to bytes, a precompiled
artifact. To that end my rough plan is to merge all of the compiled
artifacts for a component into one large object file instead of having
lots of separate object files and lots of separate mmaps to manage. To
that end I plan on eventually using `ModuleTextBuilder` to build one
large text section for all core wasm modules and trampolines, meaning
that `ModuleTextBuilder` is no longer specific to one module. I've
extracted out functionality such as function name calculation as well as
relocation resolving (now a closure passed in) in preparation for this.

For now this just keeps tests passing, and the trajectory for this
should become more clear over the following commits.

* Remove component-specific object emission

This commit removes the `ComponentCompiler::emit_obj` function in favor
of `Compiler::emit_obj`, now renamed `append_code`. This involved
significantly refactoring code emission to take a flat list of functions
into `append_code` and the caller is responsible for weaving together
various "families" of functions and un-weaving them afterwards.

* Consolidate ELF parsing in `CodeMemory`

This commit moves the ELF file parsing and section iteration from
`CompiledModule` into `CodeMemory` so one location keeps track of
section ranges and such. This is in preparation for sharing much of this
code with components which needs all the same sections to get tracked
but won't be using `CompiledModule`. A small side benefit from this is
that the section parsing done in `CodeMemory` and `CompiledModule` is no
longer duplicated.

* Remove separately tracked traps in components

Previously components would generate an "always trapping" function
and the metadata around which pc was allowed to trap was handled
manually for components. With recent refactorings the Wasmtime-standard
trap section in object files is now being generated for components as
well which means that can be reused instead of custom-tracking this
metadata. This commit removes the manual tracking for the `always_trap`
functions and plumbs the necessary bits around to make components look
more like modules.

* Remove a now-unnecessary `Arc` in `Module`

Not expected to have any measurable impact on performance, but
complexity-wise this should make it a bit easier to understand the
internals since there's no longer any need to store this somewhere else
than its owner's location.

* Merge compilation artifacts of components

This commit is a large refactoring of the component compilation process
to produce a single artifact instead of multiple binary artifacts. The
core wasm compilation process is refactored as well to share as much
code as necessary with the component compilation process.

This method of representing a compiled component necessitated a few
medium-sized changes internally within Wasmtime:

* A new data structure was created, `CodeObject`, which represents
  metadata about a single compiled artifact. This is then stored as an
  `Arc` within a component and a module. For `Module` this is always
  uniquely owned and represents a shuffling around of data from one
  owner to another. For a `Component`, however, this is shared amongst
  all loaded modules and the top-level component.

* The "module registry" which is used for symbolicating backtraces and
  for trap information has been updated to account for a single region
  of loaded code holding possibly multiple modules. This involved adding
  a second-level `BTreeMap` for now. This will likely slow down
  instantiation slightly but if it poses an issue in the future this
  should be able to be represented with a more clever data structure.

This commit additionally solves a number of longstanding issues with
components such as compiling only one host-to-wasm trampoline per
signature instead of possibly once-per-module. Additionally the
`SignatureCollection` registration now happens once-per-component
instead of once-per-module-within-a-component.

* Fix compile errors from prior commits

* Support AOT-compiling components

This commit adds support for AOT-compiled components in the same manner
as `Module`, specifically adding:

* `Engine::precompile_component`
* `Component::serialize`
* `Component::deserialize`
* `Component::deserialize_file`

Internally the support for components looks quite similar to `Module`.
All the prior commits to this made adding the support here
(unsurprisingly) easy. Components are represented as a single object
file as are modules, and the functions for each module are all piled
into the same object file next to each other (as are areas such as data
sections). Support was also added here to quickly differentiate compiled
components vs compiled modules via the `e_flags` field in the ELF
header.

* Prevent serializing exported modules on components

The current representation of a module within a component means that the
implementation of `Module::serialize` will not work if the module is
exported from a component. The reason for this is that `serialize`
doesn't actually do anything and simply returns the underlying mmap as a
list of bytes. The mmap, however, has `.wasmtime.info` describing
component metadata as opposed to this module's metadata. While rewriting
this section could be implemented it's not so easy to do so and is
otherwise seen as not super important of a feature right now anyway.

* Fix windows build

* Fix an unused function warning

* Update crates/environ/src/compilation.rs

Co-authored-by: Nick Fitzgerald <fitzgen@gmail.com>

Co-authored-by: Nick Fitzgerald <fitzgen@gmail.com>
This commit is contained in:
Alex Crichton
2022-11-02 10:26:26 -05:00
committed by GitHub
parent 033758daaf
commit cd53bed898
45 changed files with 1991 additions and 1763 deletions

View File

@@ -1,13 +1,14 @@
//! A `Compilation` contains the compiled function bodies for a WebAssembly
//! module.
use crate::obj;
use crate::{
DefinedFuncIndex, FilePos, FunctionBodyData, ModuleTranslation, ModuleTypes, PrimaryMap,
SignatureIndex, StackMap, Tunables, WasmError, WasmFuncType,
DefinedFuncIndex, FilePos, FuncIndex, FunctionBodyData, ModuleTranslation, ModuleTypes,
PrimaryMap, StackMap, Tunables, WasmError, WasmFuncType,
};
use anyhow::Result;
use object::write::Object;
use object::{Architecture, BinaryFormat};
use object::write::{Object, SymbolId};
use object::{Architecture, BinaryFormat, FileFlags};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::borrow::Cow;
@@ -20,30 +21,19 @@ use thiserror::Error;
/// and stack maps.
#[derive(Serialize, Deserialize, Default)]
#[allow(missing_docs)]
pub struct FunctionInfo {
pub struct WasmFunctionInfo {
pub start_srcloc: FilePos,
pub stack_maps: Vec<StackMapInformation>,
/// Offset in the text section of where this function starts.
pub start: u64,
/// The size of the compiled function, in bytes.
pub length: u32,
/// The alignment requirements of this function, in bytes.
pub alignment: u32,
pub stack_maps: Box<[StackMapInformation]>,
}
/// Information about a compiled trampoline which the host can call to enter
/// wasm.
#[derive(Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct Trampoline {
/// The signature this trampoline is for
pub signature: SignatureIndex,
/// Offset in the text section of where this function starts.
pub start: u64,
/// The size of the compiled function, in bytes.
/// Description of where a function is located in the text section of a
/// compiled image.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct FunctionLoc {
/// The byte offset from the start of the text section where this
/// function starts.
pub start: u32,
/// The byte length of this function's function body.
pub length: u32,
}
@@ -155,6 +145,14 @@ pub enum SettingKind {
Preset,
}
/// Types of objects that can be created by `Compiler::object`
pub enum ObjectKind {
/// A core wasm compilation artifact
Module,
/// A component compilation artifact
Component,
}
/// An implementation of a compiler which can compile WebAssembly functions to
/// machine code and perform other miscellaneous tasks needed by the JIT runtime.
pub trait Compiler: Send + Sync {
@@ -170,7 +168,7 @@ pub trait Compiler: Send + Sync {
data: FunctionBodyData<'_>,
tunables: &Tunables,
types: &ModuleTypes,
) -> Result<Box<dyn Any + Send>, CompileError>;
) -> Result<(WasmFunctionInfo, Box<dyn Any + Send>), CompileError>;
/// Creates a function of type `VMTrampoline` which will then call the
/// function pointer argument which has the `ty` type provided.
@@ -179,34 +177,35 @@ pub trait Compiler: Send + Sync {
ty: &WasmFuncType,
) -> Result<Box<dyn Any + Send>, CompileError>;
/// Collects the results of compilation into an in-memory object.
/// Appends a list of compiled functions to an in-memory object.
///
/// This function will receive the same `Box<dyn Ayn>` produced as part of
/// `compile_function`, as well as the general compilation environment with
/// the translation. THe `trampolines` argument is generated by
/// `compile_host_to_wasm_trampoline` for each of
/// `module.exported_signatures`. This method is expected to populate
/// information in the object file such as:
/// compilation from functions like `compile_function`,
/// compile_host_to_wasm_trampoline`, and other component-related shims.
/// Internally this will take all of these functions and add information to
/// the object such as:
///
/// * Compiled code in a `.text` section
/// * Unwind information in Wasmtime-specific sections
/// * DWARF debugging information for the host, if `emit_dwarf` is `true`
/// and the compiler supports it.
/// * Relocations, if necessary, for the text section
///
/// The final result of compilation will contain more sections inserted by
/// the compiler-agnostic runtime.
/// Each function is accompanied with its desired symbol name and the return
/// value of this function is the symbol for each function as well as where
/// each function was placed within the object.
///
/// This function returns information about the compiled functions (where
/// they are in the text section) along with where trampolines are located.
fn emit_obj(
/// The `resolve_reloc` argument is intended to resolving relocations
/// between function, chiefly resolving intra-module calls within one core
/// wasm module. The closure here takes two arguments: first the index
/// within `funcs` that is being resolved and next the `FuncIndex` which is
/// the relocation target to resolve. The return value is an index within
/// `funcs` that the relocation points to.
fn append_code(
&self,
module: &ModuleTranslation,
funcs: PrimaryMap<DefinedFuncIndex, Box<dyn Any + Send>>,
trampolines: Vec<Box<dyn Any + Send>>,
tunables: &Tunables,
obj: &mut Object<'static>,
) -> Result<(PrimaryMap<DefinedFuncIndex, FunctionInfo>, Vec<Trampoline>)>;
funcs: &[(String, Box<dyn Any + Send>)],
tunables: &Tunables,
resolve_reloc: &dyn Fn(usize, FuncIndex) -> usize,
) -> Result<Vec<(SymbolId, FunctionLoc)>>;
/// Inserts two functions for host-to-wasm and wasm-to-host trampolines into
/// the `obj` provided.
@@ -220,7 +219,7 @@ pub trait Compiler: Send + Sync {
ty: &WasmFuncType,
host_fn: usize,
obj: &mut Object<'static>,
) -> Result<(Trampoline, Trampoline)>;
) -> Result<(FunctionLoc, FunctionLoc)>;
/// Creates a new `Object` file which is used to build the results of a
/// compilation into.
@@ -228,11 +227,11 @@ pub trait Compiler: Send + Sync {
/// The returned object file will have an appropriate
/// architecture/endianness for `self.triple()`, but at this time it is
/// always an ELF file, regardless of target platform.
fn object(&self) -> Result<Object<'static>> {
fn object(&self, kind: ObjectKind) -> Result<Object<'static>> {
use target_lexicon::Architecture::*;
let triple = self.triple();
Ok(Object::new(
let mut obj = Object::new(
BinaryFormat::Elf,
match triple.architecture {
X86_32(_) => Architecture::I386,
@@ -249,7 +248,16 @@ pub trait Compiler: Send + Sync {
target_lexicon::Endianness::Little => object::Endianness::Little,
target_lexicon::Endianness::Big => object::Endianness::Big,
},
))
);
obj.flags = FileFlags::Elf {
os_abi: obj::ELFOSABI_WASMTIME,
e_flags: match kind {
ObjectKind::Module => obj::EF_WASMTIME_MODULE,
ObjectKind::Component => obj::EF_WASMTIME_COMPONENT,
},
abi_version: 0,
};
Ok(obj)
}
/// Returns the target triple that this compiler is compiling for.
@@ -276,6 +284,15 @@ pub trait Compiler: Send + Sync {
/// `Self` in which case this function would simply return `self`.
#[cfg(feature = "component-model")]
fn component_compiler(&self) -> &dyn crate::component::ComponentCompiler;
/// Appends generated DWARF sections to the `obj` specified for the compiled
/// functions.
fn append_dwarf(
&self,
obj: &mut Object<'_>,
translation: &ModuleTranslation<'_>,
funcs: &PrimaryMap<DefinedFuncIndex, (SymbolId, &(dyn Any + Send))>,
) -> Result<()>;
}
/// Value of a configured setting for a [`Compiler`]