cranelift-module: expose trap information when defining functions

The current interface of `cranelift-module` requires consumers who want
to be informed about traps to discover that information through
`Module::Product`, which is backend-specific.  Since it's advantageous
to manipulate this information in a backend-agnostic way, this patch
changes `Module::define_function{,_bytes}` to return information about
the traps contained in the function being defined.
This commit is contained in:
Nathan Froyd
2020-03-03 11:27:45 -05:00
parent f7c2a58d23
commit 0f49a830c9
6 changed files with 60 additions and 37 deletions

View File

@@ -152,10 +152,11 @@ impl Backend for FaerieBackend {
ctx: &cranelift_codegen::Context, ctx: &cranelift_codegen::Context,
namespace: &ModuleNamespace<Self>, namespace: &ModuleNamespace<Self>,
total_size: u32, total_size: u32,
) -> ModuleResult<FaerieCompiledFunction> { ) -> ModuleResult<(FaerieCompiledFunction, Option<&Vec<TrapSite>>)> {
let mut code: Vec<u8> = vec![0; total_size as usize]; let mut code: Vec<u8> = vec![0; total_size as usize];
// TODO: Replace this with FaerieStackmapSink once it is implemented. // TODO: Replace this with FaerieStackmapSink once it is implemented.
let mut stackmap_sink = NullStackmapSink {}; let mut stackmap_sink = NullStackmapSink {};
let mut traps = None;
// Non-lexical lifetimes would obviate the braces here. // Non-lexical lifetimes would obviate the braces here.
{ {
@@ -178,7 +179,7 @@ impl Backend for FaerieBackend {
&mut stackmap_sink, &mut stackmap_sink,
) )
}; };
trap_manifest.add_sink(trap_sink); traps = Some(trap_manifest.add_sink(trap_sink));
} else { } else {
let mut trap_sink = NullTrapSink {}; let mut trap_sink = NullTrapSink {};
unsafe { unsafe {
@@ -200,7 +201,7 @@ impl Backend for FaerieBackend {
.define(name, code) .define(name, code)
.expect("inconsistent declaration"); .expect("inconsistent declaration");
Ok(FaerieCompiledFunction { code_length }) Ok((FaerieCompiledFunction { code_length }, traps))
} }
fn define_function_bytes( fn define_function_bytes(
@@ -210,22 +211,23 @@ impl Backend for FaerieBackend {
bytes: &[u8], bytes: &[u8],
_namespace: &ModuleNamespace<Self>, _namespace: &ModuleNamespace<Self>,
traps: Vec<TrapSite>, traps: Vec<TrapSite>,
) -> ModuleResult<FaerieCompiledFunction> { ) -> ModuleResult<(FaerieCompiledFunction, Option<&Vec<TrapSite>>)> {
let code_length: u32 = match bytes.len().try_into() { let code_length: u32 = match bytes.len().try_into() {
Ok(code_length) => code_length, Ok(code_length) => code_length,
_ => Err(ModuleError::FunctionTooLarge(name.to_string()))?, _ => Err(ModuleError::FunctionTooLarge(name.to_string()))?,
}; };
let mut ret_traps = None;
if let Some(ref mut trap_manifest) = self.trap_manifest { if let Some(ref mut trap_manifest) = self.trap_manifest {
let trap_sink = FaerieTrapSink::new_with_sites(name, code_length, traps); let trap_sink = FaerieTrapSink::new_with_sites(name, code_length, traps);
trap_manifest.add_sink(trap_sink); ret_traps = Some(trap_manifest.add_sink(trap_sink));
} }
self.artifact self.artifact
.define(name, bytes.to_vec()) .define(name, bytes.to_vec())
.expect("inconsistent declaration"); .expect("inconsistent declaration");
Ok(FaerieCompiledFunction { code_length }) Ok((FaerieCompiledFunction { code_length }, ret_traps))
} }
fn define_data( fn define_data(

View File

@@ -59,7 +59,8 @@ impl FaerieTrapManifest {
} }
/// Put a `FaerieTrapSink` into manifest /// Put a `FaerieTrapSink` into manifest
pub fn add_sink(&mut self, sink: FaerieTrapSink) { pub fn add_sink(&mut self, sink: FaerieTrapSink) -> &Vec<TrapSite> {
self.sinks.push(sink); self.sinks.push(sink);
&self.sinks.last().unwrap().sites
} }
} }

View File

@@ -86,7 +86,7 @@ where
ctx: &Context, ctx: &Context,
namespace: &ModuleNamespace<Self>, namespace: &ModuleNamespace<Self>,
code_size: u32, code_size: u32,
) -> ModuleResult<Self::CompiledFunction>; ) -> ModuleResult<(Self::CompiledFunction, Option<&Vec<TrapSite>>)>;
/// Define a function, taking the function body from the given `bytes`. /// Define a function, taking the function body from the given `bytes`.
/// ///
@@ -98,7 +98,7 @@ where
bytes: &[u8], bytes: &[u8],
namespace: &ModuleNamespace<Self>, namespace: &ModuleNamespace<Self>,
traps: Vec<TrapSite>, traps: Vec<TrapSite>,
) -> ModuleResult<Self::CompiledFunction>; ) -> ModuleResult<(Self::CompiledFunction, Option<&Vec<TrapSite>>)>;
/// Define a zero-initialized data object of the given size. /// Define a zero-initialized data object of the given size.
/// ///

