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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
mod dispatch;
mod func_info;
use crate::{
budget::CostType,
host::{Frame, HostImpl},
HostError, VmCaller,
};
use std::{cell::RefCell, io::Cursor, ops::RangeInclusive, rc::Rc};
use super::{
xdr::{Hash, ScVal, ScVec},
Host, RawVal, Symbol,
};
use func_info::HOST_FUNCTIONS;
use soroban_env_common::{
meta,
xdr::{ReadXdr, ScEnvMetaEntry, ScHostFnErrorCode, ScVmErrorCode},
ConversionError,
};
use wasmi::{
core::Value, Caller, Engine, Instance, Linker, Memory, Module, StepMeter, Store,
StoreContextMut,
};
impl wasmi::core::HostError for HostError {}
impl StepMeter for HostImpl {
fn max_insn_step(&self) -> u64 {
256
}
fn charge_cpu(&self, insns: u64) -> Result<(), wasmi::core::TrapCode> {
self.budget
.clone()
.charge(CostType::WasmInsnExec, insns)
.map_err(|_| wasmi::core::TrapCode::CpuLimitExceeded)
}
fn charge_mem(&self, bytes: u64) -> Result<(), wasmi::core::TrapCode> {
self.budget
.clone()
.charge(CostType::WasmMemAlloc, bytes)
.map_err(|_| wasmi::core::TrapCode::MemLimitExceeded)
}
}
pub struct Vm {
#[allow(dead_code)]
pub(crate) contract_id: Hash,
module: Module,
store: RefCell<Store<Host>>,
instance: Instance,
memory: Option<Memory>,
}
#[derive(Clone, Eq, PartialEq)]
pub struct VmFunction {
pub name: String,
pub param_count: usize,
pub result_count: usize,
}
impl Vm {
fn check_meta_section(host: &Host, m: &Module) -> Result<(), HostError> {
const SUPPORTED_INTERFACE_VERSION_RANGE: RangeInclusive<u64> =
meta::INTERFACE_VERSION..=meta::INTERFACE_VERSION;
if let Some(env_meta) = Self::module_custom_section(m, meta::ENV_META_V0_SECTION_NAME) {
let mut cursor = Cursor::new(env_meta);
for env_meta_entry in ScEnvMetaEntry::read_xdr_iter(&mut cursor) {
match host.map_err(env_meta_entry)? {
ScEnvMetaEntry::ScEnvMetaKindInterfaceVersion(v) => {
if SUPPORTED_INTERFACE_VERSION_RANGE.contains(&v) {
return Ok(());
} else {
return Err(host.err_status_msg(
ScHostFnErrorCode::InputArgsInvalid,
"unexpected environment interface version",
));
}
}
#[allow(unreachable_patterns)]
_ => (),
}
}
Err(host.err_status_msg(
ScHostFnErrorCode::InputArgsInvalid,
"missing environment interface version",
))
} else {
Err(host.err_status_msg(
ScHostFnErrorCode::InputArgsInvalid,
"input contract missing metadata section",
))
}
}
pub fn new(
host: &Host,
contract_id: Hash,
module_wasm_code: &[u8],
) -> Result<Rc<Self>, HostError> {
host.charge_budget(CostType::VmInstantiation, module_wasm_code.len() as u64)?;
let mut config = wasmi::Config::default();
config.wasm_multi_value(false);
config.wasm_mutable_global(false);
config.wasm_saturating_float_to_int(false);
config.wasm_sign_extension(false);
assert!(config.wasm_features().deterministic_only);
let engine = Engine::new(&config);
let module = host.map_err(Module::new(&engine, module_wasm_code))?;
Self::check_meta_section(host, &module)?;
let mut store = Store::new(&engine, host.clone());
store.set_step_meter(host.0.clone());
let mut linker = <Linker<Host>>::new();
for hf in HOST_FUNCTIONS {
let func = (hf.wrap)(&mut store);
linker.define(hf.mod_str, hf.fn_str, func).map_err(|_| {
host.err_status_msg(ScVmErrorCode::Instantiation, "error defining host function")
})?;
}
let not_started_instance = host.map_err(linker.instantiate(&mut store, &module))?;
let instance = not_started_instance
.ensure_no_start(&mut store)
.map_err(|_| {
host.err_status_msg(
ScVmErrorCode::Instantiation,
"module contains disallowed start function",
)
})?;
let memory = if let Some(ext) = instance.get_export(&mut store, "memory") {
ext.into_memory()
} else {
None
};
let store = RefCell::new(store);
Ok(Rc::new(Self {
contract_id,
module,
store,
instance,
memory,
}))
}
pub(crate) fn get_memory(&self, host: &Host) -> Result<Memory, HostError> {
match self.memory {
Some(mem) => Ok(mem),
None => {
Err(host.err_status_msg(ScVmErrorCode::Memory, "no linear memory named `memory`"))
}
}
}
pub(crate) fn invoke_function_raw(
self: &Rc<Self>,
host: &Host,
func: &str,
args: &[RawVal],
) -> Result<RawVal, HostError> {
host.charge_budget(CostType::InvokeVmFunction, 1)?;
host.with_frame(
Frame::ContractVM(self.clone(), Symbol::from_str(func)),
|| {
let wasm_args: Vec<Value> = args
.iter()
.map(|i| Value::I64(i.get_payload() as i64))
.collect();
let mut wasm_ret: [Value; 1] = [Value::I64(0)];
let ext = match self.instance.get_export(&*self.store.borrow(), func) {
None => {
return Err(
host.err_status_msg(ScVmErrorCode::Unknown, "invoking unknown export")
)
}
Some(e) => e,
};
let func = match ext.into_func() {
None => {
return Err(
host.err_status_msg(ScVmErrorCode::Unknown, "export is not a function")
)
}
Some(e) => e,
};
host.map_err(func.call(
&mut *self.store.borrow_mut(),
wasm_args.as_slice(),
&mut wasm_ret,
))?;
Ok(wasm_ret[0].try_into().ok_or(ConversionError)?)
},
)
}
pub fn invoke_function(
self: &Rc<Self>,
host: &Host,
func: &str,
args: &ScVec,
) -> Result<ScVal, HostError> {
let mut raw_args: Vec<RawVal> = Vec::new();
for scv in args.0.iter() {
raw_args.push(host.to_host_val(scv)?);
}
let raw_res = self.invoke_function_raw(host, func, raw_args.as_slice())?;
Ok(host.from_host_val(raw_res)?)
}
pub fn functions(&self) -> Vec<VmFunction> {
let mut res = Vec::new();
for e in self.module.exports() {
if let wasmi::ExportItemKind::Func(f) = e.kind() {
res.push(VmFunction {
name: e.name().to_string(),
param_count: f.params().len(),
result_count: f.results().len(),
})
}
}
res
}
fn module_custom_section(m: &Module, name: impl AsRef<str>) -> Option<&[u8]> {
m.custom_sections().iter().find_map(|s| {
if &*s.name == name.as_ref() {
Some(&*s.data)
} else {
None
}
})
}
pub fn custom_section(&self, name: impl AsRef<str>) -> Option<&[u8]> {
Self::module_custom_section(&self.module, name)
}
pub fn with_vmcaller<F, T>(&self, f: F) -> T
where
F: FnOnce(&mut VmCaller<Host>) -> T,
{
let store: &mut Store<Host> = &mut *self.store.borrow_mut();
let mut ctx: StoreContextMut<Host> = store.into();
let caller: Caller<Host> = Caller::new(&mut ctx, Some(self.instance));
let mut vmcaller: VmCaller<Host> = VmCaller(Some(caller));
f(&mut vmcaller)
}
}