wasm-utils/src/pack.rs

219 lines
8.6 KiB
Rust
Raw Normal View History

use parity_wasm::elements::{self, Section, Opcode, DataSegment, InitExpr, Internal};
use parity_wasm::builder;
2017-10-27 18:32:33 +03:00
use super::{CREATE_SYMBOL, CALL_SYMBOL};
2017-10-26 15:49:55 +03:00
2017-11-22 01:40:58 +03:00
/// Pack error.
///
/// Pack has number of assumptions of passed module structure.
/// When they are violated, pack_instance returns one of these.
#[derive(Debug)]
pub enum Error {
MalformedModule,
NoTypeSection,
NoExportSection,
NoCodeSection,
InvalidCreateSignature,
NoCreateSymbol,
InvalidCreateMember,
}
2017-10-26 15:49:55 +03:00
/// If module has an exported "_create" function we want to pack it into "constructor".
/// `raw_module` is the actual contract code
/// `ctor_module` is the constructor which should return `raw_module`
2017-11-22 01:40:58 +03:00
pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module) -> Result<elements::Module, Error> {
// Total number of constructor module import functions
let ctor_import_functions = ctor_module.import_section().map(|x| x.functions()).unwrap_or(0);
2017-10-26 15:49:55 +03:00
// We need to find an internal ID of function witch is exported as "_create"
// in order to find it in the Code section of the module
2017-10-25 20:36:05 +03:00
let create_func_id = {
2017-11-22 01:40:58 +03:00
let found_entry = ctor_module.export_section().ok_or(Error::NoExportSection)?.entries().iter()
.find(|entry| CREATE_SYMBOL == entry.field()).ok_or(Error::NoCreateSymbol)?;
2017-10-25 20:36:05 +03:00
let function_index: usize = match found_entry.internal() {
&Internal::Function(index) => index as usize,
2017-11-22 01:40:58 +03:00
_ => { return Err(Error::InvalidCreateMember) },
};
// Constructor should be of signature `func(i32)` (void), fail otherwise
let type_id = ctor_module.function_section().ok_or(Error::NoCodeSection)?
.entries().get(function_index).ok_or(Error::MalformedModule)?
.type_ref();
match ctor_module.type_section().ok_or(Error::NoTypeSection)?
.types().get(type_id as usize).ok_or(Error::MalformedModule)?
{
&elements::Type::Function(ref f) => {
if f.params().len() != 1 || f.params()[0] != elements::ValueType::I32 {
return Err(Error::InvalidCreateSignature);
}
if f.return_type().is_some() {
return Err(Error::InvalidCreateSignature);
}
}
2017-10-25 20:36:05 +03:00
};
// Calculates a function index within module's function section
function_index - ctor_import_functions
2017-10-25 20:36:05 +03:00
};
// If new function is put in ctor module, it will have this callable index
let last_function_index = ctor_module.function_section().map(|x| x.entries().len()).unwrap_or(0)
+ ctor_import_functions;
2017-10-26 15:49:55 +03:00
// Code data address is an address where we put the contract's code (raw_module)
2017-10-25 20:36:05 +03:00
let mut code_data_address = 0i32;
2017-10-27 18:32:33 +03:00
2017-10-25 20:36:05 +03:00
for section in ctor_module.sections_mut() {
match section {
2017-10-27 18:32:33 +03:00
// TODO: add data section is there no one
2017-10-25 20:36:05 +03:00
&mut Section::Data(ref mut data_section) => {
let (index, offset) = if let Some(ref entry) = data_section.entries().iter().last() {
if let Opcode::I32Const(offst) = entry.offset().code()[0] {
let len = entry.value().len() as i32;
let offst = offst as i32;
2017-10-26 19:24:40 +03:00
(entry.index(), offst + (len + 4) - len % 4)
2017-10-25 20:36:05 +03:00
} else {
(0, 0)
}
} else {
(0, 0)
};
2017-10-26 15:49:55 +03:00
let code_data = DataSegment::new(
index,
2017-10-30 18:35:20 +03:00
InitExpr::new(vec![Opcode::I32Const(offset), Opcode::End]),
2017-10-26 15:49:55 +03:00
raw_module.clone()
);
2017-10-25 20:36:05 +03:00
data_section.entries_mut().push(code_data);
code_data_address = offset;
},
_ => {;}
}
}
let mut new_module = builder::from_module(ctor_module)
.function()
.signature().param().i32().build()
.body().with_opcodes(elements::Opcodes::new(
vec![
Opcode::GetLocal(0),
Opcode::Call(create_func_id as u32),
Opcode::GetLocal(0),
Opcode::I32Const(code_data_address),
Opcode::I32Store(0, 8),
Opcode::GetLocal(0),
Opcode::I32Const(raw_module.len() as i32),
Opcode::I32Store(0, 12),
Opcode::End,
])).build()
.build()
.build();
for section in new_module.sections_mut() {
2017-10-25 20:36:05 +03:00
match section {
&mut Section::Export(ref mut export_section) => {
for entry in export_section.entries_mut().iter_mut() {
2017-10-26 15:49:55 +03:00
if CREATE_SYMBOL == entry.field() {
2017-10-25 20:36:05 +03:00
// change _create export name into default _call
2017-10-26 15:49:55 +03:00
*entry.field_mut() = CALL_SYMBOL.to_owned();
*entry.internal_mut() = elements::Internal::Function(last_function_index as u32);
2017-10-25 20:36:05 +03:00
}
}
},
_ => { },
2017-10-25 20:36:05 +03:00
}
};
2017-11-22 01:40:58 +03:00
Ok(new_module)
2017-10-25 20:36:05 +03:00
}
2017-10-27 18:32:33 +03:00
#[cfg(test)]
mod test {
extern crate parity_wasm;
2017-10-27 19:25:57 +03:00
extern crate byteorder;
2017-10-27 19:50:12 +03:00
use parity_wasm::builder;
2017-10-27 18:32:33 +03:00
use parity_wasm::interpreter;
2017-10-27 19:25:57 +03:00
use parity_wasm::interpreter::RuntimeValue;
2017-10-27 18:32:33 +03:00
use parity_wasm::ModuleInstanceInterface;
use super::*;
use super::super::optimize;
2017-10-27 19:25:57 +03:00
use byteorder::{ByteOrder, LittleEndian};
2017-10-27 18:32:33 +03:00
#[test]
fn call_returns_code() {
let mut module = builder::module()
.import()
.module("env")
.field("memory")
.external()
.memory(1 as u32, Some(1 as u32))
.build()
.data()
.offset(elements::Opcode::I32Const(16))
.value(vec![0u8])
.build()
.function()
2017-10-30 18:35:20 +03:00
.signature().build()
2017-10-27 18:32:33 +03:00
.body()
.with_opcodes(elements::Opcodes::new(
vec![
elements::Opcode::End
]
))
.build()
.build()
.function()
.signature().param().i32().build()
.body()
.with_opcodes(elements::Opcodes::new(
vec![
elements::Opcode::End
]
))
.build()
.build()
.export()
2017-11-15 19:33:39 +03:00
.field(CALL_SYMBOL)
2017-10-27 18:32:33 +03:00
.internal().func(0)
.build()
.export()
2017-11-15 19:33:39 +03:00
.field(CREATE_SYMBOL)
2017-10-27 18:32:33 +03:00
.internal().func(1)
.build()
.build();
2017-10-27 19:25:57 +03:00
2017-10-27 18:32:33 +03:00
let mut ctor_module = module.clone();
optimize(&mut module, vec![CALL_SYMBOL]).expect("Optimizer to finish without errors");
optimize(&mut ctor_module, vec![CREATE_SYMBOL]).expect("Optimizer to finish without errors");
2017-10-27 18:32:33 +03:00
let raw_module = parity_wasm::serialize(module).unwrap();
2017-11-22 01:40:58 +03:00
let ctor_module = pack_instance(raw_module.clone(), ctor_module).expect("Packing failed");
2017-10-27 18:32:33 +03:00
2017-10-30 18:35:20 +03:00
let program = parity_wasm::DefaultProgramInstance::new().expect("Program instance failed to load");
2017-10-27 18:32:33 +03:00
let env_instance = program.module("env").expect("Wasm program to contain env module");
let env_memory = env_instance.memory(interpreter::ItemIndex::Internal(0)).expect("Linear memory to exist in wasm runtime");
2017-10-27 19:50:12 +03:00
let execution_params = interpreter::ExecutionParams::default();
2017-10-30 18:35:20 +03:00
let constructor_module = program.add_module("contract", ctor_module, None).expect("Failed to initialize module");
2017-10-27 18:32:33 +03:00
2017-10-30 18:35:20 +03:00
let _ = constructor_module.execute_export(CALL_SYMBOL, execution_params.add_argument(RuntimeValue::I32(1024)));
2017-10-27 19:25:57 +03:00
let pointer = LittleEndian::read_u32(&env_memory.get(1024 + 8, 4).unwrap());
let len = LittleEndian::read_u32(&env_memory.get(1024 + 12, 4).unwrap());
2017-10-30 18:35:20 +03:00
let contract_code = env_memory.get(pointer, len as usize).expect("Failed to get code");
2017-10-27 18:32:33 +03:00
2017-10-30 18:35:20 +03:00
assert_eq!(raw_module, contract_code);
2017-10-27 18:32:33 +03:00
2017-10-30 18:35:20 +03:00
let contract_module: elements::Module = parity_wasm::deserialize_buffer(contract_code).expect("Constructed contract module is not valid");
2017-10-27 18:32:33 +03:00
2017-10-30 18:35:20 +03:00
let program = parity_wasm::DefaultProgramInstance::new().expect("Program2 instance failed to load");
let contract_module_instance = program.add_module("contract", contract_module, None).expect("Failed to initialize constructed contract module");
2017-10-27 18:32:33 +03:00
let execution_params = interpreter::ExecutionParams::default();
2017-10-30 18:35:20 +03:00
contract_module_instance.execute_export(CALL_SYMBOL, execution_params).expect("Constructed contract failed to execute");
2017-10-27 18:32:33 +03:00
}
}