referrerpolicy=no-referrer-when-downgrade

sc_executor_common/
wasm_runtime.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
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//! Definitions for a wasm runtime.
20
21use crate::error::Error;
22
23use std::time::Duration;
24
25pub use sc_allocator::AllocationStats;
26
27/// Default heap allocation strategy.
28pub const DEFAULT_HEAP_ALLOC_STRATEGY: HeapAllocStrategy =
29	HeapAllocStrategy::Static { extra_pages: DEFAULT_HEAP_ALLOC_PAGES };
30
31/// Default heap allocation pages.
32pub const DEFAULT_HEAP_ALLOC_PAGES: u32 = 2048;
33
34/// A trait that defines an abstract WASM runtime module.
35///
36/// This can be implemented by an execution engine.
37pub trait WasmModule: Sync + Send {
38	/// Create a new instance with the given heap allocation strategy.
39	///
40	/// The `heap_alloc_strategy` determines the memory limits applied to this instance.
41	fn new_instance(
42		&self,
43		heap_alloc_strategy: HeapAllocStrategy,
44	) -> Result<Box<dyn WasmInstance>, Error>;
45}
46
47/// A trait that defines an abstract wasm module instance.
48///
49/// This can be implemented by an execution engine.
50pub trait WasmInstance: Send {
51	/// Call a method on this WASM instance.
52	///
53	/// Before execution, instance is reset.
54	///
55	/// Returns the encoded result on success.
56	fn call(&mut self, method: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
57		self.call_with_allocation_stats(method, data).0
58	}
59
60	/// Call a method on this WASM instance.
61	///
62	/// Before execution, instance is reset.
63	///
64	/// Returns the encoded result on success.
65	fn call_with_allocation_stats(
66		&mut self,
67		method: &str,
68		data: &[u8],
69	) -> (Result<Vec<u8>, Error>, Option<AllocationStats>);
70
71	/// Call an exported method on this WASM instance.
72	///
73	/// Before execution, instance is reset.
74	///
75	/// Returns the encoded result on success.
76	fn call_export(&mut self, method: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
77		self.call(method.into(), data)
78	}
79
80	/// Call a method on this WASM instance, interrupting execution once `timeout` has elapsed.
81	///
82	/// Before execution, instance is reset.
83	///
84	/// Returns the encoded result on success. Fails with [`Error::ExecutionTimeout`] on timeout,
85	/// or with [`Error::ExecutionTimeoutUnsupported`] if the module was not compiled with support
86	/// for execution timeouts.
87	fn call_with_timeout(
88		&mut self,
89		method: &str,
90		data: &[u8],
91		timeout: Duration,
92	) -> Result<Vec<u8>, Error>;
93
94	/// Update the heap allocation strategy for subsequent calls.
95	///
96	/// This is used when an instance is reused from a pool but the caller needs
97	/// a different memory limit than what the instance was originally created with.
98	fn set_heap_alloc_strategy(&mut self, _heap_alloc_strategy: HeapAllocStrategy) {}
99}
100
101/// Defines the heap pages allocation strategy the wasm runtime should use.
102///
103/// A heap page is defined as 64KiB of memory.
104#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq)]
105pub enum HeapAllocStrategy {
106	/// Allocate a static number of heap pages.
107	///
108	/// The total number of allocated heap pages is the initial number of heap pages requested by
109	/// the wasm file plus the `extra_pages`.
110	Static {
111		/// The number of pages that will be added on top of the initial heap pages requested by
112		/// the wasm file.
113		extra_pages: u32,
114	},
115	/// Allocate the initial heap pages as requested by the wasm file and then allow it to grow
116	/// dynamically.
117	Dynamic {
118		/// The absolute maximum size of the linear memory (in pages).
119		///
120		/// When `Some(_)` the linear memory will be allowed to grow up to this limit.
121		/// When `None` the linear memory will be allowed to grow up to the maximum limit supported
122		/// by WASM (4GB).
123		maximum_pages: Option<u32>,
124	},
125}
126
127impl HeapAllocStrategy {
128	/// Double this heap allocation strategy.
129	pub const fn double(self) -> Self {
130		match self {
131			Self::Static { extra_pages } => {
132				Self::Static { extra_pages: extra_pages.saturating_mul(2) }
133			},
134			Self::Dynamic { maximum_pages } => Self::Dynamic {
135				maximum_pages: match maximum_pages {
136					Some(p) => Some(p.saturating_mul(2)),
137					None => None,
138				},
139			},
140		}
141	}
142}