1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use std::sync::Arc;
use anyhow::Result;
use wasmtime::ResourceLimiter;
use crate::{
config::{ProcessConfig, UNIT_OF_COMPUTE_IN_INSTRUCTIONS},
state::ProcessState,
ExecutionResult, ResultValue,
};
use super::RawWasm;
#[derive(Clone)]
pub struct WasmtimeRuntime {
engine: wasmtime::Engine,
}
impl WasmtimeRuntime {
pub fn new(config: &wasmtime::Config) -> Result<Self> {
let engine = wasmtime::Engine::new(config)?;
Ok(Self { engine })
}
pub fn compile_module<T>(&self, data: RawWasm) -> Result<WasmtimeCompiledModule<T>>
where
T: ProcessState,
{
let module = wasmtime::Module::new(&self.engine, data.as_slice())?;
let mut linker = wasmtime::Linker::new(&self.engine);
<T as ProcessState>::register(&mut linker)?;
let default_state = T::default();
let mut store = wasmtime::Store::new(&self.engine, default_state);
let instance_pre = linker.instantiate_pre(&mut store, &module)?;
let compiled_module = WasmtimeCompiledModule::new(data, module, instance_pre);
Ok(compiled_module)
}
pub async fn instantiate<T>(
&self,
compiled_module: &WasmtimeCompiledModule<T>,
state: T,
) -> Result<WasmtimeInstance<T>>
where
T: ProcessState + Send + ResourceLimiter,
{
let max_fuel = state.config().get_max_fuel();
let mut store = wasmtime::Store::new(&self.engine, state);
store.limiter(|state| state);
store.out_of_fuel_trap();
match max_fuel {
Some(max_fuel) => {
store.out_of_fuel_async_yield(max_fuel, UNIT_OF_COMPUTE_IN_INSTRUCTIONS)
}
None => store.out_of_fuel_async_yield(u64::MAX, UNIT_OF_COMPUTE_IN_INSTRUCTIONS),
};
let instance = compiled_module
.instantiator()
.instantiate_async(&mut store)
.await?;
store.data_mut().initialize();
Ok(WasmtimeInstance { store, instance })
}
}
pub struct WasmtimeCompiledModule<T> {
inner: Arc<WasmtimeCompiledModuleInner<T>>,
}
pub struct WasmtimeCompiledModuleInner<T> {
source: RawWasm,
module: wasmtime::Module,
instance_pre: wasmtime::InstancePre<T>,
}
impl<T> WasmtimeCompiledModule<T> {
pub fn new(
source: RawWasm,
module: wasmtime::Module,
instance_pre: wasmtime::InstancePre<T>,
) -> WasmtimeCompiledModule<T> {
let inner = Arc::new(WasmtimeCompiledModuleInner {
source,
module,
instance_pre,
});
Self { inner }
}
pub fn exports(&self) -> impl ExactSizeIterator<Item = wasmtime::ExportType<'_>> {
self.inner.module.exports()
}
pub fn source(&self) -> &RawWasm {
&self.inner.source
}
pub fn instantiator(&self) -> &wasmtime::InstancePre<T> {
&self.inner.instance_pre
}
}
impl<T> Clone for WasmtimeCompiledModule<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
pub struct WasmtimeInstance<T>
where
T: Send,
{
store: wasmtime::Store<T>,
instance: wasmtime::Instance,
}
impl<T> WasmtimeInstance<T>
where
T: Send,
{
pub async fn call(mut self, function: &str, params: Vec<wasmtime::Val>) -> ExecutionResult<T> {
let entry = self.instance.get_func(&mut self.store, function);
if entry.is_none() {
return ExecutionResult {
state: self.store.into_data(),
result: ResultValue::SpawnError(format!("Function '{}' not found", function)),
};
}
let result = entry
.unwrap()
.call_async(&mut self.store, ¶ms, &mut [])
.await;
ExecutionResult {
state: self.store.into_data(),
result: match result {
Ok(()) => ResultValue::Ok,
Err(err) => {
match err.downcast_ref::<wasmtime::Trap>() {
Some(trap) => {
if trap.i32_exit_status().is_some()
&& trap.i32_exit_status().unwrap() == 0
{
ResultValue::Ok
} else {
ResultValue::Failed(trap.to_string())
}
}
None => {
ResultValue::Failed("Can't downcast trap to wasmtime::Trap".to_string())
}
}
}
},
}
}
}
pub fn default_config() -> wasmtime::Config {
let mut config = wasmtime::Config::new();
config
.async_support(true)
.debug_info(false)
.consume_fuel(true)
.wasm_reference_types(true)
.wasm_bulk_memory(true)
.wasm_multi_value(true)
.wasm_multi_memory(true)
.cranelift_opt_level(wasmtime::OptLevel::SpeedAndSize)
.allocation_strategy(wasmtime::InstanceAllocationStrategy::OnDemand)
.static_memory_forced(true);
config
}