View File

@@ -352,6 +352,11 @@ where
backend: B, backend: B,
} }
pub struct ModuleCompiledFunction<'a> {
pub size: binemit::CodeOffset,
pub traps: Option<&'a Vec<TrapSite>>,
}
impl<B> Module<B> impl<B> Module<B>
where where
B: Backend, B: Backend,
@@ -557,7 +562,7 @@ where
&mut self, &mut self,
func: FuncId, func: FuncId,
ctx: &mut Context, ctx: &mut Context,
) -> ModuleResult<binemit::CodeOffset> { ) -> ModuleResult<ModuleCompiledFunction> {
info!( info!(
"defining function {}: {}", "defining function {}: {}",
func, func,
@@ -572,7 +577,7 @@ where
return Err(ModuleError::InvalidImportDefinition(info.decl.name.clone())); return Err(ModuleError::InvalidImportDefinition(info.decl.name.clone()));
} }
let compiled = Some(self.backend.define_function( let (compiled, traps) = self.backend.define_function(
func, func,
&info.decl.name, &info.decl.name,
ctx, ctx,
@@ -580,11 +585,14 @@ where
contents: &self.contents, contents: &self.contents,
}, },
total_size, total_size,
)?); )?;
self.contents.functions[func].compiled = compiled; self.contents.functions[func].compiled = Some(compiled);
self.functions_to_finalize.push(func); self.functions_to_finalize.push(func);
Ok(total_size) Ok(ModuleCompiledFunction {
size: total_size,
traps,
})
} }
/// Define a function, taking the function body from the given `bytes`. /// Define a function, taking the function body from the given `bytes`.
@@ -599,7 +607,7 @@ where
func: FuncId, func: FuncId,
bytes: &[u8], bytes: &[u8],
traps: Vec<TrapSite>, traps: Vec<TrapSite>,
) -> ModuleResult<binemit::CodeOffset> { ) -> ModuleResult<ModuleCompiledFunction> {
info!("defining function {} with bytes", func); info!("defining function {} with bytes", func);
let info = &self.contents.functions[func]; let info = &self.contents.functions[func];
if info.compiled.is_some() { if info.compiled.is_some() {
@@ -614,7 +622,7 @@ where
_ => Err(ModuleError::FunctionTooLarge(info.decl.name.clone()))?, _ => Err(ModuleError::FunctionTooLarge(info.decl.name.clone()))?,
}; };
let compiled = Some(self.backend.define_function_bytes( let (compiled, traps) = self.backend.define_function_bytes(
func, func,
&info.decl.name, &info.decl.name,
bytes, bytes,
@@ -622,11 +630,14 @@ where
contents: &self.contents, contents: &self.contents,
}, },
traps, traps,
)?); )?;
self.contents.functions[func].compiled = compiled; self.contents.functions[func].compiled = Some(compiled);
self.functions_to_finalize.push(func); self.functions_to_finalize.push(func);
Ok(total_size) Ok(ModuleCompiledFunction {
size: total_size,
traps,
})
} }
/// Define a data object, producing the data contents from the given `DataContext`. /// Define a data object, producing the data contents from the given `DataContext`.

View File

