gear_backend_common/
runtime.rs

1// This file is part of Gear.
2
3// Copyright (C) 2023 Gear Technologies Inc.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Trait that both sandbox and wasmi runtimes must implement.
20
21use crate::{
22    memory::{MemoryAccessRecorder, MemoryOwner},
23    BackendExternalities, BackendState, BackendSyscallError, UndefinedTerminationReason,
24};
25use gear_core::{costs::RuntimeCosts, pages::WasmPage};
26use gear_core_errors::ExtError as FallibleExtError;
27
28/// Error returned from closure argument in [`Runtime::run_fallible`].
29#[derive(Debug, Clone)]
30pub enum RunFallibleError {
31    UndefinedTerminationReason(UndefinedTerminationReason),
32    FallibleExt(FallibleExtError),
33}
34
35impl<E> From<E> for RunFallibleError
36where
37    E: BackendSyscallError,
38{
39    fn from(err: E) -> Self {
40        err.into_run_fallible_error()
41    }
42}
43
44pub trait Runtime<Ext: BackendExternalities>:
45    MemoryOwner + MemoryAccessRecorder + BackendState
46{
47    type Error;
48
49    fn unreachable_error() -> Self::Error;
50
51    fn ext_mut(&mut self) -> &mut Ext;
52
53    fn run_any<T, F>(
54        &mut self,
55        gas: u64,
56        cost: RuntimeCosts,
57        f: F,
58    ) -> Result<(u64, T), Self::Error>
59    where
60        F: FnOnce(&mut Self) -> Result<T, UndefinedTerminationReason>;
61
62    fn run_fallible<T: Sized, F, R>(
63        &mut self,
64        gas: u64,
65        res_ptr: u32,
66        cost: RuntimeCosts,
67        f: F,
68    ) -> Result<(u64, ()), Self::Error>
69    where
70        F: FnOnce(&mut Self) -> Result<T, RunFallibleError>,
71        R: From<Result<T, u32>> + Sized;
72
73    fn alloc(&mut self, pages: u32) -> Result<WasmPage, Ext::AllocError>;
74}