Skip to content

Commit

Permalink
Make VM compile (no iterator or tests)
Browse files Browse the repository at this point in the history
  • Loading branch information
webmaster128 committed Sep 14, 2020
1 parent cadafc5 commit cc94242
Show file tree
Hide file tree
Showing 13 changed files with 623 additions and 703 deletions.
79 changes: 3 additions & 76 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion packages/vm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ staking = ["cosmwasm-std/staking"]
cosmwasm-std = { path = "../std", version = "0.10.1" }
serde_json = "1.0"
wasmer = { path = "../../../wasmer/lib/api" }
wasmer-compiler = { path = "../../../wasmer/lib/compiler" }
wasmer-compiler-cranelift = { path = "../../../wasmer/lib/compiler-cranelift", optional = true }
wasmer-compiler-singlepass = { path = "../../../wasmer/lib/compiler-singlepass", optional = true }
wasmer-runtime-core = { path = "../../../wasmer/lib/deprecated/runtime-core" }
wasmer-engine = { path = "../../../wasmer/lib/engine" }
wasmer-engine-jit = { path = "../../../wasmer/lib/engine-jit" }
wasmer-types = { path = "../../../wasmer/lib/wasmer-types" }
schemars = "0.7"
serde = { version = "1.0.103", default-features = false, features = ["derive", "alloc"] }
Expand Down
20 changes: 9 additions & 11 deletions packages/vm/src/backends/cranelift.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#![cfg(any(feature = "cranelift", feature = "default-cranelift"))]

use wasmer_clif_backend::CraneliftCompiler;
use wasmer_runtime_core::{
backend::Compiler, backend::CompilerConfig, compile_with_config, module::Module, vm::Ctx,
};
use wasmer::Module;
use wasmer_compiler_cranelift::Cranelift;
use wasmer_engine_jit::JIT;

use crate::errors::VmResult;

Expand All @@ -14,22 +13,21 @@ pub fn compile(code: &[u8]) -> VmResult<Module> {
enable_verification: false, // As discussed in https://github.com/CosmWasm/cosmwasm/issues/155
..Default::default()
};
let module = compile_with_config(code, compiler().as_ref(), config)?;
let compiler = Cranelift::default();
let engine = JIT::new(&mut compiler).engine();
let store = Store::new(&engine);
let module = Module::new(&store, code)?;
Ok(module)
}

pub fn compiler() -> Box<dyn Compiler> {
Box::new(CraneliftCompiler::new())
}

pub fn backend() -> &'static str {
"cranelift"
}

/// Set the amount of gas units that can be used in the context.
pub fn set_gas_left(_ctx: &mut Ctx, _amount: u64) {}
pub fn set_gas_left<S: Storage, Q: Querier>(_env: &mut Env<S, Q>, _amount: u64) {}

