Reduce the extent of unsafe code.

This commit is contained in:
Dan Gohman
2017-09-22 16:21:25 -07:00
parent ecd746718b
commit 64d596005c

View File

@@ -124,12 +124,13 @@ pub fn compile_module(
/// Jumps to the code region of memory and execute the start function of the module. /// Jumps to the code region of memory and execute the start function of the module.
pub fn execute(exec: &ExecutableCode) -> Result<(), String> { pub fn execute(exec: &ExecutableCode) -> Result<(), String> {
let code_buf = &exec.functions_code[exec.start_index]; let code_buf = &exec.functions_code[exec.start_index];
unsafe { match unsafe {
match protect( protect(
code_buf.as_ptr(), code_buf.as_ptr(),
code_buf.len(), code_buf.len(),
Protection::ReadWriteExecute, Protection::ReadWriteExecute,
) { )
} {
Ok(()) => (), Ok(()) => (),
Err(err) => { Err(err) => {
return Err(format!( return Err(format!(
@@ -137,15 +138,16 @@ pub fn execute(exec: &ExecutableCode) -> Result<(), String> {
err.description() err.description()
)) ))
} }
}; }
// Rather than writing inline assembly to jump to the code region, we use the fact that // Rather than writing inline assembly to jump to the code region, we use the fact that
// the Rust ABI for calling a function with no arguments and no return matches the one of // the Rust ABI for calling a function with no arguments and no return matches the one of
// the generated code.Thanks to this, we can transmute the code region into a first-class // the generated code.Thanks to this, we can transmute the code region into a first-class
// Rust function and call it. // Rust function and call it.
unsafe {
let start_func = transmute::<_, fn()>(code_buf.as_ptr()); let start_func = transmute::<_, fn()>(code_buf.as_ptr());
start_func(); start_func();
Ok(())
} }
Ok(())
} }
/// Performs the relocations inside the function bytecode, provided the necessary metadata /// Performs the relocations inside the function bytecode, provided the necessary metadata