soil_client/executor/common/wasm_runtime.rs
1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Definitions for a wasm runtime.
8
9use super::error::Error;
10
11pub use subsoil::allocator::AllocationStats;
12
13/// Default heap allocation strategy.
14pub const DEFAULT_HEAP_ALLOC_STRATEGY: HeapAllocStrategy =
15 HeapAllocStrategy::Static { extra_pages: DEFAULT_HEAP_ALLOC_PAGES };
16
17/// Default heap allocation pages.
18pub const DEFAULT_HEAP_ALLOC_PAGES: u32 = 2048;
19
20/// A trait that defines an abstract WASM runtime module.
21///
22/// This can be implemented by an execution engine.
23pub trait WasmModule: Sync + Send {
24 /// Create a new instance.
25 fn new_instance(&self) -> Result<Box<dyn WasmInstance>, Error>;
26}
27
28/// A trait that defines an abstract wasm module instance.
29///
30/// This can be implemented by an execution engine.
31pub trait WasmInstance: Send {
32 /// Call a method on this WASM instance.
33 ///
34 /// Before execution, instance is reset.
35 ///
36 /// Returns the encoded result on success.
37 fn call(&mut self, method: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
38 self.call_with_allocation_stats(method, data).0
39 }
40
41 /// Call a method on this WASM instance.
42 ///
43 /// Before execution, instance is reset.
44 ///
45 /// Returns the encoded result on success.
46 fn call_with_allocation_stats(
47 &mut self,
48 method: &str,
49 data: &[u8],
50 ) -> (Result<Vec<u8>, Error>, Option<AllocationStats>);
51
52 /// Call an exported method on this WASM instance.
53 ///
54 /// Before execution, instance is reset.
55 ///
56 /// Returns the encoded result on success.
57 fn call_export(&mut self, method: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
58 self.call(method.into(), data)
59 }
60}
61
62/// Defines the heap pages allocation strategy the wasm runtime should use.
63///
64/// A heap page is defined as 64KiB of memory.
65#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq)]
66pub enum HeapAllocStrategy {
67 /// Allocate a static number of heap pages.
68 ///
69 /// The total number of allocated heap pages is the initial number of heap pages requested by
70 /// the wasm file plus the `extra_pages`.
71 Static {
72 /// The number of pages that will be added on top of the initial heap pages requested by
73 /// the wasm file.
74 extra_pages: u32,
75 },
76 /// Allocate the initial heap pages as requested by the wasm file and then allow it to grow
77 /// dynamically.
78 Dynamic {
79 /// The absolute maximum size of the linear memory (in pages).
80 ///
81 /// When `Some(_)` the linear memory will be allowed to grow up to this limit.
82 /// When `None` the linear memory will be allowed to grow up to the maximum limit supported
83 /// by WASM (4GB).
84 maximum_pages: Option<u32>,
85 },
86}