Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Normalize missing entry case #659

Merged
merged 4 commits into from Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion core-backend/common/src/lib.rs
Expand Up @@ -90,7 +90,7 @@ pub trait Environment<E: Ext + Into<ExtInfo> + 'static>: Default + Sized {
) -> Result<(), BackendError<'static>>;

/// Run setuped instance starting at `entry_point` - wasm export function name.
/// NOTE: expternal environment must be setuped.
/// NOTE: external environment must be setuped.
breathx marked this conversation as resolved.
Show resolved Hide resolved
fn execute(&mut self, entry_point: &str) -> Result<BackendReport, BackendError>;

/// Create internal representation of wasm memory with size `total_pages`
Expand Down
4 changes: 2 additions & 2 deletions core-backend/sandbox/Cargo.toml
Expand Up @@ -9,12 +9,12 @@ license = "GPL-3.0"
gear-core = { path = "../../core" }
gear-backend-common = { path = "../common" }
common = { package = "gear-common", path = "../../common", default-features = false }
sp-io = { version = "4.0.0-dev", git = "https://github.com/gear-tech/substrate.git", branch = "gear-stable", default-features = false }

parity-wasm = { version = "0.42.2", default-features = false }
sp-io = { version = "4.0.0-dev", git = "https://github.com/gear-tech/substrate.git", branch = "gear-stable", default-features = false }
sp-sandbox = { version = "0.10.0-dev", git = "https://github.com/gear-tech/substrate.git", branch = "gear-stable", default-features = false }
log = { version = "0.4.14", default-features = false }

[features]
default = ["std"]
std = ["sp-sandbox/std", "log/std"]

59 changes: 51 additions & 8 deletions core-backend/sandbox/src/env.rs
Expand Up @@ -19,7 +19,7 @@
//! sp-sandbox environment for running a module.

use crate::{funcs, memory::MemoryWrap};
use alloc::{boxed::Box, collections::BTreeMap, format};
use alloc::{boxed::Box, collections::BTreeMap, format, string::String, vec::Vec};
use gear_backend_common::{
funcs as common_funcs, BackendError, BackendReport, Environment, ExtInfo, TerminationReason,
};
Expand All @@ -29,30 +29,44 @@ use gear_core::{
};
use sp_sandbox::{
default_executor::{EnvironmentDefinitionBuilder, Instance, Memory as DefaultExecutorMemory},
SandboxEnvironmentBuilder, SandboxInstance, SandboxMemory,
ReturnValue, SandboxEnvironmentBuilder, SandboxInstance, SandboxMemory,
};

