Refactor TargetRuntime as enum

Don't rename create symbol for substrate binaries
This commit is contained in:
holygits 2019-01-23 17:03:53 +13:00
parent 7c7a0713fc
commit c47adc1bd4
5 changed files with 74 additions and 53 deletions

View File

@ -31,7 +31,7 @@ fn main() {
// Invoke packer // Invoke packer
let mut result_module = utils::pack_instance(raw_module, ctor_module, &utils::TargetRuntime::pwasm()).expect("Packing failed"); let mut result_module = utils::pack_instance(raw_module, ctor_module, &utils::TargetRuntime::pwasm()).expect("Packing failed");
// Optimize constructor, since it does not need everything // Optimize constructor, since it does not need everything
utils::optimize(&mut result_module, vec![target_runtime.call_symbol]).expect("Optimization failed"); utils::optimize(&mut result_module, vec![target_runtime.symbols().call]).expect("Optimization failed");
parity_wasm::serialize_to_file(&output, result_module).expect("Serialization failed"); parity_wasm::serialize_to_file(&output, result_module).expect("Serialization failed");
} }

View File

@ -24,12 +24,12 @@ fn main() {
.short("e") .short("e")
.takes_value(true) .takes_value(true)
.value_name("functions") .value_name("functions")
.help(&format!("Comma-separated list of exported functions to keep. Default: '{}'", target_runtime.call_symbol))) .help(&format!("Comma-separated list of exported functions to keep. Default: '{}'", target_runtime.symbols().call)))
.get_matches(); .get_matches();
let exports = matches let exports = matches
.value_of("exports") .value_of("exports")
.unwrap_or(target_runtime.call_symbol) .unwrap_or(target_runtime.symbols().call)
.split(',') .split(',')
.collect(); .collect();

View File

