Reimplement how unwind information is stored (#3180)
* Reimplement how unwind information is stored This commit is a major refactoring of how unwind information is stored after compilation of a function has finished. Previously we would store the raw `UnwindInfo` as a result of compilation and this would get serialized/deserialized alongside the rest of the ELF object that compilation creates. Whenever functions were registered with `CodeMemory` this would also result in registering unwinding information dynamically at runtime, which in the case of Unix, for example, would dynamically created FDE/CIE entries on-the-fly. Eventually I'd like to support compiling Wasmtime without Cranelift, but this means that `UnwindInfo` wouldn't be easily available to decode into and create unwinding information from. To solve this I've changed the ELF object created to have the unwinding information encoded into it ahead-of-time so loading code into memory no longer needs to create unwinding tables. This change has two different implementations for Windows/Unix: * On Windows the implementation was much easier. The unwinding information on Windows is already stored after the function itself in the text section. This was actually slightly duplicated in object building and in code memory allocation. Now the object building continues to do the same, recording unwinding information after functions, and code memory no longer manually tracks this. Additionally Wasmtime will emit a special custom section in the object file with unwinding information which is the list of `RUNTIME_FUNCTION` structures that `RtlAddFunctionTable` expects. This means that the object file has all the information precompiled into it and registration at runtime is simply passing a few pointers around to the runtime. * Unix was a little bit more difficult than Windows. Today a `.eh_frame` section is created on-the-fly with offsets in FDEs specified as the absolute address that functions are loaded at. This absolute address hindered the ability to precompile the FDE into the object file itself. I've switched how addresses are encoded, though, to using `DW_EH_PE_pcrel` which means that FDE addresses are now specified relative to the FDE itself. This means that we can maintain a fixed offset between the `.eh_frame` loaded in memory and the beginning of code memory. When doing so this enables precompiling the `.eh_frame` section into the object file and at runtime when loading an object no further construction of unwinding information is needed. The overall result of this commit is that unwinding information is no longer stored in its cranelift-data-structure form on disk. This means that this unwinding information format is only present during compilation, which will make it that much easier to compile out cranelift in the future. This commit also significantly refactors `CodeMemory` since the way unwinding information is handled is not much different from before. Previously `CodeMemory` was suitable for incrementally adding more and more functions to it, but nowadays a `CodeMemory` either lives per module (in which case all functions are known up front) or it's created once-per-`Func::new` with two trampolines. In both cases we know all functions up front so the functionality of incrementally adding more and more segments is no longer needed. This commit removes the ability to add a function-at-a-time in `CodeMemory` and instead it can now only load objects in their entirety. A small helper function is added to build a small object file for trampolines in `Func::new` to handle allocation there. Finally, this commit also folds the `wasmtime-obj` crate directly into the `wasmtime-cranelift` crate and its builder structure to be more amenable to this strategy of managing unwinding tables. It is not intentional to have any real functional change as a result of this commit. This might accelerate loading a module from cache slightly since less work is needed to manage the unwinding information, but that's just a side benefit from the main goal of this commit which is to remove the dependence on cranelift unwinding information being available at runtime. * Remove isa reexport from wasmtime-environ * Trim down reexports of `cranelift-codegen` Remove everything non-essential so that only the bits which will need to be refactored out of cranelift remain. * Fix debug tests * Review comments
This commit is contained in:
@@ -1,20 +1,10 @@
|
||||
//! Module for System V ABI unwind registry.
|
||||
|
||||
use crate::Compiler;
|
||||
use anyhow::{bail, Result};
|
||||
use gimli::{
|
||||
write::{Address, EhFrame, EndianVec, FrameTable, Writer},
|
||||
RunTimeEndian,
|
||||
};
|
||||
use wasmtime_environ::isa::unwind::UnwindInfo;
|
||||
use anyhow::Result;
|
||||
|
||||
/// Represents a registry of function unwind information for System V ABI.
|
||||
pub struct UnwindRegistry {
|
||||
base_address: usize,
|
||||
functions: Vec<gimli::write::FrameDescriptionEntry>,
|
||||
frame_table: Vec<u8>,
|
||||
/// Represents a registration of function unwind information for System V ABI.
|
||||
pub struct UnwindRegistration {
|
||||
registrations: Vec<usize>,
|
||||
published: bool,
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
@@ -23,100 +13,34 @@ extern "C" {
|
||||
fn __deregister_frame(fde: *const u8);
|
||||
}
|
||||
|
||||
impl UnwindRegistry {
|
||||
/// Creates a new unwind registry with the given base address.
|
||||
pub fn new(base_address: usize) -> Self {
|
||||
Self {
|
||||
base_address,
|
||||
functions: Vec::new(),
|
||||
frame_table: Vec::new(),
|
||||
registrations: Vec::new(),
|
||||
published: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a function given the start offset, length, and unwind information.
|
||||
pub fn register(&mut self, func_start: u32, _func_len: u32, info: &UnwindInfo) -> Result<()> {
|
||||
if self.published {
|
||||
bail!("unwind registry has already been published");
|
||||
}
|
||||
|
||||
match info {
|
||||
UnwindInfo::SystemV(info) => {
|
||||
self.functions.push(info.to_fde(Address::Constant(
|
||||
self.base_address as u64 + func_start as u64,
|
||||
)));
|
||||
}
|
||||
_ => bail!("unsupported unwind information"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Publishes all registered functions.
|
||||
pub fn publish(&mut self, compiler: &Compiler) -> Result<()> {
|
||||
if self.published {
|
||||
bail!("unwind registry has already been published");
|
||||
}
|
||||
|
||||
if self.functions.is_empty() {
|
||||
self.published = true;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.set_frame_table(compiler)?;
|
||||
|
||||
unsafe {
|
||||
self.register_frames();
|
||||
}
|
||||
|
||||
self.published = true;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_frame_table(&mut self, compiler: &Compiler) -> Result<()> {
|
||||
let mut table = FrameTable::default();
|
||||
let cie_id = table.add_cie(match compiler.compiler().create_systemv_cie() {
|
||||
Some(cie) => cie,
|
||||
None => bail!("ISA does not support System V unwind information"),
|
||||
});
|
||||
|
||||
let functions = std::mem::replace(&mut self.functions, Vec::new());
|
||||
|
||||
for func in functions {
|
||||
table.add_fde(cie_id, func);
|
||||
}
|
||||
|
||||
let mut eh_frame = EhFrame(EndianVec::new(RunTimeEndian::default()));
|
||||
table.write_eh_frame(&mut eh_frame).unwrap();
|
||||
|
||||
impl UnwindRegistration {
|
||||
/// Registers precompiled unwinding information with the system.
|
||||
///
|
||||
/// The `_base_address` field is ignored here (only used on other
|
||||
/// platforms), but the `unwind_info` and `unwind_len` parameters should
|
||||
/// describe an in-memory representation of a `.eh_frame` section. This is
|
||||
/// typically arranged for by the `wasmtime-obj` crate.
|
||||
pub unsafe fn new(
|
||||
_base_address: *mut u8,
|
||||
unwind_info: *mut u8,
|
||||
unwind_len: usize,
|
||||
) -> Result<UnwindRegistration> {
|
||||
let mut registrations = Vec::new();
|
||||
if cfg!(any(
|
||||
all(target_os = "linux", target_env = "gnu"),
|
||||
target_os = "freebsd"
|
||||
)) {
|
||||
// libgcc expects a terminating "empty" length, so write a 0 length at the end of the table.
|
||||
eh_frame.0.write_u32(0).unwrap();
|
||||
}
|
||||
|
||||
self.frame_table = eh_frame.0.into_vec();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn register_frames(&mut self) {
|
||||
if cfg!(any(
|
||||
all(target_os = "linux", target_env = "gnu"),
|
||||
target_os = "freebsd"
|
||||
)) {
|
||||
// On gnu (libgcc), `__register_frame` will walk the FDEs until an entry of length 0
|
||||
let ptr = self.frame_table.as_ptr();
|
||||
__register_frame(ptr);
|
||||
self.registrations.push(ptr as usize);
|
||||
// On gnu (libgcc), `__register_frame` will walk the FDEs until an
|
||||
// entry of length 0
|
||||
__register_frame(unwind_info);
|
||||
registrations.push(unwind_info as usize);
|
||||
} else {
|
||||
// For libunwind, `__register_frame` takes a pointer to a single FDE
|
||||
let start = self.frame_table.as_ptr();
|
||||
let end = start.add(self.frame_table.len());
|
||||
// For libunwind, `__register_frame` takes a pointer to a single
|
||||
// FDE. Note that we subtract 4 from the length of unwind info since
|
||||
// wasmtime-encode .eh_frame sections always have a trailing 32-bit
|
||||
// zero for the platforms above.
|
||||
let start = unwind_info;
|
||||
let end = start.add(unwind_len - 4);
|
||||
let mut current = start;
|
||||
|
||||
// Walk all of the entries in the frame table and register them
|
||||
@@ -126,31 +50,36 @@ impl UnwindRegistry {
|
||||
// Skip over the CIE
|
||||
if current != start {
|
||||
__register_frame(current);
|
||||
self.registrations.push(current as usize);
|
||||
registrations.push(current as usize);
|
||||
}
|
||||
|
||||
// Move to the next table entry (+4 because the length itself is not inclusive)
|
||||
// Move to the next table entry (+4 because the length itself is
|
||||
// not inclusive)
|
||||
current = current.add(len + 4);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(UnwindRegistration { registrations })
|
||||
}
|
||||
|
||||
pub fn section_name() -> &'static str {
|
||||
"_wasmtime_eh_frame"
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UnwindRegistry {
|
||||
impl Drop for UnwindRegistration {
|
||||
fn drop(&mut self) {
|
||||
if self.published {
|
||||
unsafe {
|
||||
// libgcc stores the frame entries as a linked list in decreasing sort order
|
||||
// based on the PC value of the registered entry.
|
||||
//
|
||||
// As we store the registrations in increasing order, it would be O(N^2) to
|
||||
// deregister in that order.
|
||||
//
|
||||
// To ensure that we just pop off the first element in the list upon every
|
||||
// deregistration, walk our list of registrations backwards.
|
||||
for fde in self.registrations.iter().rev() {
|
||||
__deregister_frame(*fde as *const _);
|
||||
}
|
||||
unsafe {
|
||||
// libgcc stores the frame entries as a linked list in decreasing
|
||||
// sort order based on the PC value of the registered entry.
|
||||
//
|
||||
// As we store the registrations in increasing order, it would be
|
||||
// O(N^2) to deregister in that order.
|
||||
//
|
||||
// To ensure that we just pop off the first element in the list upon
|
||||
// every deregistration, walk our list of registrations backwards.
|
||||
for fde in self.registrations.iter().rev() {
|
||||
__deregister_frame(*fde as *const _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +1,46 @@
|
||||
//! Module for Windows x64 ABI unwind registry.
|
||||
|
||||
use crate::Compiler;
|
||||
use anyhow::{bail, Result};
|
||||
use wasmtime_environ::isa::unwind::UnwindInfo;
|
||||
use std::mem;
|
||||
use winapi::um::winnt;
|
||||
|
||||
/// Represents a registry of function unwind information for Windows x64 ABI.
|
||||
pub struct UnwindRegistry {
|
||||
base_address: usize,
|
||||
functions: Vec<winnt::RUNTIME_FUNCTION>,
|
||||
published: bool,
|
||||
pub struct UnwindRegistration {
|
||||
functions: usize,
|
||||
}
|
||||
|
||||
impl UnwindRegistry {
|
||||
/// Creates a new unwind registry with the given base address.
|
||||
pub fn new(base_address: usize) -> Self {
|
||||
Self {
|
||||
base_address,
|
||||
functions: Vec::new(),
|
||||
published: false,
|
||||
impl UnwindRegistration {
|
||||
pub unsafe fn new(
|
||||
base_address: *mut u8,
|
||||
unwind_info: *mut u8,
|
||||
unwind_len: usize,
|
||||
) -> Result<UnwindRegistration> {
|
||||
assert!(unwind_info as usize % 4 == 0);
|
||||
let unit_len = mem::size_of::<winnt::RUNTIME_FUNCTION>();
|
||||
assert!(unwind_len % unit_len == 0);
|
||||
if winnt::RtlAddFunctionTable(
|
||||
unwind_info as *mut _,
|
||||
(unwind_len / unit_len) as u32,
|
||||
base_address as u64,
|
||||
) == 0
|
||||
{
|
||||
bail!("failed to register function table");
|
||||
}
|
||||
|
||||
Ok(UnwindRegistration {
|
||||
functions: unwind_info as usize,
|
||||
})
|
||||
}
|
||||
|
||||
/// Registers a function given the start offset, length, and unwind information.
|
||||
pub fn register(&mut self, func_start: u32, func_len: u32, info: &UnwindInfo) -> Result<()> {
|
||||
if self.published {
|
||||
bail!("unwind registry has already been published");
|
||||
}
|
||||
|
||||
match info {
|
||||
UnwindInfo::WindowsX64(_) => {
|
||||
let mut entry = winnt::RUNTIME_FUNCTION::default();
|
||||
|
||||
entry.BeginAddress = func_start;
|
||||
entry.EndAddress = func_start + func_len;
|
||||
|
||||
// The unwind information should be immediately following the function
|
||||
// with padding for 4 byte alignment
|
||||
unsafe {
|
||||
*entry.u.UnwindInfoAddress_mut() = (entry.EndAddress + 3) & !3;
|
||||
}
|
||||
|
||||
self.functions.push(entry);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
_ => bail!("unsupported unwind information"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes all registered functions.
|
||||
pub fn publish(&mut self, _compiler: &Compiler) -> Result<()> {
|
||||
if self.published {
|
||||
bail!("unwind registry has already been published");
|
||||
}
|
||||
|
||||
self.published = true;
|
||||
|
||||
if !self.functions.is_empty() {
|
||||
// Windows heap allocations are 32-bit aligned, but assert just in case
|
||||
assert_eq!(
|
||||
(self.functions.as_mut_ptr() as u64) % 4,
|
||||
0,
|
||||
"function table allocation was not aligned"
|
||||
);
|
||||
|
||||
unsafe {
|
||||
if winnt::RtlAddFunctionTable(
|
||||
self.functions.as_mut_ptr(),
|
||||
self.functions.len() as u32,
|
||||
self.base_address as u64,
|
||||
) == 0
|
||||
{
|
||||
bail!("failed to register function table");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
pub fn section_name() -> &'static str {
|
||||
"_wasmtime_winx64_unwind"
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UnwindRegistry {
|
||||
impl Drop for UnwindRegistration {
|
||||
fn drop(&mut self) {
|
||||
if self.published {
|
||||
unsafe {
|
||||
winnt::RtlDeleteFunctionTable(self.functions.as_mut_ptr());
|
||||
}
|
||||
unsafe {
|
||||
winnt::RtlDeleteFunctionTable(self.functions as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user