/// Environment to run one module at a time providing Ext.
pub struct SandboxEnvironment<E: Ext + Into<ExtInfo>> {
pub struct SandboxEnvironment<E>
where
E: Ext + Into<ExtInfo>,
{
runtime: Option<Runtime<E>>,
instance: Option<Instance<Runtime<E>>>,
entries: Option<Vec<String>>,
}

impl<E: Ext + Into<ExtInfo>> Default for SandboxEnvironment<E> {
impl<E> Default for SandboxEnvironment<E>
where
E: Ext + Into<ExtInfo>,
{
fn default() -> Self {
Self {
runtime: None,
instance: None,
entries: None,
}
}
}

pub struct Runtime<E: Ext + Into<ExtInfo>> {
pub struct Runtime<E>
where
E: Ext + Into<ExtInfo>,
{
pub(crate) ext: LaterExt<E>,
pub(crate) trap: Option<&'static str>,
}

impl<E: Ext + Into<ExtInfo> + 'static> Runtime<E> {
impl<E> Runtime<E>
where
E: Ext + Into<ExtInfo> + 'static,
{
fn new(ext: E) -> Self {
let mut later_ext = LaterExt::default();
later_ext.set(ext);
Expand All @@ -64,7 +78,21 @@ impl<E: Ext + Into<ExtInfo> + 'static> Runtime<E> {
}
}

impl<E: Ext + Into<ExtInfo> + 'static> Environment<E> for SandboxEnvironment<E> {
fn get_module_exports(binary: &[u8]) -> Result<Vec<String>, String> {
Ok(parity_wasm::elements::Module::from_bytes(binary)
.map_err(|e| format!("Unable to create wasm module: {}", e))?
.export_section()
.ok_or_else(|| String::from("Unable to get wasm module section"))?
.entries()
.iter()
.map(|v| String::from(v.field()))
.collect())
}

impl<E> Environment<E> for SandboxEnvironment<E>
where
E: Ext + Into<ExtInfo> + 'static,
{
fn setup(
&mut self,
ext: E,
Expand Down Expand Up @@ -125,6 +153,15 @@ impl<E: Ext + Into<ExtInfo> + 'static> Environment<E> for SandboxEnvironment<E>
}
})?;

let entries = get_module_exports(binary).map_err(|e| {
let info: ExtInfo = runtime.ext.unset().into();
BackendError {
reason: "Unable to get wasm module exports",
description: Some(format!("{:?}", e).into()),
gas_amount: info.gas_amount,
}
})?;

// Set module memory.
memory.set_pages(memory_pages).map_err(|e| {
let info: ExtInfo = runtime.ext.unset().into();
Expand All @@ -138,15 +175,21 @@ impl<E: Ext + Into<ExtInfo> + 'static> Environment<E> for SandboxEnvironment<E>

self.runtime.replace(runtime);
self.instance.replace(instance);
self.entries.replace(entries);

Ok(())
}

fn execute(&mut self, entry_point: &str) -> Result<BackendReport, BackendError> {
let instance = self.instance.as_mut().expect("Must have instance");
let runtime = self.runtime.as_mut().expect("Must have runtime");
let entries = self.entries.as_mut().expect("Must have entries");

let res = instance.invoke(entry_point, &[], runtime);
let res = if entries.contains(&String::from(entry_point)) {
instance.invoke(entry_point, &[], runtime)
} else {
Ok(ReturnValue::Unit)
};

let info: ExtInfo = runtime.ext.unset().into();

Expand Down
16 changes: 11 additions & 5 deletions core-backend/wasmtime/src/env.rs
Expand Up @@ -322,11 +322,17 @@ impl<E: Ext + Into<ExtInfo>> Environment<E> for WasmtimeEnvironment<E> {
fn execute(&mut self, entry_point: &str) -> Result<BackendReport, BackendError> {
let instance = self.instance.as_mut().expect("Must have instance");

let entry_func = instance.get_func(entry_point).ok_or_else(|| BackendError {
reason: "Unable to find function export",
description: Some(format!("Failed to find `{}` function export", entry_point).into()),
gas_amount: self.ext.unset().into().gas_amount,
})?;
let entry_func = match instance.get_func(entry_point) {
// Entry function found
Some(f) => f,
// Entry function not found, so we mean this as empty function
_ => {
return Ok(BackendReport {
termination: TerminationReason::Success,
info: self.ext.unset().into(),
})
}
};

let res = entry_func.call(&[]);

Expand Down
3 changes: 0 additions & 3 deletions examples/block-info/src/lib.rs
Expand Up @@ -13,6 +13,3 @@ pub unsafe extern "C" fn handle() {
let bh = exec::block_height();
msg::reply_bytes(format!("{}_{}", payload, bh), 10_000_000, 0);
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/bot/src/lib.rs
Expand Up @@ -170,9 +170,6 @@ pub unsafe extern "C" fn handle() {
}
}

#[no_mangle]
pub unsafe extern "C" fn handle_reply() {}

#[no_mangle]
pub unsafe extern "C" fn init() {
let maybe_handlers: Result<Vec<Handler>, _> = msg::load();
Expand Down
3 changes: 0 additions & 3 deletions examples/collector/src/lib.rs
Expand Up @@ -30,6 +30,3 @@ pub unsafe extern "C" fn handle() {
MY_COLLECTION.insert(COUNTER, new_msg);
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/decoder/src/lib.rs
Expand Up @@ -51,6 +51,3 @@ pub unsafe extern "C" fn handle() {

handle.commit(msg::source(), 10_000_000, 0);
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
6 changes: 0 additions & 6 deletions examples/exit-code/src/lib.rs
Expand Up @@ -4,12 +4,6 @@ use gstd::{msg, prelude::ToString, ActorId};

static mut HOST: ActorId = ActorId::new([0u8; 32]);

#[no_mangle]
pub unsafe extern "C" fn init() {}

#[no_mangle]
pub unsafe extern "C" fn handle() {}

#[no_mangle]
pub unsafe extern "C" fn handle_reply() {
msg::send_bytes(HOST, msg::exit_code().to_string(), 0, 0);
Expand Down
3 changes: 0 additions & 3 deletions examples/fib/src/lib.rs
Expand Up @@ -36,6 +36,3 @@ pub unsafe extern "C" fn handle() {
debug!(log);
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/guestbook/src/lib.rs
Expand Up @@ -38,6 +38,3 @@ pub unsafe extern "C" fn handle() {
}
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/mem/src/lib.rs
Expand Up @@ -9,6 +9,3 @@ pub unsafe extern "C" fn handle() {
msg::reply(&data, 0, 0);
panic!()
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/minimal/src/lib.rs
Expand Up @@ -6,6 +6,3 @@ use gstd::msg;
pub unsafe extern "C" fn handle() {
msg::reply(b"Hello world!", 0, 0);
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/multiping/src/lib.rs
Expand Up @@ -22,6 +22,3 @@ pub unsafe extern "C" fn handle() {
msg::send_commit(handle, msg::source(), 10_000_000, 0);
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
8 changes: 2 additions & 6 deletions examples/panicker/src/lib.rs
@@ -1,13 +1,9 @@
#![no_std]

// for panic/oom handlers
extern crate gstd;
use gstd::debug;

#[no_mangle]
pub unsafe extern "C" fn handle() {
gstd::debug!("Starting panicker handle");
debug!("Starting panicker handle");
panic!("I just panic every time")
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
5 changes: 0 additions & 5 deletions examples/ping/src/lib.rs
Expand Up @@ -22,8 +22,3 @@ pub unsafe extern "C" fn handle() {
debug!(log);
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {
debug!("Hello from ping init");
}
3 changes: 0 additions & 3 deletions examples/program-id/src/lib.rs
Expand Up @@ -9,6 +9,3 @@ pub unsafe extern "C" fn handle() {
debug!("My program id: {:?}", program_id);
msg::reply(b"program_id", 0, 0);
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/state_rollback/src/lib.rs
Expand Up @@ -28,6 +28,3 @@ pub unsafe extern "C" fn handle() {
}
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
26 changes: 4 additions & 22 deletions examples/sync_duplicate/src/lib.rs
Expand Up @@ -4,34 +4,16 @@ use gstd::{msg, prelude::*};

static mut COUNTER: usize = 0;

fn increase() {
unsafe {
COUNTER += 1;
}
}

fn get() -> i32 {
(unsafe { COUNTER }) as i32
}

fn clear() {
unsafe {
COUNTER = 0;
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}

#[gstd::async_main]
async fn main() {
let msg = String::from_utf8(msg::load_bytes()).expect("Invalid message: should be utf-8");
if &msg == "async" {
increase();
COUNTER += 1;
let _ = msg::send_bytes_and_wait_for_reply(2.into(), b"PING", 100_000_000, 0)
.await
.expect("Error in async message processing");
msg::reply(get(), 100_000_000, 0);
clear();
msg::reply(COUNTER as i32, 100_000_000, 0);

COUNTER = 0;
};
}
3 changes: 0 additions & 3 deletions examples/vec/src/lib.rs
Expand Up @@ -27,6 +27,3 @@ pub unsafe extern "C" fn handle() {
debug!(log);
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}
3 changes: 0 additions & 3 deletions examples/wait/src/lib.rs
Expand Up @@ -33,6 +33,3 @@ pub unsafe extern "C" fn handle() {
}
}
}

#[no_mangle]
pub unsafe extern "C" fn init() {}