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,6 +1,6 @@
//! Data structures to provide transformation of the source
// addresses of a WebAssembly module into the native code.
use crate::obj::ELF_WASMTIME_ADDRMAP;
use object::write::{Object, StandardSegment};
use object::{Bytes, LittleEndian, SectionKind, U32Bytes};
use serde::{Deserialize, Serialize};
@@ -65,35 +65,6 @@ pub struct AddressMapSection {
last_offset: u32,
}
/// A custom Wasmtime-specific section of our compilation image which stores
/// mapping data from offsets in the image to offset in the original wasm
/// binary.
///
/// This section has a custom binary encoding. Currently its encoding is:
///
/// * The section starts with a 32-bit little-endian integer. This integer is
/// how many entries are in the following two arrays.
/// * Next is an array with the previous count number of 32-bit little-endian
/// integers. This array is a sorted list of relative offsets within the text
/// section. This is intended to be a lookup array to perform a binary search
/// on an offset within the text section on this array.
/// * Finally there is another array, with the same count as before, also of
/// 32-bit little-endian integers. These integers map 1:1 with the previous
/// array of offsets, and correspond to what the original offset was in the
/// wasm file.
///
/// Decoding this section is intentionally simple, it only requires loading a
/// 32-bit little-endian integer plus some bounds checks. Reading this section
/// is done with the `lookup_file_pos` function below. Reading involves
/// performing a binary search on the first array using the index found for the
/// native code offset to index into the second array and find the wasm code
/// offset.
///
/// At this time this section has an alignment of 1, which means all reads of it
/// are unaligned. Additionally at this time the 32-bit encodings chosen here
/// mean that >=4gb text sections are not supported.
pub const ELF_WASMTIME_ADDRMAP: &str = ".wasmtime.addrmap";
impl AddressMapSection {
/// Pushes a new set of instruction mapping information for a function added
/// in the exectuable.

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`]

View File

@@ -1,34 +1,8 @@
use crate::component::{
Component, ComponentTypes, LowerImport, LoweredIndex, RuntimeAlwaysTrapIndex,
RuntimeTranscoderIndex, Transcoder,
};
use crate::{PrimaryMap, SignatureIndex, Trampoline, WasmFuncType};
use crate::component::{Component, ComponentTypes, LowerImport, Transcoder};
use crate::WasmFuncType;
use anyhow::Result;
use object::write::Object;
use serde::{Deserialize, Serialize};
use std::any::Any;
/// Description of where a trampoline is located in the text section of a
/// compiled image.
#[derive(Serialize, Deserialize)]
pub struct FunctionInfo {
/// The byte offset from the start of the text section where this trampoline
/// starts.
pub start: u32,
/// The byte length of this trampoline's function body.
pub length: u32,
}
/// Description of an "always trap" function generated by
/// `ComponentCompiler::compile_always_trap`.
#[derive(Serialize, Deserialize)]
pub struct AlwaysTrapInfo {
/// Information about the extent of this generated function.
pub info: FunctionInfo,
/// The offset from `start` of where the trapping instruction is located.
pub trap_offset: u32,
}
/// Compilation support necessary for components.
pub trait ComponentCompiler: Send + Sync {
/// Creates a trampoline for a `canon.lower`'d host function.
@@ -79,26 +53,4 @@ pub trait ComponentCompiler: Send + Sync {
transcoder: &Transcoder,
types: &ComponentTypes,
) -> Result<Box<dyn Any + Send>>;
/// Emits the `lowerings` and `trampolines` specified into the in-progress
/// ELF object specified by `obj`.
///
/// Returns a map of trampoline information for where to find them all in
/// the text section.
///
/// Note that this will also prepare unwinding information for all the
/// trampolines as necessary.
fn emit_obj(
&self,
lowerings: PrimaryMap<LoweredIndex, Box<dyn Any + Send>>,
always_trap: PrimaryMap<RuntimeAlwaysTrapIndex, Box<dyn Any + Send>>,
transcoders: PrimaryMap<RuntimeTranscoderIndex, Box<dyn Any + Send>>,
tramplines: Vec<(SignatureIndex, Box<dyn Any + Send>)>,
obj: &mut Object<'static>,
) -> Result<(
PrimaryMap<LoweredIndex, FunctionInfo>,
PrimaryMap<RuntimeAlwaysTrapIndex, AlwaysTrapInfo>,
PrimaryMap<RuntimeTranscoderIndex, FunctionInfo>,
Vec<Trampoline>,
)>;
}

View File

@@ -1,33 +1,121 @@
//! Utilities for working with object files that operate as Wasmtime's
//! serialization and intermediate format for compiled modules.
use crate::{EntityRef, FuncIndex, SignatureIndex};
/// Filler for the `os_abi` field of the ELF header.
///
/// This is just a constant that seems reasonable in the sense it's unlikely to
/// clash with others.
pub const ELFOSABI_WASMTIME: u8 = 200;
const FUNCTION_PREFIX: &str = "_wasm_function_";
const TRAMPOLINE_PREFIX: &str = "_trampoline_";
/// Flag for the `e_flags` field in the ELF header indicating a compiled
/// module.
pub const EF_WASMTIME_MODULE: u32 = 1 << 0;
/// Returns the symbol name in an object file for the corresponding wasm
/// function index in a module.
pub fn func_symbol_name(index: FuncIndex) -> String {
format!("{}{}", FUNCTION_PREFIX, index.index())
}
/// Flag for the `e_flags` field in the ELF header indicating a compiled
/// component.
pub const EF_WASMTIME_COMPONENT: u32 = 1 << 1;
/// Attempts to extract the corresponding function index from a symbol possibly produced by
/// `func_symbol_name`.
pub fn try_parse_func_name(name: &str) -> Option<FuncIndex> {
let n = name.strip_prefix(FUNCTION_PREFIX)?.parse().ok()?;
Some(FuncIndex::new(n))
}
/// A custom Wasmtime-specific section of our compilation image which stores
/// mapping data from offsets in the image to offset in the original wasm
/// binary.
///
/// This section has a custom binary encoding. Currently its encoding is:
///
/// * The section starts with a 32-bit little-endian integer. This integer is
/// how many entries are in the following two arrays.
/// * Next is an array with the previous count number of 32-bit little-endian
/// integers. This array is a sorted list of relative offsets within the text
/// section. This is intended to be a lookup array to perform a binary search
/// on an offset within the text section on this array.
/// * Finally there is another array, with the same count as before, also of
/// 32-bit little-endian integers. These integers map 1:1 with the previous
/// array of offsets, and correspond to what the original offset was in the
/// wasm file.
///
/// Decoding this section is intentionally simple, it only requires loading a
/// 32-bit little-endian integer plus some bounds checks. Reading this section
/// is done with the `lookup_file_pos` function below. Reading involves
/// performing a binary search on the first array using the index found for the
/// native code offset to index into the second array and find the wasm code
/// offset.
///
/// At this time this section has an alignment of 1, which means all reads of it
/// are unaligned. Additionally at this time the 32-bit encodings chosen here
/// mean that >=4gb text sections are not supported.
pub const ELF_WASMTIME_ADDRMAP: &str = ".wasmtime.addrmap";
/// Returns the symbol name in an object file for the corresponding trampoline
/// for the given signature in a module.
pub fn trampoline_symbol_name(index: SignatureIndex) -> String {
format!("{}{}", TRAMPOLINE_PREFIX, index.index())
}
/// A custom binary-encoded section of wasmtime compilation artifacts which
/// encodes the ability to map an offset in the text section to the trap code
/// that it corresponds to.
///
/// This section is used at runtime to determine what flavor fo trap happened to
/// ensure that embedders and debuggers know the reason for the wasm trap. The
/// encoding of this section is custom to Wasmtime and managed with helpers in
/// the `object` crate:
///
/// * First the section has a 32-bit little endian integer indicating how many
/// trap entries are in the section.
/// * Next is an array, of the same length as read before, of 32-bit
/// little-endian integers. These integers are offsets into the text section
/// of the compilation image.
/// * Finally is the same count number of bytes. Each of these bytes corresponds
/// to a trap code.
///
/// This section is decoded by `lookup_trap_code` below which will read the
/// section count, slice some bytes to get the various arrays, and then perform
/// a binary search on the offsets array to find the an index corresponding to
/// the pc being looked up. If found the same index in the trap array (the array
/// of bytes) is the trap code for that offset.
///
/// Note that at this time this section has an alignment of 1. Additionally due
/// to the 32-bit encodings for offsets this doesn't support images >=4gb.
pub const ELF_WASMTIME_TRAPS: &str = ".wasmtime.traps";
/// Attempts to extract the corresponding signature index from a symbol
/// possibly produced by `trampoline_symbol_name`.
pub fn try_parse_trampoline_name(name: &str) -> Option<SignatureIndex> {
let n = name.strip_prefix(TRAMPOLINE_PREFIX)?.parse().ok()?;
Some(SignatureIndex::new(n))
}
/// A custom section which consists of just 1 byte which is either 0 or 1 as to
/// whether BTI is enabled.
pub const ELF_WASM_BTI: &str = ".wasmtime.bti";
/// A bincode-encoded section containing engine-specific metadata used to
/// double-check that an artifact can be loaded into the current host.
pub const ELF_WASM_ENGINE: &str = ".wasmtime.engine";
/// This is the name of the section in the final ELF image which contains
/// concatenated data segments from the original wasm module.
///
/// This section is simply a list of bytes and ranges into this section are
/// stored within a `Module` for each data segment. Memory initialization and
/// passive segment management all index data directly located in this section.
///
/// Note that this implementation does not afford any method of leveraging the
/// `data.drop` instruction to actually release the data back to the OS. The
/// data section is simply always present in the ELF image. If we wanted to
/// release the data it's probably best to figure out what the best
/// implementation is for it at the time given a particular set of constraints.
pub const ELF_WASM_DATA: &'static str = ".rodata.wasm";
/// This is the name of the section in the final ELF image which contains a
/// `bincode`-encoded `CompiledModuleInfo`.
///
/// This section is optionally decoded in `CompiledModule::from_artifacts`
/// depending on whether or not a `CompiledModuleInfo` is already available. In
/// cases like `Module::new` where compilation directly leads into consumption,
/// it's available. In cases like `Module::deserialize` this section must be
/// decoded to get all the relevant information.
pub const ELF_WASMTIME_INFO: &'static str = ".wasmtime.info";
/// This is the name of the section in the final ELF image which contains a
/// concatenated list of all function names.
///
/// This section is optionally included in the final artifact depending on
/// whether the wasm module has any name data at all (or in the future if we add
/// an option to not preserve name data). This section is a concatenated list of
/// strings where `CompiledModuleInfo::func_names` stores offsets/lengths into
/// this section.
///
/// Note that the goal of this section is to avoid having to decode names at
/// module-load time if we can. Names are typically only used for debugging or
/// things like backtraces so there's no need to eagerly load all of them. By
/// storing the data in a separate section the hope is that the data, which is
/// sometimes quite large (3MB seen for spidermonkey-compiled-to-wasm), can be
/// paged in lazily from an mmap and is never paged in if we never reference it.
pub const ELF_NAME_DATA: &'static str = ".name.wasm";

View File

@@ -1,3 +1,4 @@
use crate::obj::ELF_WASMTIME_TRAPS;
use object::write::{Object, StandardSegment};
use object::{Bytes, LittleEndian, SectionKind, U32Bytes};
use std::convert::TryFrom;
@@ -16,33 +17,6 @@ pub struct TrapEncodingBuilder {
last_offset: u32,
}
/// A custom binary-encoded section of wasmtime compilation artifacts which
/// encodes the ability to map an offset in the text section to the trap code
/// that it corresponds to.
///
/// This section is used at runtime to determine what flavor fo trap happened to
/// ensure that embedders and debuggers know the reason for the wasm trap. The
/// encoding of this section is custom to Wasmtime and managed with helpers in
/// the `object` crate:
///
/// * First the section has a 32-bit little endian integer indicating how many
/// trap entries are in the section.
/// * Next is an array, of the same length as read before, of 32-bit
/// little-endian integers. These integers are offsets into the text section
/// of the compilation image.
/// * Finally is the same count number of bytes. Each of these bytes corresponds
/// to a trap code.
///
/// This section is decoded by `lookup_trap_code` below which will read the
/// section count, slice some bytes to get the various arrays, and then perform
/// a binary search on the offsets array to find the an index corresponding to
/// the pc being looked up. If found the same index in the trap array (the array
/// of bytes) is the trap code for that offset.
///
/// Note that at this time this section has an alignment of 1. Additionally due
/// to the 32-bit encodings for offsets this doesn't support images >=4gb.
pub const ELF_WASMTIME_TRAPS: &str = ".wasmtime.traps";
/// Information about trap.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TrapInformation {