gear_sandbox_env/
lib.rs

1// This file is part of Gear.
2
3// Copyright (C) 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//! Definition of a sandbox environment.
20
21#![cfg_attr(not(feature = "std"), no_std)]
22
23extern crate alloc;
24
25use alloc::string::String;
26use codec::{Decode, Encode};
27use sp_debug_derive::RuntimeDebug;
28use sp_std::vec::Vec;
29use sp_wasm_interface_common::ReturnValue;
30
31#[derive(Clone, Copy, Debug)]
32pub enum Instantiate {
33    /// The first version of instantiate method and syscalls.
34    Version1,
35    /// The second version of syscalls changes their signatures to
36    /// accept global gas value as its first argument and return the remaining
37    /// gas value as its first result tuple element. The approach eliminates
38    /// redundant host calls to get/set WASM-global value.
39    Version2,
40}
41
42/// Error error that can be returned from host function.
43#[derive(Encode, Decode, RuntimeDebug)]
44#[codec(crate = codec)]
45pub struct HostError;
46
47/// Describes an entity to define or import into the environment.
48#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
49#[codec(crate = codec)]
50pub enum ExternEntity {
51    /// Function that is specified by an index in a default table of
52    /// a module that creates the sandbox.
53    #[codec(index = 1)]
54    Function(u32),
55
56    /// Linear memory that is specified by some identifier returned by sandbox
57    /// module upon creation new sandboxed memory.
58    #[codec(index = 2)]
59    Memory(u32),
60}
61
62/// An entry in a environment definition table.
63///
64/// Each entry has a two-level name and description of an entity
65/// being defined.
66#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
67#[codec(crate = codec)]
68pub struct Entry {
69    /// Module name of which corresponding entity being defined.
70    pub module_name: String,
71    /// Field name in which corresponding entity being defined.
72    pub field_name: String,
73    /// External entity being defined.
74    pub entity: ExternEntity,
75}
76
77/// Definition of runtime that could be used by sandboxed code.
78#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
79#[codec(crate = codec)]
80pub struct EnvironmentDefinition {
81    /// Vector of all entries in the environment definition.
82    pub entries: Vec<Entry>,
83}
84
85/// Constant for specifying no limit when creating a sandboxed
86/// memory instance. For FFI purposes.
87pub const MEM_UNLIMITED: u32 = -1i32 as u32;
88
89/// No error happened.
90///
91/// For FFI purposes.
92pub const ERR_OK: u32 = 0;
93
94/// Validation or instantiation error occurred when creating new
95/// sandboxed module instance.
96///
97/// For FFI purposes.
98pub const ERR_MODULE: u32 = -1i32 as u32;
99
100/// Out-of-bounds access attempted with memory or table.
101///
102/// For FFI purposes.
103pub const ERR_OUT_OF_BOUNDS: u32 = -2i32 as u32;
104
105/// Execution error occurred (typically trap).
106///
107/// For FFI purposes.
108pub const ERR_EXECUTION: u32 = -3i32 as u32;
109
110/// A global variable has been successfully changed.
111///
112/// For FFI purposes.
113pub const ERROR_GLOBALS_OK: u32 = 0;
114
115/// A global variable is not found.
116///
117/// For FFI purposes.
118pub const ERROR_GLOBALS_NOT_FOUND: u32 = u32::MAX;
119
120/// A global variable is immutable or has a different type.
121///
122/// For FFI purposes.
123pub const ERROR_GLOBALS_OTHER: u32 = u32::MAX - 1;
124
125/// Typed value that can be returned from a wasm function
126/// through the dispatch thunk.
127/// Additionally contains globals values.
128#[derive(Clone, Copy, PartialEq, Encode, Decode, Debug)]
129#[codec(crate = codec)]
130pub struct WasmReturnValue {
131    pub gas: i64,
132    pub inner: ReturnValue,
133}
134
135impl WasmReturnValue {
136    pub const ENCODED_MAX_SIZE: usize = 8 + ReturnValue::ENCODED_MAX_SIZE;
137}
138
139// TODO #3057
140pub const GLOBAL_NAME_GAS: &str = "gear_gas";
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use codec::Codec;
146    use std::fmt;
147
148    fn roundtrip<S: Codec + PartialEq + fmt::Debug>(s: S) {
149        let encoded = s.encode();
150        assert_eq!(S::decode(&mut &encoded[..]).unwrap(), s);
151    }
152
153    #[test]
154    fn env_def_roundtrip() {
155        roundtrip(EnvironmentDefinition { entries: vec![] });
156
157        roundtrip(EnvironmentDefinition {
158            entries: vec![Entry {
159                module_name: "kernel".to_string(),
160                field_name: "memory".to_string(),
161                entity: ExternEntity::Memory(1337),
162            }],
163        });
164
165        roundtrip(EnvironmentDefinition {
166            entries: vec![Entry {
167                module_name: "env".to_string(),
168                field_name: "abort".to_string(),
169                entity: ExternEntity::Function(228),
170            }],
171        });
172    }
173}