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,16 +1,16 @@
//! Memory management for executable code.
use crate::subslice_range;
use crate::unwind::UnwindRegistration;
use anyhow::{anyhow, bail, Context, Result};
use object::read::{File, Object, ObjectSection};
use std::ffi::c_void;
use std::mem;
use std::mem::ManuallyDrop;
use std::ops::Range;
use wasmtime_environ::obj;
use wasmtime_environ::FunctionLoc;
use wasmtime_jit_icache_coherence as icache_coherence;
use wasmtime_runtime::MmapVec;
/// Name of the section in ELF files indicating that branch protection was
/// enabled for the compiled code.
pub const ELF_WASM_BTI: &str = ".wasmtime.bti";
use wasmtime_runtime::{MmapVec, VMTrampoline};
/// Management of executable memory within a `MmapVec`
///
@@ -22,6 +22,20 @@ pub struct CodeMemory {
mmap: ManuallyDrop<MmapVec>,
unwind_registration: ManuallyDrop<Option<UnwindRegistration>>,
published: bool,
enable_branch_protection: bool,
// Ranges within `self.mmap` of where the particular sections lie.
text: Range<usize>,
unwind: Range<usize>,
trap_data: Range<usize>,
wasm_data: Range<usize>,
address_map_data: Range<usize>,
func_name_data: Range<usize>,
info_data: Range<usize>,
/// Map of dwarf sections indexed by `gimli::SectionId` which points to the
/// range within `code_memory`'s mmap as to the contents of the section.
dwarf_sections: Vec<Range<usize>>,
}
impl Drop for CodeMemory {
@@ -39,32 +53,115 @@ fn _assert() {
_assert_send_sync::<CodeMemory>();
}
/// Result of publishing a `CodeMemory`, containing references to the parsed
/// internals.
pub struct Publish<'a> {
/// The parsed ELF image that resides within the original `MmapVec`.
pub obj: File<'a>,
/// Reference to the entire `MmapVec` and its contents.
pub mmap: &'a MmapVec,
/// Reference to just the text section of the object file, a subslice of
/// `mmap`.
pub text: &'a [u8],
}
impl CodeMemory {
/// Creates a new `CodeMemory` by taking ownership of the provided
/// `MmapVec`.
///
/// The returned `CodeMemory` manages the internal `MmapVec` and the
/// `publish` method is used to actually make the memory executable.
pub fn new(mmap: MmapVec) -> Self {
Self {
pub fn new(mmap: MmapVec) -> Result<Self> {
use gimli::SectionId::*;
let obj = File::parse(&mmap[..])
.with_context(|| "failed to parse internal compilation artifact")?;
let mut text = 0..0;
let mut unwind = 0..0;
let mut enable_branch_protection = None;
let mut trap_data = 0..0;
let mut wasm_data = 0..0;
let mut address_map_data = 0..0;
let mut func_name_data = 0..0;
let mut info_data = 0..0;
let mut dwarf_sections = Vec::new();
for section in obj.sections() {
let data = section.data()?;
let name = section.name()?;
let range = subslice_range(data, &mmap);
// Double-check that sections are all aligned properly.
if section.align() != 0 && data.len() != 0 {
if (data.as_ptr() as u64 - mmap.as_ptr() as u64) % section.align() != 0 {
bail!(
"section `{}` isn't aligned to {:#x}",
section.name().unwrap_or("ERROR"),
section.align()
);
}
}
let mut gimli = |id: gimli::SectionId| {
let idx = id as usize;
if dwarf_sections.len() <= idx {
dwarf_sections.resize(idx + 1, 0..0);
}
dwarf_sections[idx] = range.clone();
};
match name {
obj::ELF_WASM_BTI => match data.len() {
1 => enable_branch_protection = Some(data[0] != 0),
_ => bail!("invalid `{name}` section"),
},
".text" => {
text = range;
// Double-check there are no relocations in the text section. At
// this time relocations are not expected at all from loaded code
// since everything should be resolved at compile time. Handling
// must be added here, though, if relocations pop up.
assert!(section.relocations().count() == 0);
}
UnwindRegistration::SECTION_NAME => unwind = range,
obj::ELF_WASM_DATA => wasm_data = range,
obj::ELF_WASMTIME_ADDRMAP => address_map_data = range,
obj::ELF_WASMTIME_TRAPS => trap_data = range,
obj::ELF_NAME_DATA => func_name_data = range,
obj::ELF_WASMTIME_INFO => info_data = range,
// Register dwarf sections into the `dwarf_sections`
// array which is indexed by `gimli::SectionId`
".debug_abbrev.wasm" => gimli(DebugAbbrev),
".debug_addr.wasm" => gimli(DebugAddr),
".debug_aranges.wasm" => gimli(DebugAranges),
".debug_frame.wasm" => gimli(DebugFrame),
".eh_frame.wasm" => gimli(EhFrame),
".eh_frame_hdr.wasm" => gimli(EhFrameHdr),
".debug_info.wasm" => gimli(DebugInfo),
".debug_line.wasm" => gimli(DebugLine),
".debug_line_str.wasm" => gimli(DebugLineStr),
".debug_loc.wasm" => gimli(DebugLoc),
".debug_loc_lists.wasm" => gimli(DebugLocLists),
".debug_macinfo.wasm" => gimli(DebugMacinfo),
".debug_macro.wasm" => gimli(DebugMacro),
".debug_pub_names.wasm" => gimli(DebugPubNames),
".debug_pub_types.wasm" => gimli(DebugPubTypes),
".debug_ranges.wasm" => gimli(DebugRanges),
".debug_rng_lists.wasm" => gimli(DebugRngLists),
".debug_str.wasm" => gimli(DebugStr),
".debug_str_offsets.wasm" => gimli(DebugStrOffsets),
".debug_types.wasm" => gimli(DebugTypes),
".debug_cu_index.wasm" => gimli(DebugCuIndex),
".debug_tu_index.wasm" => gimli(DebugTuIndex),
_ => log::debug!("ignoring section {name}"),
}
}
Ok(Self {
mmap: ManuallyDrop::new(mmap),
unwind_registration: ManuallyDrop::new(None),
published: false,
}
enable_branch_protection: enable_branch_protection
.ok_or_else(|| anyhow!("missing `{}` section", obj::ELF_WASM_BTI))?,
text,
unwind,
trap_data,
address_map_data,
func_name_data,
dwarf_sections,
info_data,
wasm_data,
})
}
/// Returns a reference to the underlying `MmapVec` this memory owns.
@@ -72,6 +169,67 @@ impl CodeMemory {
&self.mmap
}
/// Returns the contents of the text section of the ELF executable this
/// represents.
pub fn text(&self) -> &[u8] {
&self.mmap[self.text.clone()]
}
/// Returns the data in the corresponding dwarf section, or an empty slice
/// if the section wasn't present.
pub fn dwarf_section(&self, section: gimli::SectionId) -> &[u8] {
let range = self
.dwarf_sections
.get(section as usize)
.cloned()
.unwrap_or(0..0);
&self.mmap[range]
}
/// Returns the data in the `ELF_NAME_DATA` section.
pub fn func_name_data(&self) -> &[u8] {
&self.mmap[self.func_name_data.clone()]
}
/// Returns the concatenated list of all data associated with this wasm
/// module.
///
/// This is used for initialization of memories and all data ranges stored
/// in a `Module` are relative to the slice returned here.
pub fn wasm_data(&self) -> &[u8] {
&self.mmap[self.wasm_data.clone()]
}
/// Returns the encoded address map section used to pass to
/// `wasmtime_environ::lookup_file_pos`.
pub fn address_map_data(&self) -> &[u8] {
&self.mmap[self.address_map_data.clone()]
}
/// Returns the contents of the `ELF_WASMTIME_INFO` section, or an empty
/// slice if it wasn't found.
pub fn wasmtime_info(&self) -> &[u8] {
&self.mmap[self.info_data.clone()]
}
/// Returns the contents of the `ELF_WASMTIME_TRAPS` section, or an empty
/// slice if it wasn't found.
pub fn trap_data(&self) -> &[u8] {
&self.mmap[self.trap_data.clone()]
}
/// Returns a `VMTrampoline` function pointer for the given function in the
/// text section.
///
/// # Unsafety
///
/// This function is unsafe as there's no guarantee that the returned
/// function pointer is valid.
pub unsafe fn vmtrampoline(&self, loc: FunctionLoc) -> VMTrampoline {
let ptr = self.text()[loc.start as usize..][..loc.length as usize].as_ptr();
mem::transmute::<*const u8, VMTrampoline>(ptr)
}
/// Publishes the internal ELF image to be ready for execution.
///
/// This method can only be called once and will panic if called twice. This
@@ -82,99 +240,37 @@ impl CodeMemory {
/// * Register unwinding information with the OS
///
/// After this function executes all JIT code should be ready to execute.
/// The various parsed results of the internals of the `MmapVec` are
/// returned through the `Publish` structure.
pub fn publish(&mut self) -> Result<Publish<'_>> {
pub fn publish(&mut self) -> Result<()> {
assert!(!self.published);
self.published = true;
let mut ret = Publish {
obj: File::parse(&self.mmap[..])
.with_context(|| "failed to parse internal compilation artifact")?,
mmap: &self.mmap,
text: &[],
};
let mmap_ptr = self.mmap.as_ptr() as u64;
// Sanity-check that all sections are aligned correctly and
// additionally probe for a few sections that we're interested in.
let mut enable_branch_protection = None;
let mut text = None;
for section in ret.obj.sections() {
let data = match section.data() {
Ok(data) => data,
Err(_) => continue,
};
if section.align() == 0 || data.len() == 0 {
continue;
}
if (data.as_ptr() as u64 - mmap_ptr) % section.align() != 0 {
bail!(
"section `{}` isn't aligned to {:#x}",
section.name().unwrap_or("ERROR"),
section.align()
);
}
match section.name().unwrap_or("") {
ELF_WASM_BTI => match data.len() {
1 => enable_branch_protection = Some(data[0] != 0),
_ => bail!("invalid `{ELF_WASM_BTI}` section"),
},
".text" => {
ret.text = data;
text = Some(section);
}
_ => {}
}
if self.text().is_empty() {
return Ok(());
}
let enable_branch_protection =
enable_branch_protection.ok_or_else(|| anyhow!("missing `{ELF_WASM_BTI}` section"))?;
let text = match text {
Some(text) => text,
None => return Ok(ret),
};
// The unsafety here comes from a few things:
//
// * First in `apply_reloc` we're walking around the `File` that the
// `object` crate has to get a mutable view into the text section.
// Currently the `object` crate doesn't support easily parsing a file
// and updating small bits and pieces of it, so we work around it for
// now. ELF's file format should guarantee that `text_mut` doesn't
// collide with any memory accessed by `text.relocations()`.
// * We're actually updating some page protections to executable memory.
//
// * Second we're actually updating some page protections to executable
// memory.
//
// * Finally we're registering unwinding information which relies on the
// * We're registering unwinding information which relies on the
// correctness of the information in the first place. This applies to
// both the actual unwinding tables as well as the validity of the
// pointers we pass in itself.
unsafe {
let text_mut =
std::slice::from_raw_parts_mut(ret.text.as_ptr() as *mut u8, ret.text.len());
let text_offset = ret.text.as_ptr() as usize - ret.mmap.as_ptr() as usize;
let text_range = text_offset..text_offset + text_mut.len();
// Double-check there are no relocations in the text section. At
// this time relocations are not expected at all from loaded code
// since everything should be resolved at compile time. Handling
// must be added here, though, if relocations pop up.
assert!(text.relocations().count() == 0);
let text = self.text();
// Clear the newly allocated code from cache if the processor requires it
//
// Do this before marking the memory as R+X, technically we should be able to do it after
// but there are some CPU's that have had errata about doing this with read only memory.
icache_coherence::clear_cache(ret.text.as_ptr() as *const c_void, ret.text.len())
icache_coherence::clear_cache(text.as_ptr().cast(), text.len())
.expect("Failed cache clear");
// Switch the executable portion from read/write to
// read/execute, notably not using read/write/execute to prevent
// modifications.
self.mmap
.make_executable(text_range.clone(), enable_branch_protection)
.make_executable(self.text.clone(), self.enable_branch_protection)
.expect("unable to make memory executable");
// Flush any in-flight instructions from the pipeline
@@ -184,26 +280,22 @@ impl CodeMemory {
// `UnwindRegistration` implementation to inform the general
// runtime that there's unwinding information available for all
// our just-published JIT functions.
*self.unwind_registration = register_unwind_info(&ret.obj, ret.text)?;
self.register_unwind_info()?;
}
Ok(ret)
Ok(())
}
}
unsafe fn register_unwind_info(obj: &File, text: &[u8]) -> Result<Option<UnwindRegistration>> {
let unwind_info = match obj
.section_by_name(UnwindRegistration::section_name())
.and_then(|s| s.data().ok())
{
Some(info) => info,
None => return Ok(None),
};
if unwind_info.len() == 0 {
return Ok(None);
unsafe fn register_unwind_info(&mut self) -> Result<()> {
if self.unwind.len() == 0 {
return Ok(());
}
let text = self.text();
let unwind_info = &self.mmap[self.unwind.clone()];
let registration =
UnwindRegistration::new(text.as_ptr(), unwind_info.as_ptr(), unwind_info.len())
.context("failed to create unwind info registration")?;
*self.unwind_registration = Some(registration);
Ok(())
}
Ok(Some(
UnwindRegistration::new(text.as_ptr(), unwind_info.as_ptr(), unwind_info.len())
.context("failed to create unwind info registration")?,
))
}