@ -51,7 +51,7 @@ impl std::fmt::Display for Error {
fn has_ctor(module: &elements::Module, target_runtime: &TargetRuntime) -> bool { fn has_ctor(module: &elements::Module, target_runtime: &TargetRuntime) -> bool {
if let Some(ref section) = module.export_section() { if let Some(ref section) = module.export_section() {
section.entries().iter().any(|e| target_runtime.create_symbol == e.field()) section.entries().iter().any(|e| target_runtime.symbols().create == e.field())
} else { } else {
false false
} }
@ -94,7 +94,7 @@ pub fn build(
let mut ctor_module = module.clone(); let mut ctor_module = module.clone();
let mut public_api_entries = public_api_entries.to_vec(); let mut public_api_entries = public_api_entries.to_vec();
public_api_entries.push(target_runtime.call_symbol); public_api_entries.push(target_runtime.symbols().call);
if !skip_optimization { if !skip_optimization {
optimize( optimize(
&mut module, &mut module,
@ -104,7 +104,7 @@ pub fn build(
if has_ctor(&ctor_module, target_runtime) { if has_ctor(&ctor_module, target_runtime) {
if !skip_optimization { if !skip_optimization {
optimize(&mut ctor_module, vec![target_runtime.create_symbol])?; optimize(&mut ctor_module, vec![target_runtime.symbols().create])?;
} }
let ctor_module = pack_instance( let ctor_module = pack_instance(
parity_wasm::serialize(module.clone()).map_err(Error::Encoding)?, parity_wasm::serialize(module.clone()).map_err(Error::Encoding)?,

View File

@ -5,59 +5,76 @@
#[macro_use] #[macro_use]
extern crate alloc; extern crate alloc;
extern crate parity_wasm;
extern crate byteorder; extern crate byteorder;
#[macro_use] extern crate log; extern crate parity_wasm;
#[macro_use]
extern crate log;
pub mod rules; pub mod rules;
mod build; mod build;
mod optimizer;
mod gas;
mod symbols;
mod ext; mod ext;
mod gas;
mod optimizer;
mod pack; mod pack;
mod runtime_type; mod runtime_type;
mod symbols;
pub mod stack_height; pub mod stack_height;
pub use build::{build, SourceTarget, Error as BuildError}; pub use build::{build, Error as BuildError, SourceTarget};
pub use optimizer::{optimize, Error as OptimizerError}; pub use ext::{
externalize, externalize_mem, shrink_unknown_stack, underscore_funcs, ununderscore_funcs,
};
pub use gas::inject_gas_counter; pub use gas::inject_gas_counter;
pub use ext::{externalize, externalize_mem, underscore_funcs, ununderscore_funcs, shrink_unknown_stack}; pub use optimizer::{optimize, Error as OptimizerError};
pub use pack::{pack_instance, Error as PackingError}; pub use pack::{pack_instance, Error as PackingError};
pub use runtime_type::inject_runtime_type; pub use runtime_type::inject_runtime_type;
pub struct TargetRuntime { pub struct TargetSymbols {
pub create_symbol: &'static str, pub create: &'static str,
pub call_symbol: &'static str, pub call: &'static str,
pub return_symbol: &'static str, pub return_: &'static str,
}
pub enum TargetRuntime {
Substrate(TargetSymbols),
PWasm(TargetSymbols),
} }
impl TargetRuntime { impl TargetRuntime {
pub fn substrate() -> TargetRuntime {
TargetRuntime {
create_symbol: "deploy",
call_symbol: "call",
return_symbol: "ext_return",
}
}
pub fn pwasm() -> TargetRuntime { pub fn substrate() -> TargetRuntime {
TargetRuntime { TargetRuntime::Substrate(TargetSymbols {
create_symbol: "deploy", create: "deploy",
call_symbol: "call", call: "call",
return_symbol: "ret", return_: "ext_return",
})
}
pub fn pwasm() -> TargetRuntime {
TargetRuntime::PWasm(TargetSymbols {
create: "deploy",
call: "call",
return_: "ret",
})
}
pub fn symbols(&self) -> &TargetSymbols {
match self {
TargetRuntime::Substrate(s) => s,
TargetRuntime::PWasm(s) => s,
} }
} }
} }
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
mod std { mod std {
pub use core::*; pub use alloc::{borrow, boxed, string, vec};
pub use alloc::{vec, string, boxed, borrow}; pub use core::*;
pub mod collections { pub mod collections {
pub use alloc::collections::{BTreeMap, BTreeSet}; pub use alloc::collections::{BTreeMap, BTreeSet};
} }
} }

View File

@ -41,7 +41,7 @@ impl fmt::Display for Error {
} }
} }
/// If module has an exported "CREATE_SYMBOL" function we want to pack it into "constructor". /// If module has an exported function matching "create" symbol we want to pack it into "constructor".
/// `raw_module` is the actual contract code /// `raw_module` is the actual contract code
/// `ctor_module` is the constructor which should return `raw_module` /// `ctor_module` is the constructor which should return `raw_module`
pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, target: &TargetRuntime) -> Result<elements::Module, Error> { pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, target: &TargetRuntime) -> Result<elements::Module, Error> {
@ -49,15 +49,15 @@ pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, tar
// Total number of constructor module import functions // Total number of constructor module import functions
let ctor_import_functions = ctor_module.import_section().map(|x| x.functions()).unwrap_or(0); let ctor_import_functions = ctor_module.import_section().map(|x| x.functions()).unwrap_or(0);
// We need to find an internal ID of function witch is exported as "CREATE_SYMBOL" // We need to find an internal ID of function which is exported as `symbols().create`
// in order to find it in the Code section of the module // in order to find it in the Code section of the module
let mut create_func_id = { let mut create_func_id = {
let found_entry = ctor_module.export_section().ok_or(Error::NoExportSection)?.entries().iter() let found_entry = ctor_module.export_section().ok_or(Error::NoExportSection)?.entries().iter()
.find(|entry| target.create_symbol == entry.field()).ok_or_else(|| Error::NoCreateSymbol(target.create_symbol))?; .find(|entry| target.symbols().create == entry.field()).ok_or_else(|| Error::NoCreateSymbol(target.symbols().create))?;
let function_index: usize = match found_entry.internal() { let function_index: usize = match found_entry.internal() {
&Internal::Function(index) => index as usize, &Internal::Function(index) => index as usize,
_ => { return Err(Error::InvalidCreateMember(target.create_symbol)) }, _ => { return Err(Error::InvalidCreateMember(target.symbols().create)) },
}; };
// Calculates a function index within module's function section // Calculates a function index within module's function section
@ -73,10 +73,10 @@ pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, tar
// Deploy should have no arguments and also should return nothing // Deploy should have no arguments and also should return nothing
if !func.params().is_empty() { if !func.params().is_empty() {
return Err(Error::InvalidCreateSignature(target.create_symbol)); return Err(Error::InvalidCreateSignature(target.symbols().create));
} }
if func.return_type().is_some() { if func.return_type().is_some() {
return Err(Error::InvalidCreateSignature(target.create_symbol)); return Err(Error::InvalidCreateSignature(target.symbols().create));
} }
function_internal_index function_internal_index
@ -87,7 +87,7 @@ pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, tar
let mut found = false; let mut found = false;
for entry in ctor_module.import_section().ok_or(Error::NoImportSection)?.entries().iter() { for entry in ctor_module.import_section().ok_or(Error::NoImportSection)?.entries().iter() {
if let External::Function(_) = *entry.external() { if let External::Function(_) = *entry.external() {
if entry.field() == target.return_symbol { found = true; break; } if entry.field() == target.symbols().return_ { found = true; break; }
else { id += 1; } else { id += 1; }
} }
} }
@ -102,7 +102,7 @@ pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, tar
mbuilder.push_import( mbuilder.push_import(
builder::import() builder::import()
.module("env") .module("env")
.field(&target.return_symbol) .field(&target.symbols().return_)
.external().func(import_sig) .external().func(import_sig)
.build() .build()
); );
@ -195,13 +195,17 @@ pub fn pack_instance(raw_module: Vec<u8>, mut ctor_module: elements::Module, tar
])).build() ])).build()
.build() .build()
.build(); .build();
if let TargetRuntime::Substrate(_) = target {
return Ok(new_module)
}
for section in new_module.sections_mut() { for section in new_module.sections_mut() {
if let &mut Section::Export(ref mut export_section) = section { if let &mut Section::Export(ref mut export_section) = section {
for entry in export_section.entries_mut().iter_mut() { for entry in export_section.entries_mut().iter_mut() {
if target.create_symbol == entry.field() { if target.symbols().create == entry.field() {
// change `create_symbol` export name into default `call_symbol`. // change `create` symbol export name into default `call` symbol name.
*entry.field_mut() = target.call_symbol.to_owned(); *entry.field_mut() = target.symbols().call.to_owned();
*entry.internal_mut() = elements::Internal::Function(last_function_index as u32); *entry.internal_mut() = elements::Internal::Function(last_function_index as u32);
} }
} }
@ -221,8 +225,8 @@ mod test {
fn test_packer(mut module: elements::Module, target_runtime: &TargetRuntime) { fn test_packer(mut module: elements::Module, target_runtime: &TargetRuntime) {
let mut ctor_module = module.clone(); let mut ctor_module = module.clone();
optimize(&mut module, vec![target_runtime.call_symbol]).expect("Optimizer to finish without errors"); optimize(&mut module, vec![target_runtime.symbols().call]).expect("Optimizer to finish without errors");
optimize(&mut ctor_module, vec![target_runtime.create_symbol]).expect("Optimizer to finish without errors"); optimize(&mut ctor_module, vec![target_runtime.symbols().create]).expect("Optimizer to finish without errors");
let raw_module = parity_wasm::serialize(module).unwrap(); let raw_module = parity_wasm::serialize(module).unwrap();
let ctor_module = pack_instance(raw_module.clone(), ctor_module, target_runtime).expect("Packing failed"); let ctor_module = pack_instance(raw_module.clone(), ctor_module, target_runtime).expect("Packing failed");
@ -269,11 +273,11 @@ mod test {
.build() .build()
.build() .build()
.export() .export()
.field(target_runtime.call_symbol) .field(target_runtime.symbols().call)
.internal().func(1) .internal().func(1)
.build() .build()
.export() .export()
.field(target_runtime.create_symbol) .field(target_runtime.symbols().create)
.internal().func(2) .internal().func(2)
.build() .build()
.build(), .build(),
@ -321,11 +325,11 @@ mod test {
.build() .build()
.build() .build()
.export() .export()
.field(target_runtime.call_symbol) .field(target_runtime.symbols().call)
.internal().func(1) .internal().func(1)
.build() .build()
.export() .export()
.field(target_runtime.create_symbol) .field(target_runtime.symbols().create)
.internal().func(2) .internal().func(2)
.build() .build()
.build(), .build(),