@@ -17,6 +17,7 @@ use object::write::{
use object::{RelocationEncoding, RelocationKind, SymbolFlags, SymbolKind, SymbolScope}; use object::{RelocationEncoding, RelocationKind, SymbolFlags, SymbolKind, SymbolScope};
use std::collections::HashMap; use std::collections::HashMap;
use std::mem; use std::mem;
use std::ops::IndexMut;
use target_lexicon::{BinaryFormat, PointerWidth}; use target_lexicon::{BinaryFormat, PointerWidth};
#[derive(Debug)] #[derive(Debug)]
@@ -188,7 +189,7 @@ impl Backend for ObjectBackend {
ctx: &cranelift_codegen::Context, ctx: &cranelift_codegen::Context,
_namespace: &ModuleNamespace<Self>, _namespace: &ModuleNamespace<Self>,
code_size: u32, code_size: u32,
) -> ModuleResult<ObjectCompiledFunction> { ) -> ModuleResult<(ObjectCompiledFunction, Option<&Vec<TrapSite>>)> {
let mut code: Vec<u8> = vec![0; code_size as usize]; let mut code: Vec<u8> = vec![0; code_size as usize];
let mut reloc_sink = ObjectRelocSink::new(self.object.format()); let mut reloc_sink = ObjectRelocSink::new(self.object.format());
let mut trap_sink = ObjectTrapSink::default(); let mut trap_sink = ObjectTrapSink::default();
@@ -229,8 +230,9 @@ impl Backend for ObjectBackend {
relocs: reloc_sink.relocs, relocs: reloc_sink.relocs,
}); });
} }
self.traps[func_id] = trap_sink.sites; let trapref = self.traps.index_mut(func_id);
Ok(ObjectCompiledFunction) *trapref = trap_sink.sites;
Ok((ObjectCompiledFunction, Some(trapref)))
} }
fn define_function_bytes( fn define_function_bytes(
@@ -240,14 +242,15 @@ impl Backend for ObjectBackend {
bytes: &[u8], bytes: &[u8],
_namespace: &ModuleNamespace<Self>, _namespace: &ModuleNamespace<Self>,
traps: Vec<TrapSite>, traps: Vec<TrapSite>,
) -> ModuleResult<ObjectCompiledFunction> { ) -> ModuleResult<(ObjectCompiledFunction, Option<&Vec<TrapSite>>)> {
let symbol = self.functions[func_id].unwrap(); let symbol = self.functions[func_id].unwrap();
let section = self.object.section_id(StandardSection::Text); let section = self.object.section_id(StandardSection::Text);
let _offset = self let _offset = self
.object .object
.add_symbol_data(symbol, section, bytes, self.function_alignment); .add_symbol_data(symbol, section, bytes, self.function_alignment);
self.traps[func_id] = traps; let trapref = self.traps.index_mut(func_id);
Ok(ObjectCompiledFunction) *trapref = traps;
Ok((ObjectCompiledFunction, Some(trapref)))
} }
fn define_data( fn define_data(

View File

@@ -278,7 +278,7 @@ impl<'simple_jit_backend> Backend for SimpleJITBackend {
ctx: &cranelift_codegen::Context, ctx: &cranelift_codegen::Context,
_namespace: &ModuleNamespace<Self>, _namespace: &ModuleNamespace<Self>,
code_size: u32, code_size: u32,
) -> ModuleResult<Self::CompiledFunction> { ) -> ModuleResult<(Self::CompiledFunction, Option<&Vec<TrapSite>>)> {
let size = code_size as usize; let size = code_size as usize;
let ptr = self let ptr = self
.memory .memory
@@ -303,11 +303,14 @@ impl<'simple_jit_backend> Backend for SimpleJITBackend {
) )
}; };
Ok(Self::CompiledFunction { Ok((
code: ptr, Self::CompiledFunction {
size, code: ptr,
relocs: reloc_sink.relocs, size,
}) relocs: reloc_sink.relocs,
},
None,
))
} }
fn define_function_bytes( fn define_function_bytes(
@@ -317,7 +320,7 @@ impl<'simple_jit_backend> Backend for SimpleJITBackend {
bytes: &[u8], bytes: &[u8],
_namespace: &ModuleNamespace<Self>, _namespace: &ModuleNamespace<Self>,
_traps: Vec<TrapSite>, _traps: Vec<TrapSite>,
) -> ModuleResult<Self::CompiledFunction> { ) -> ModuleResult<(Self::CompiledFunction, Option<&Vec<TrapSite>>)> {
let size = bytes.len(); let size = bytes.len();
let ptr = self let ptr = self
.memory .memory
@@ -331,11 +334,14 @@ impl<'simple_jit_backend> Backend for SimpleJITBackend {
ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, size); ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, size);
} }
Ok(Self::CompiledFunction { Ok((
code: ptr, Self::CompiledFunction {
size, code: ptr,
relocs: vec![], size,
}) relocs: vec![],
},
None,
))
} }
fn define_data( fn define_data(