wasmer_compiler/function.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
// This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md
//! A `Compilation` contains the compiled function bodies for a WebAssembly
//! module (`CompiledFunction`).
use crate::lib::std::vec::Vec;
use crate::section::{CustomSection, SectionIndex};
use crate::trap::TrapInformation;
use crate::{
CompiledFunctionUnwindInfo, CompiledFunctionUnwindInfoRef, FunctionAddressMap,
JumpTableOffsets, Relocation,
};
use wasmer_types::entity::PrimaryMap;
use wasmer_types::{FunctionIndex, LocalFunctionIndex, SignatureIndex};
/// The frame info for a Compiled function.
///
/// This structure is only used for reconstructing
/// the frame information after a `Trap`.
#[derive(
rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, PartialEq, Eq, Default,
)]
pub struct CompiledFunctionFrameInfo {
/// The traps (in the function body).
///
/// Code offsets of the traps MUST be in ascending order.
pub traps: Vec<TrapInformation>,
/// The address map.
pub address_map: FunctionAddressMap,
}
/// The function body.
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, PartialEq, Eq)]
pub struct FunctionBody {
/// The function body bytes.
pub body: Vec<u8>,
/// The function unwind info
pub unwind_info: Option<CompiledFunctionUnwindInfo>,
}
/// See [`FunctionBody`].
#[derive(Clone, Copy)]
pub struct FunctionBodyRef<'a> {
/// Function body bytes.
pub body: &'a [u8],
/// The function unwind info.
pub unwind_info: Option<CompiledFunctionUnwindInfoRef<'a>>,
}
impl<'a> From<&'a FunctionBody> for FunctionBodyRef<'a> {
fn from(body: &'a FunctionBody) -> Self {
FunctionBodyRef {
body: &*body.body,
unwind_info: body.unwind_info.as_ref().map(Into::into),
}
}
}
impl<'a> From<&'a ArchivedFunctionBody> for FunctionBodyRef<'a> {
fn from(body: &'a ArchivedFunctionBody) -> Self {
FunctionBodyRef {
body: &*body.body,
unwind_info: body.unwind_info.as_ref().map(Into::into),
}
}
}
/// The result of compiling a WebAssembly function.
///
/// This structure only have the compiled information data
/// (function bytecode body, relocations, traps, jump tables
/// and unwind information).
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, PartialEq, Eq)]
pub struct CompiledFunction {
/// The function body.
pub body: FunctionBody,
/// The relocations (in the body)
pub relocations: Vec<Relocation>,
/// The jump tables offsets (in the body).
pub jt_offsets: JumpTableOffsets,
/// The frame information.
pub frame_info: CompiledFunctionFrameInfo,
}
/// The compiled functions map (index in the Wasm -> function)
pub type Functions = PrimaryMap<LocalFunctionIndex, CompiledFunction>;
/// The custom sections for a Compilation.
pub type CustomSections = PrimaryMap<SectionIndex, CustomSection>;
/// The DWARF information for this Compilation.
///
/// It is used for retrieving the unwind information once an exception
/// happens.
/// In the future this structure may also hold other information useful
/// for debugging.
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, PartialEq, Eq, Clone)]
pub struct Dwarf {
/// The section index in the [`Compilation`] that corresponds to the exception frames.
/// [Learn
/// more](https://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html).
pub eh_frame: SectionIndex,
}
impl Dwarf {
/// Creates a `Dwarf` struct with the corresponding indices for its sections
pub fn new(eh_frame: SectionIndex) -> Self {
Self { eh_frame }
}
}
/// Trampolines section used by ARM short jump (26bits)
#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, PartialEq, Eq, Clone)]
pub struct TrampolinesSection {
/// SectionIndex for the actual Trampolines code
pub section_index: SectionIndex,
/// Number of jump slots in the section
pub slots: usize,
/// Slot size
pub size: usize,
}
impl TrampolinesSection {
/// Creates a `Trampolines` struct with the indice for its section, and number of slots and size of slot
pub fn new(section_index: SectionIndex, slots: usize, size: usize) -> Self {
Self {
section_index,
slots,
size,
}
}
}
/// The result of compiling a WebAssembly module's functions.
#[derive(Debug, PartialEq, Eq)]
pub struct Compilation {
/// Compiled code for the function bodies.
functions: Functions,
/// Custom sections for the module.
/// It will hold the data, for example, for constants used in a
/// function, global variables, rodata_64, hot/cold function partitioning, ...
custom_sections: CustomSections,
/// Trampolines to call a function defined locally in the wasm via a
/// provided `Vec` of values.
///
/// This allows us to call easily Wasm functions, such as:
///
/// ```ignore
/// let func = instance.exports.get_function("my_func");
/// func.call(&[Value::I32(1)]);
/// ```
function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>,
/// Trampolines to call a dynamic function defined in
/// a host, from a Wasm module.
///
/// This allows us to create dynamic Wasm functions, such as:
///
/// ```ignore
/// fn my_func(values: &[Val]) -> Result<Vec<Val>, RuntimeError> {
/// // do something
/// }
///
/// let my_func_type = FunctionType::new(vec![Type::I32], vec![Type::I32]);
/// let imports = imports!{
/// "namespace" => {
/// "my_func" => Function::new(&store, my_func_type, my_func),
/// }
/// }
/// ```
///
/// Note: Dynamic function trampolines are only compiled for imported function types.
dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>,
/// Section ids corresponding to the Dwarf debug info
debug: Option<Dwarf>,
/// Trampolines for the arch that needs it
trampolines: Option<TrampolinesSection>,
}
impl Compilation {
/// Creates a compilation artifact from a contiguous function buffer and a set of ranges
pub fn new(
functions: Functions,
custom_sections: CustomSections,
function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>,
dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>,
debug: Option<Dwarf>,
trampolines: Option<TrampolinesSection>,
) -> Self {
Self {
functions,
custom_sections,
function_call_trampolines,
dynamic_function_trampolines,
debug,
trampolines,
}
}
/// Gets the bytes of a single function
pub fn get(&self, func: LocalFunctionIndex) -> &CompiledFunction {
&self.functions[func]
}
/// Gets the number of functions defined.
pub fn len(&self) -> usize {
self.functions.len()
}
/// Returns whether there are no functions defined.
pub fn is_empty(&self) -> bool {
self.functions.is_empty()
}
/// Gets functions relocations.
pub fn get_relocations(&self) -> PrimaryMap<LocalFunctionIndex, Vec<Relocation>> {
self.functions
.iter()
.map(|(_, func)| func.relocations.clone())
.collect::<PrimaryMap<LocalFunctionIndex, _>>()
}
/// Gets functions bodies.
pub fn get_function_bodies(&self) -> PrimaryMap<LocalFunctionIndex, FunctionBody> {
self.functions
.iter()
.map(|(_, func)| func.body.clone())
.collect::<PrimaryMap<LocalFunctionIndex, _>>()
}
/// Gets functions jump table offsets.
pub fn get_jt_offsets(&self) -> PrimaryMap<LocalFunctionIndex, JumpTableOffsets> {
self.functions
.iter()
.map(|(_, func)| func.jt_offsets.clone())
.collect::<PrimaryMap<LocalFunctionIndex, _>>()
}
/// Gets functions frame info.
pub fn get_frame_info(&self) -> PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo> {
self.functions
.iter()
.map(|(_, func)| func.frame_info.clone())
.collect::<PrimaryMap<LocalFunctionIndex, _>>()
}
/// Gets function call trampolines.
pub fn get_function_call_trampolines(&self) -> PrimaryMap<SignatureIndex, FunctionBody> {
self.function_call_trampolines.clone()
}
/// Gets function call trampolines.
pub fn get_dynamic_function_trampolines(&self) -> PrimaryMap<FunctionIndex, FunctionBody> {
self.dynamic_function_trampolines.clone()
}
/// Gets custom section data.
pub fn get_custom_sections(&self) -> PrimaryMap<SectionIndex, CustomSection> {
self.custom_sections.clone()
}
/// Gets relocations that apply to custom sections.
pub fn get_custom_section_relocations(&self) -> PrimaryMap<SectionIndex, Vec<Relocation>> {
self.custom_sections
.iter()
.map(|(_, section)| section.relocations.clone())
.collect::<PrimaryMap<SectionIndex, _>>()
}
/// Returns the Dwarf info.
pub fn get_debug(&self) -> Option<Dwarf> {
self.debug.clone()
}
/// Returns the Trampolines info.
pub fn get_trampolines(&self) -> Option<TrampolinesSection> {
self.trampolines.clone()
}
}
impl<'a> IntoIterator for &'a Compilation {
type IntoIter = Iter<'a>;
type Item = <Self::IntoIter as Iterator>::Item;
fn into_iter(self) -> Self::IntoIter {
Iter {
iterator: self.functions.iter(),
}
}
}
pub struct Iter<'a> {
iterator: <&'a Functions as IntoIterator>::IntoIter,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a CompiledFunction;
fn next(&mut self) -> Option<Self::Item> {
self.iterator.next().map(|(_, b)| b)
}
}