/// Get how many more gas units can be used in the context.
pub fn get_gas_left(_ctx: &Ctx) -> u64 {
pub fn get_gas_left<S: Storage, Q: Querier>(_env: &Env<S, Q>) -> u64 {
FAKE_GAS_AVAILABLE
}
31 changes: 11 additions & 20 deletions packages/vm/src/backends/mod.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
pub mod cranelift;
pub mod singlepass;

pub use wasmer_runtime_core::backend::Compiler;
use wasmer_runtime_core::vm::Ctx;

pub fn compiler_for_backend(backend: &str) -> Option<Box<dyn Compiler>> {
match backend {
#[cfg(any(feature = "cranelift", feature = "default-cranelift"))]
"cranelift" => Some(cranelift::compiler()),

#[cfg(any(feature = "singlepass", feature = "default-singlepass"))]
"singlepass" => Some(singlepass::compiler()),

_ => None,
}
}
use crate::context::Env;
use crate::traits::{Querier, Storage};

#[derive(Debug)]
pub struct InsufficientGasLeft;

/// Decreases gas left by the given amount.
/// If the amount exceeds the available gas, the remaining gas is set to 0 and
/// an InsufficientGasLeft error is returned.
pub fn decrease_gas_left(ctx: &mut Ctx, amount: u64) -> Result<(), InsufficientGasLeft> {
let remaining = get_gas_left(ctx);
pub fn decrease_gas_left<S: Storage, Q: Querier>(
env: &mut Env<S, Q>,
amount: u64,
) -> Result<(), InsufficientGasLeft> {
let remaining = get_gas_left(env);
if amount > remaining {
set_gas_left(ctx, 0);
set_gas_left(env, 0);
Err(InsufficientGasLeft)
} else {
set_gas_left(ctx, remaining - amount);
set_gas_left(env, remaining - amount);
Ok(())
}
}
Expand All @@ -44,12 +35,12 @@ pub use singlepass::{backend, compile, get_gas_left, set_gas_left};
mod test {
use super::*;
use wabt::wat2wasm;
use wasmer_runtime_core::{imports, Instance as WasmerInstance};
use wasmer::{imports, Instance as WasmerInstance};

fn instantiate(code: &[u8]) -> WasmerInstance {
let module = compile(code).unwrap();
let import_obj = imports! { "env" => {}, };
module.instantiate(&import_obj).unwrap()
WasmerInstance::new(&module, &import_obj).unwrap()
}

#[test]
Expand Down
33 changes: 15 additions & 18 deletions packages/vm/src/backends/singlepass.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
#![cfg(any(feature = "singlepass", feature = "default-singlepass"))]

// use wasmer_middleware_common::metering;
use wasmer_compiler_singlepass::{Singlepass, SinglepassCompiler};
use wasmer_runtime_core::{
backend::{Backend, Compiler},
compile_with,
module::Module,
vm::Ctx,
};

use crate::errors::{VmError, VmResult};
use wasmer::{Module, Store};
use wasmer_compiler_singlepass::Singlepass;
use wasmer_engine_jit::JIT;

use crate::context::Env;
use crate::errors::VmResult;
use crate::traits::{Querier, Storage};
// use crate::middleware::DeterministicMiddleware;

/// In Wasmer, the gas limit is set on modules during compilation and is included in the cached modules.
Expand All @@ -26,23 +24,22 @@ const MAX_GAS_LIMIT: u64 = u64::MAX / 2;
const FAKE_GAS_AVAILABLE: u64 = 1_000_000;

pub fn compile(code: &[u8]) -> VmResult<Module> {
compile_with(code, Backend::Auto).map_err(|err| VmError::compile_err(err.to_string()))
}

pub fn compiler() -> Box<dyn Compiler> {
let config = Singlepass::default();
Box::new(SinglepassCompiler::new(&config))
let compiler = Singlepass::default();
let engine = JIT::new(&compiler).engine();
let store = Store::new(&engine);
let module = Module::new(&store, code)?;
Ok(module)
}

pub fn backend() -> &'static str {
"singlepass"
}

/// Set the amount of gas units that can be used in the context.
pub fn set_gas_left(_ctx: &mut Ctx, _amount: u64) {}
pub fn set_gas_left<S: Storage, Q: Querier>(_env: &mut Env<S, Q>, _amount: u64) {}

/// Get how many more gas units can be used in the context.
pub fn get_gas_left(_ctx: &Ctx) -> u64 {
pub fn get_gas_left<S: Storage, Q: Querier>(_env: &Env<S, Q>) -> u64 {
FAKE_GAS_AVAILABLE
}

Expand Down Expand Up @@ -70,7 +67,7 @@ pub fn get_gas_left(_ctx: &Ctx) -> u64 {
mod test {
use super::*;
use wabt::wat2wasm;
use wasmer_runtime_core::{imports, Instance as WasmerInstance};
use wasmer::{imports, Instance as WasmerInstance};

fn instantiate(code: &[u8]) -> WasmerInstance {
let module = compile(code).unwrap();
Expand Down
22 changes: 6 additions & 16 deletions packages/vm/src/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use serde::de::DeserializeOwned;
use std::fmt;

use cosmwasm_std::{Env, HandleResult, InitResult, MigrateResult, QueryResult};
use wasmer::Val;

use crate::errors::{VmError, VmResult};
use crate::instance::{Func, Instance};
use crate::instance::Instance;
use crate::serde::{from_slice, to_vec};
use crate::traits::{Api, Querier, Storage};
use schemars::JsonSchema;
Expand Down Expand Up @@ -131,25 +132,14 @@ fn call_raw<S: Storage + 'static, A: Api + 'static, Q: Querier + 'static>(
args: &[&[u8]],
result_max_length: usize,
) -> VmResult<Vec<u8>> {
let mut arg_region_ptrs = Vec::<u32>::with_capacity(args.len());
let mut arg_region_ptrs = Vec::<Val>::with_capacity(args.len());
for arg in args {
let region_ptr = instance.allocate(arg.len())?;
instance.write_memory(region_ptr, arg)?;
arg_region_ptrs.push(region_ptr);
arg_region_ptrs.push(region_ptr.into());
}

let res_region_ptr = match args.len() {
1 => {
let func: Func<u32, u32> = instance.func(name)?;
func.call(arg_region_ptrs[0])?
}
2 => {
let func: Func<(u32, u32), u32> = instance.func(name)?;
func.call(arg_region_ptrs[0], arg_region_ptrs[1])?
}
_ => panic!("call_raw called with unsupported number of arguments"),
};

let result = instance.call_function(name, &arg_region_ptrs)?;
let res_region_ptr = result[0].unwrap_i32() as u32;
let data = instance.read_memory(res_region_ptr, result_max_length)?;
// free return value in wasm (arguments were freed in wasm code)
instance.deallocate(res_region_ptr)?;
Expand Down
Loading

0 comments on commit cc94242

Please sign in to comment.