casper_wasmi/
runner.rs

1use crate::{
2    func::{FuncInstance, FuncInstanceInternal, FuncRef},
3    host::Externals,
4    isa,
5    memory::MemoryRef,
6    memory_units::Pages,
7    module::ModuleRef,
8    nan_preserving_float::{F32, F64},
9    value::{
10        ArithmeticOps,
11        ExtendInto,
12        Float,
13        Integer,
14        LittleEndianConvert,
15        TransmuteInto,
16        TryTruncateInto,
17        WrapInto,
18    },
19    RuntimeValue,
20    Signature,
21    Trap,
22    TrapCode,
23    ValueType,
24};
25use alloc::{boxed::Box, vec::Vec};
26use casper_wasm::elements::Local;
27#[cfg(feature = "sign_ext")]
28use casper_wasmi_core::SignExtendFrom;
29use core::{fmt, ops};
30use validation::{DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX};
31
32/// Maximum number of bytes on the value stack.
33pub const DEFAULT_VALUE_STACK_LIMIT: usize = 1024 * 1024;
34
35/// Maximum number of levels on the call stack.
36pub const DEFAULT_CALL_STACK_LIMIT: usize = 64 * 1024;
37
38/// This is a wrapper around u64 to allow us to treat runtime values as a tag-free `u64`
39/// (where if the runtime value is <64 bits the upper bits are 0). This is safe, since
40/// all of the possible runtime values are valid to create from 64 defined bits, so if
41/// types don't line up we get a logic error (which will ideally be caught by the wasm
42/// spec tests) and not undefined behaviour.
43///
44/// At the boundary between the interpreter and the outside world we convert to the public
45/// `Value` type, which can then be matched on. We can create a `Value` from
46/// a `ValueInternal` only when the type is statically known, which it always is
47/// at these boundaries.
48#[derive(Copy, Clone, Debug, PartialEq, Default)]
49#[repr(transparent)]
50struct ValueInternal(pub u64);
51
52impl ValueInternal {
53    pub fn with_type(self, ty: ValueType) -> RuntimeValue {
54        match ty {
55            ValueType::I32 => RuntimeValue::I32(<_>::from_value_internal(self)),
56            ValueType::I64 => RuntimeValue::I64(<_>::from_value_internal(self)),
57            ValueType::F32 => RuntimeValue::F32(<_>::from_value_internal(self)),
58            ValueType::F64 => RuntimeValue::F64(<_>::from_value_internal(self)),
59        }
60    }
61}
62
63trait FromValueInternal
64where
65    Self: Sized,
66{
67    fn from_value_internal(val: ValueInternal) -> Self;
68}
69
70macro_rules! impl_from_value_internal {
71	($($t:ty),*) =>	{
72		$(
73			impl FromValueInternal for $t {
74				fn from_value_internal(
75					ValueInternal(val): ValueInternal,
76				) -> Self {
77					val	as _
78				}
79			}
80
81			impl From<$t> for ValueInternal {
82				fn from(other: $t) -> Self {
83					ValueInternal(other as _)
84				}
85			}
86		)*
87	};
88}
89
90macro_rules! impl_from_value_internal_float	{
91	($($t:ty),*) =>	{
92		$(
93			impl FromValueInternal for $t {
94				fn from_value_internal(
95					ValueInternal(val): ValueInternal,
96				) -> Self {
97					<$t>::from_bits(val	as _)
98				}
99			}
100
101			impl From<$t> for ValueInternal {
102				fn from(other: $t) -> Self {
103					ValueInternal(other.to_bits() as	_)
104				}
105			}
106		)*
107	};
108}
109
110impl_from_value_internal!(i8, u8, i16, u16, i32, u32, i64, u64);
111impl_from_value_internal_float!(f32, f64, F32, F64);
112
113impl From<bool> for ValueInternal {
114    fn from(other: bool) -> Self {
115        (if other { 1 } else { 0 }).into()
116    }
117}
118
119impl FromValueInternal for bool {
120    fn from_value_internal(ValueInternal(val): ValueInternal) -> Self {
121        val != 0
122    }
123}
124
125impl From<RuntimeValue> for ValueInternal {
126    fn from(other: RuntimeValue) -> Self {
127        match other {
128            RuntimeValue::I32(val) => val.into(),
129            RuntimeValue::I64(val) => val.into(),
130            RuntimeValue::F32(val) => val.into(),
131            RuntimeValue::F64(val) => val.into(),
132        }
133    }
134}
135
136/// Interpreter action to execute after executing instruction.
137pub enum InstructionOutcome {
138    /// Continue with next instruction.
139    RunNextInstruction,
140    /// Branch to an instruction at the given position.
141    Branch(isa::Target),
142    /// Execute function call.
143    ExecuteCall(FuncRef),
144    /// Return from current function block.
145    Return(isa::DropKeep),
146}
147
148#[derive(PartialEq, Eq)]
149/// Function execution state, related to pause and resume.
150pub enum InterpreterState {
151    /// The interpreter has been created, but has not been executed.
152    Initialized,
153    /// The interpreter has started execution, and cannot be called again if it exits normally, or no Host traps happened.
154    Started,
155    /// The interpreter has been executed, and returned a Host trap. It can resume execution by providing back a return
156    /// value.
157    Resumable(Option<ValueType>),
158}
159
160impl InterpreterState {
161    pub fn is_resumable(&self) -> bool {
162        matches!(self, InterpreterState::Resumable(_))
163    }
164}
165
166/// Function run result.
167enum RunResult {
168    /// Function has returned.
169    Return,
170    /// Function is calling other function.
171    NestedCall(FuncRef),
172}
173
174/// Function interpreter.
175pub struct Interpreter {
176    value_stack: ValueStack,
177    call_stack: CallStack,
178    return_type: Option<ValueType>,
179    state: InterpreterState,
180    scratch: Vec<RuntimeValue>,
181}
182
183impl Interpreter {
184    pub fn new(
185        func: &FuncRef,
186        args: &[RuntimeValue],
187        mut stack_recycler: Option<&mut StackRecycler>,
188    ) -> Result<Interpreter, Trap> {
189        let mut value_stack = StackRecycler::recreate_value_stack(&mut stack_recycler);
190        for &arg in args {
191            let arg = arg.into();
192            value_stack.push(arg).map_err(
193                // There is not enough space for pushing initial arguments.
194                // Weird, but bail out anyway.
195                |_| Trap::from(TrapCode::StackOverflow),
196            )?;
197        }
198
199        let mut call_stack = StackRecycler::recreate_call_stack(&mut stack_recycler);
200        let initial_frame = FunctionContext::new(func.clone());
201        call_stack.push(initial_frame);
202
203        let return_type = func.signature().return_type();
204
205        Ok(Interpreter {
206            value_stack,
207            call_stack,
208            return_type,
209            state: InterpreterState::Initialized,
210            scratch: Vec::new(),
211        })
212    }
213
214    pub fn state(&self) -> &InterpreterState {
215        &self.state
216    }
217
218    pub fn start_execution<'a, E: Externals + 'a>(
219        &mut self,
220        externals: &'a mut E,
221    ) -> Result<Option<RuntimeValue>, Trap> {
222        // Ensure that the VM has not been executed. This is checked in `FuncInvocation::start_execution`.
223        assert!(self.state == InterpreterState::Initialized);
224
225        self.state = InterpreterState::Started;
226        self.run_interpreter_loop(externals)?;
227
228        let opt_return_value = self
229            .return_type
230            .map(|vt| self.value_stack.pop().with_type(vt));
231
232        // Ensure that stack is empty after the execution. This is guaranteed by the validation properties.
233        assert!(self.value_stack.len() == 0);
234
235        Ok(opt_return_value)
236    }
237
238    pub fn resume_execution<'a, E: Externals + 'a>(
239        &mut self,
240        return_val: Option<RuntimeValue>,
241        externals: &'a mut E,
242    ) -> Result<Option<RuntimeValue>, Trap> {
243        use core::mem::swap;
244
245        // Ensure that the VM is resumable. This is checked in `FuncInvocation::resume_execution`.
246        assert!(self.state.is_resumable());
247
248        let mut resumable_state = InterpreterState::Started;
249        swap(&mut self.state, &mut resumable_state);
250
251        if let Some(return_val) = return_val {
252            self.value_stack
253                .push(return_val.into())
254                .map_err(Trap::from)?;
255        }
256
257        self.run_interpreter_loop(externals)?;
258
259        let opt_return_value = self
260            .return_type
261            .map(|vt| self.value_stack.pop().with_type(vt));
262
263        // Ensure that stack is empty after the execution. This is guaranteed by the validation properties.
264        assert!(self.value_stack.len() == 0);
265
266        Ok(opt_return_value)
267    }
268
269    fn run_interpreter_loop<'a, E: Externals + 'a>(
270        &mut self,
271        externals: &'a mut E,
272    ) -> Result<(), Trap> {
273        loop {
274            let mut function_context = self.call_stack.pop().expect(
275                "on loop entry - not empty; on loop continue - checking for emptiness; qed",
276            );
277            let function_ref = function_context.function.clone();
278            let function_body = function_ref
279				.body()
280				.expect(
281					"Host functions checked in function_return below; Internal functions always have a body; qed"
282				);
283
284            if !function_context.is_initialized() {
285                // Initialize stack frame for the function call.
286                function_context.initialize(&function_body.locals, &mut self.value_stack)?;
287            }
288
289            let function_return = self
290                .do_run_function(&mut function_context, &function_body.code)
291                .map_err(Trap::from)?;
292
293            match function_return {
294                RunResult::Return => {
295                    if self.call_stack.is_empty() {
296                        // This was the last frame in the call stack. This means we
297                        // are done executing.
298                        return Ok(());
299                    }
300                }
301                RunResult::NestedCall(nested_func) => {
302                    if self.call_stack.is_full() {
303                        return Err(TrapCode::StackOverflow.into());
304                    }
305
306                    match *nested_func.as_internal() {
307                        FuncInstanceInternal::Internal { .. } => {
308                            let nested_context = FunctionContext::new(nested_func.clone());
309                            self.call_stack.push(function_context);
310                            self.call_stack.push(nested_context);
311                        }
312                        FuncInstanceInternal::Host { ref signature, .. } => {
313                            prepare_function_args(
314                                signature,
315                                &mut self.value_stack,
316                                &mut self.scratch,
317                            );
318                            // We push the function context first. If the VM is not resumable, it does no harm. If it is, we then save the context here.
319                            self.call_stack.push(function_context);
320
321                            let return_val = match FuncInstance::invoke(
322                                &nested_func,
323                                &self.scratch,
324                                externals,
325                            ) {
326                                Ok(val) => val,
327                                Err(trap) => {
328                                    if trap.is_host() {
329                                        self.state = InterpreterState::Resumable(
330                                            nested_func.signature().return_type(),
331                                        );
332                                    }
333                                    return Err(trap);
334                                }
335                            };
336
337                            // Check if `return_val` matches the signature.
338                            let value_ty = return_val.as_ref().map(|val| val.value_type());
339                            let expected_ty = nested_func.signature().return_type();
340                            if value_ty != expected_ty {
341                                return Err(TrapCode::UnexpectedSignature.into());
342                            }
343
344                            if let Some(return_val) = return_val {
345                                self.value_stack
346                                    .push(return_val.into())
347                                    .map_err(Trap::from)?;
348                            }
349                        }
350                    }
351                }
352            }
353        }
354    }
355
356    fn do_run_function(
357        &mut self,
358        function_context: &mut FunctionContext,
359        instructions: &isa::Instructions,
360    ) -> Result<RunResult, TrapCode> {
361        let mut iter = instructions.iterate_from(function_context.position);
362
363        loop {
364            let instruction = iter.next().expect(
365                "Ran out of instructions, this should be impossible \
366                 since validation ensures that we either have an explicit \
367                 return or an implicit block `end`.",
368            );
369
370            match self.run_instruction(function_context, &instruction)? {
371                InstructionOutcome::RunNextInstruction => {}
372                InstructionOutcome::Branch(target) => {
373                    iter = instructions.iterate_from(target.dst_pc);
374                    self.value_stack.drop_keep(target.drop_keep);
375                }
376                InstructionOutcome::ExecuteCall(func_ref) => {
377                    function_context.position = iter.position();
378                    return Ok(RunResult::NestedCall(func_ref));
379                }
380                InstructionOutcome::Return(drop_keep) => {
381                    self.value_stack.drop_keep(drop_keep);
382                    break;
383                }
384            }
385        }
386
387        Ok(RunResult::Return)
388    }
389
390    #[inline(always)]
391    fn run_instruction(
392        &mut self,
393        context: &mut FunctionContext,
394        instruction: &isa::Instruction,
395    ) -> Result<InstructionOutcome, TrapCode> {
396        match instruction {
397            isa::Instruction::Unreachable => self.run_unreachable(context),
398
399            isa::Instruction::Br(target) => self.run_br(context, *target),
400            isa::Instruction::BrIfEqz(target) => self.run_br_eqz(*target),
401            isa::Instruction::BrIfNez(target) => self.run_br_nez(*target),
402            isa::Instruction::BrTable(targets) => self.run_br_table(*targets),
403            isa::Instruction::Return(drop_keep) => self.run_return(*drop_keep),
404
405            isa::Instruction::Call(index) => self.run_call(context, *index),
406            isa::Instruction::CallIndirect(index) => self.run_call_indirect(context, *index),
407
408            isa::Instruction::Drop => self.run_drop(),
409            isa::Instruction::Select => self.run_select(),
410
411            isa::Instruction::GetLocal(depth) => self.run_get_local(*depth),
412            isa::Instruction::SetLocal(depth) => self.run_set_local(*depth),
413            isa::Instruction::TeeLocal(depth) => self.run_tee_local(*depth),
414            isa::Instruction::GetGlobal(index) => self.run_get_global(context, *index),
415            isa::Instruction::SetGlobal(index) => self.run_set_global(context, *index),
416
417            isa::Instruction::I32Load(offset) => self.run_load::<i32>(context, *offset),
418            isa::Instruction::I64Load(offset) => self.run_load::<i64>(context, *offset),
419            isa::Instruction::F32Load(offset) => self.run_load::<F32>(context, *offset),
420            isa::Instruction::F64Load(offset) => self.run_load::<F64>(context, *offset),
421            isa::Instruction::I32Load8S(offset) => {
422                self.run_load_extend::<i8, i32>(context, *offset)
423            }
424            isa::Instruction::I32Load8U(offset) => {
425                self.run_load_extend::<u8, i32>(context, *offset)
426            }
427            isa::Instruction::I32Load16S(offset) => {
428                self.run_load_extend::<i16, i32>(context, *offset)
429            }
430            isa::Instruction::I32Load16U(offset) => {
431                self.run_load_extend::<u16, i32>(context, *offset)
432            }
433            isa::Instruction::I64Load8S(offset) => {
434                self.run_load_extend::<i8, i64>(context, *offset)
435            }
436            isa::Instruction::I64Load8U(offset) => {
437                self.run_load_extend::<u8, i64>(context, *offset)
438            }
439            isa::Instruction::I64Load16S(offset) => {
440                self.run_load_extend::<i16, i64>(context, *offset)
441            }
442            isa::Instruction::I64Load16U(offset) => {
443                self.run_load_extend::<u16, i64>(context, *offset)
444            }
445            isa::Instruction::I64Load32S(offset) => {
446                self.run_load_extend::<i32, i64>(context, *offset)
447            }
448            isa::Instruction::I64Load32U(offset) => {
449                self.run_load_extend::<u32, i64>(context, *offset)
450            }
451
452            isa::Instruction::I32Store(offset) => self.run_store::<i32>(context, *offset),
453            isa::Instruction::I64Store(offset) => self.run_store::<i64>(context, *offset),
454            isa::Instruction::F32Store(offset) => self.run_store::<F32>(context, *offset),
455            isa::Instruction::F64Store(offset) => self.run_store::<F64>(context, *offset),
456            isa::Instruction::I32Store8(offset) => self.run_store_wrap::<i32, i8>(context, *offset),
457            isa::Instruction::I32Store16(offset) => {
458                self.run_store_wrap::<i32, i16>(context, *offset)
459            }
460            isa::Instruction::I64Store8(offset) => self.run_store_wrap::<i64, i8>(context, *offset),
461            isa::Instruction::I64Store16(offset) => {
462                self.run_store_wrap::<i64, i16>(context, *offset)
463            }
464            isa::Instruction::I64Store32(offset) => {
465                self.run_store_wrap::<i64, i32>(context, *offset)
466            }
467
468            isa::Instruction::CurrentMemory => self.run_current_memory(context),
469            isa::Instruction::GrowMemory => self.run_grow_memory(context),
470
471            isa::Instruction::I32Const(val) => self.run_const((*val).into()),
472            isa::Instruction::I64Const(val) => self.run_const((*val).into()),
473            isa::Instruction::F32Const(val) => self.run_const((*val).into()),
474            isa::Instruction::F64Const(val) => self.run_const((*val).into()),
475
476            isa::Instruction::I32Eqz => self.run_eqz::<i32>(),
477            isa::Instruction::I32Eq => self.run_eq::<i32>(),
478            isa::Instruction::I32Ne => self.run_ne::<i32>(),
479            isa::Instruction::I32LtS => self.run_lt::<i32>(),
480            isa::Instruction::I32LtU => self.run_lt::<u32>(),
481            isa::Instruction::I32GtS => self.run_gt::<i32>(),
482            isa::Instruction::I32GtU => self.run_gt::<u32>(),
483            isa::Instruction::I32LeS => self.run_lte::<i32>(),
484            isa::Instruction::I32LeU => self.run_lte::<u32>(),
485            isa::Instruction::I32GeS => self.run_gte::<i32>(),
486            isa::Instruction::I32GeU => self.run_gte::<u32>(),
487
488            isa::Instruction::I64Eqz => self.run_eqz::<i64>(),
489            isa::Instruction::I64Eq => self.run_eq::<i64>(),
490            isa::Instruction::I64Ne => self.run_ne::<i64>(),
491            isa::Instruction::I64LtS => self.run_lt::<i64>(),
492            isa::Instruction::I64LtU => self.run_lt::<u64>(),
493            isa::Instruction::I64GtS => self.run_gt::<i64>(),
494            isa::Instruction::I64GtU => self.run_gt::<u64>(),
495            isa::Instruction::I64LeS => self.run_lte::<i64>(),
496            isa::Instruction::I64LeU => self.run_lte::<u64>(),
497            isa::Instruction::I64GeS => self.run_gte::<i64>(),
498            isa::Instruction::I64GeU => self.run_gte::<u64>(),
499
500            isa::Instruction::F32Eq => self.run_eq::<F32>(),
501            isa::Instruction::F32Ne => self.run_ne::<F32>(),
502            isa::Instruction::F32Lt => self.run_lt::<F32>(),
503            isa::Instruction::F32Gt => self.run_gt::<F32>(),
504            isa::Instruction::F32Le => self.run_lte::<F32>(),
505            isa::Instruction::F32Ge => self.run_gte::<F32>(),
506
507            isa::Instruction::F64Eq => self.run_eq::<F64>(),
508            isa::Instruction::F64Ne => self.run_ne::<F64>(),
509            isa::Instruction::F64Lt => self.run_lt::<F64>(),
510            isa::Instruction::F64Gt => self.run_gt::<F64>(),
511            isa::Instruction::F64Le => self.run_lte::<F64>(),
512            isa::Instruction::F64Ge => self.run_gte::<F64>(),
513
514            isa::Instruction::I32Clz => self.run_clz::<i32>(),
515            isa::Instruction::I32Ctz => self.run_ctz::<i32>(),
516            isa::Instruction::I32Popcnt => self.run_popcnt::<i32>(),
517            isa::Instruction::I32Add => self.run_add::<i32>(),
518            isa::Instruction::I32Sub => self.run_sub::<i32>(),
519            isa::Instruction::I32Mul => self.run_mul::<i32>(),
520            isa::Instruction::I32DivS => self.run_div::<i32, i32>(),
521            isa::Instruction::I32DivU => self.run_div::<i32, u32>(),
522            isa::Instruction::I32RemS => self.run_rem::<i32, i32>(),
523            isa::Instruction::I32RemU => self.run_rem::<i32, u32>(),
524            isa::Instruction::I32And => self.run_and::<i32>(),
525            isa::Instruction::I32Or => self.run_or::<i32>(),
526            isa::Instruction::I32Xor => self.run_xor::<i32>(),
527            isa::Instruction::I32Shl => self.run_shl::<i32>(0x1F),
528            isa::Instruction::I32ShrS => self.run_shr::<i32, i32>(0x1F),
529            isa::Instruction::I32ShrU => self.run_shr::<i32, u32>(0x1F),
530            isa::Instruction::I32Rotl => self.run_rotl::<i32>(),
531            isa::Instruction::I32Rotr => self.run_rotr::<i32>(),
532
533            isa::Instruction::I64Clz => self.run_clz::<i64>(),
534            isa::Instruction::I64Ctz => self.run_ctz::<i64>(),
535            isa::Instruction::I64Popcnt => self.run_popcnt::<i64>(),
536            isa::Instruction::I64Add => self.run_add::<i64>(),
537            isa::Instruction::I64Sub => self.run_sub::<i64>(),
538            isa::Instruction::I64Mul => self.run_mul::<i64>(),
539            isa::Instruction::I64DivS => self.run_div::<i64, i64>(),
540            isa::Instruction::I64DivU => self.run_div::<i64, u64>(),
541            isa::Instruction::I64RemS => self.run_rem::<i64, i64>(),
542            isa::Instruction::I64RemU => self.run_rem::<i64, u64>(),
543            isa::Instruction::I64And => self.run_and::<i64>(),
544            isa::Instruction::I64Or => self.run_or::<i64>(),
545            isa::Instruction::I64Xor => self.run_xor::<i64>(),
546            isa::Instruction::I64Shl => self.run_shl::<i64>(0x3F),
547            isa::Instruction::I64ShrS => self.run_shr::<i64, i64>(0x3F),
548            isa::Instruction::I64ShrU => self.run_shr::<i64, u64>(0x3F),
549            isa::Instruction::I64Rotl => self.run_rotl::<i64>(),
550            isa::Instruction::I64Rotr => self.run_rotr::<i64>(),
551
552            isa::Instruction::F32Abs => self.run_abs::<F32>(),
553            isa::Instruction::F32Neg => self.run_neg::<F32>(),
554            isa::Instruction::F32Ceil => self.run_ceil::<F32>(),
555            isa::Instruction::F32Floor => self.run_floor::<F32>(),
556            isa::Instruction::F32Trunc => self.run_trunc::<F32>(),
557            isa::Instruction::F32Nearest => self.run_nearest::<F32>(),
558            isa::Instruction::F32Sqrt => self.run_sqrt::<F32>(),
559            isa::Instruction::F32Add => self.run_add::<F32>(),
560            isa::Instruction::F32Sub => self.run_sub::<F32>(),
561            isa::Instruction::F32Mul => self.run_mul::<F32>(),
562            isa::Instruction::F32Div => self.run_div::<F32, F32>(),
563            isa::Instruction::F32Min => self.run_min::<F32>(),
564            isa::Instruction::F32Max => self.run_max::<F32>(),
565            isa::Instruction::F32Copysign => self.run_copysign::<F32>(),
566
567            isa::Instruction::F64Abs => self.run_abs::<F64>(),
568            isa::Instruction::F64Neg => self.run_neg::<F64>(),
569            isa::Instruction::F64Ceil => self.run_ceil::<F64>(),
570            isa::Instruction::F64Floor => self.run_floor::<F64>(),
571            isa::Instruction::F64Trunc => self.run_trunc::<F64>(),
572            isa::Instruction::F64Nearest => self.run_nearest::<F64>(),
573            isa::Instruction::F64Sqrt => self.run_sqrt::<F64>(),
574            isa::Instruction::F64Add => self.run_add::<F64>(),
575            isa::Instruction::F64Sub => self.run_sub::<F64>(),
576            isa::Instruction::F64Mul => self.run_mul::<F64>(),
577            isa::Instruction::F64Div => self.run_div::<F64, F64>(),
578            isa::Instruction::F64Min => self.run_min::<F64>(),
579            isa::Instruction::F64Max => self.run_max::<F64>(),
580            isa::Instruction::F64Copysign => self.run_copysign::<F64>(),
581
582            isa::Instruction::I32WrapI64 => self.run_wrap::<i64, i32>(),
583            isa::Instruction::I32TruncSF32 => self.run_trunc_to_int::<F32, i32, i32>(),
584            isa::Instruction::I32TruncUF32 => self.run_trunc_to_int::<F32, u32, i32>(),
585            isa::Instruction::I32TruncSF64 => self.run_trunc_to_int::<F64, i32, i32>(),
586            isa::Instruction::I32TruncUF64 => self.run_trunc_to_int::<F64, u32, i32>(),
587            isa::Instruction::I64ExtendSI32 => self.run_extend::<i32, i64, i64>(),
588            isa::Instruction::I64ExtendUI32 => self.run_extend::<u32, u64, i64>(),
589            isa::Instruction::I64TruncSF32 => self.run_trunc_to_int::<F32, i64, i64>(),
590            isa::Instruction::I64TruncUF32 => self.run_trunc_to_int::<F32, u64, i64>(),
591            isa::Instruction::I64TruncSF64 => self.run_trunc_to_int::<F64, i64, i64>(),
592            isa::Instruction::I64TruncUF64 => self.run_trunc_to_int::<F64, u64, i64>(),
593            isa::Instruction::F32ConvertSI32 => self.run_extend::<i32, F32, F32>(),
594            isa::Instruction::F32ConvertUI32 => self.run_extend::<u32, F32, F32>(),
595            isa::Instruction::F32ConvertSI64 => self.run_wrap::<i64, F32>(),
596            isa::Instruction::F32ConvertUI64 => self.run_wrap::<u64, F32>(),
597            isa::Instruction::F32DemoteF64 => self.run_wrap::<F64, F32>(),
598            isa::Instruction::F64ConvertSI32 => self.run_extend::<i32, F64, F64>(),
599            isa::Instruction::F64ConvertUI32 => self.run_extend::<u32, F64, F64>(),
600            isa::Instruction::F64ConvertSI64 => self.run_extend::<i64, F64, F64>(),
601            isa::Instruction::F64ConvertUI64 => self.run_extend::<u64, F64, F64>(),
602            isa::Instruction::F64PromoteF32 => self.run_extend::<F32, F64, F64>(),
603
604            isa::Instruction::I32ReinterpretF32 => self.run_reinterpret::<F32, i32>(),
605            isa::Instruction::I64ReinterpretF64 => self.run_reinterpret::<F64, i64>(),
606            isa::Instruction::F32ReinterpretI32 => self.run_reinterpret::<i32, F32>(),
607            isa::Instruction::F64ReinterpretI64 => self.run_reinterpret::<i64, F64>(),
608
609            #[cfg(feature = "sign_ext")]
610            isa::Instruction::I32Extend8S => self.run_iextend::<i8, i32>(),
611            #[cfg(feature = "sign_ext")]
612            isa::Instruction::I32Extend16S => self.run_iextend::<i16, i32>(),
613            #[cfg(feature = "sign_ext")]
614            isa::Instruction::I64Extend8S => self.run_iextend::<i8, i64>(),
615            #[cfg(feature = "sign_ext")]
616            isa::Instruction::I64Extend16S => self.run_iextend::<i16, i64>(),
617            #[cfg(feature = "sign_ext")]
618            isa::Instruction::I64Extend32S => self.run_iextend::<i32, i64>(),
619        }
620    }
621
622    fn run_unreachable(
623        &mut self,
624        _context: &mut FunctionContext,
625    ) -> Result<InstructionOutcome, TrapCode> {
626        Err(TrapCode::Unreachable)
627    }
628
629    fn run_br(
630        &mut self,
631        _context: &mut FunctionContext,
632        target: isa::Target,
633    ) -> Result<InstructionOutcome, TrapCode> {
634        Ok(InstructionOutcome::Branch(target))
635    }
636
637    fn run_br_nez(&mut self, target: isa::Target) -> Result<InstructionOutcome, TrapCode> {
638        let condition = self.value_stack.pop_as();
639        if condition {
640            Ok(InstructionOutcome::Branch(target))
641        } else {
642            Ok(InstructionOutcome::RunNextInstruction)
643        }
644    }
645
646    fn run_br_eqz(&mut self, target: isa::Target) -> Result<InstructionOutcome, TrapCode> {
647        let condition = self.value_stack.pop_as();
648        if condition {
649            Ok(InstructionOutcome::RunNextInstruction)
650        } else {
651            Ok(InstructionOutcome::Branch(target))
652        }
653    }
654
655    fn run_br_table(&mut self, targets: isa::BrTargets) -> Result<InstructionOutcome, TrapCode> {
656        let index: u32 = self.value_stack.pop_as();
657
658        let dst = targets.get(index);
659
660        Ok(InstructionOutcome::Branch(dst))
661    }
662
663    fn run_return(&mut self, drop_keep: isa::DropKeep) -> Result<InstructionOutcome, TrapCode> {
664        Ok(InstructionOutcome::Return(drop_keep))
665    }
666
667    fn run_call(
668        &mut self,
669        context: &mut FunctionContext,
670        func_idx: u32,
671    ) -> Result<InstructionOutcome, TrapCode> {
672        let func = context
673            .module()
674            .func_by_index(func_idx)
675            .expect("Due to validation func should exists");
676        Ok(InstructionOutcome::ExecuteCall(func))
677    }
678
679    fn run_call_indirect(
680        &mut self,
681        context: &mut FunctionContext,
682        signature_idx: u32,
683    ) -> Result<InstructionOutcome, TrapCode> {
684        let table_func_idx: u32 = self.value_stack.pop_as();
685        let table = context
686            .module()
687            .table_by_index(DEFAULT_TABLE_INDEX)
688            .expect("Due to validation table should exists");
689        let func_ref = table
690            .get(table_func_idx)
691            .map_err(|_| TrapCode::TableAccessOutOfBounds)?
692            .ok_or(TrapCode::ElemUninitialized)?;
693
694        {
695            let actual_function_type = func_ref.signature();
696            let required_function_type = context
697                .module()
698                .signature_by_index(signature_idx)
699                .expect("Due to validation type should exists");
700
701            if &*required_function_type != actual_function_type {
702                return Err(TrapCode::UnexpectedSignature);
703            }
704        }
705
706        Ok(InstructionOutcome::ExecuteCall(func_ref))
707    }
708
709    fn run_drop(&mut self) -> Result<InstructionOutcome, TrapCode> {
710        let _ = self.value_stack.pop();
711        Ok(InstructionOutcome::RunNextInstruction)
712    }
713
714    fn run_select(&mut self) -> Result<InstructionOutcome, TrapCode> {
715        let (left, mid, right) = self.value_stack.pop_triple();
716
717        let condition = <_>::from_value_internal(right);
718        let val = if condition { left } else { mid };
719        self.value_stack.push(val)?;
720        Ok(InstructionOutcome::RunNextInstruction)
721    }
722
723    fn run_get_local(&mut self, index: u32) -> Result<InstructionOutcome, TrapCode> {
724        let val = *self.value_stack.pick_mut(index as usize);
725        self.value_stack.push(val)?;
726        Ok(InstructionOutcome::RunNextInstruction)
727    }
728
729    fn run_set_local(&mut self, index: u32) -> Result<InstructionOutcome, TrapCode> {
730        let val = self.value_stack.pop();
731        *self.value_stack.pick_mut(index as usize) = val;
732        Ok(InstructionOutcome::RunNextInstruction)
733    }
734
735    fn run_tee_local(&mut self, index: u32) -> Result<InstructionOutcome, TrapCode> {
736        let val = *self.value_stack.top();
737        *self.value_stack.pick_mut(index as usize) = val;
738        Ok(InstructionOutcome::RunNextInstruction)
739    }
740
741    fn run_get_global(
742        &mut self,
743        context: &mut FunctionContext,
744        index: u32,
745    ) -> Result<InstructionOutcome, TrapCode> {
746        let global = context
747            .module()
748            .global_by_index(index)
749            .expect("Due to validation global should exists");
750        let val = global.get();
751        self.value_stack.push(val.into())?;
752        Ok(InstructionOutcome::RunNextInstruction)
753    }
754
755    fn run_set_global(
756        &mut self,
757        context: &mut FunctionContext,
758        index: u32,
759    ) -> Result<InstructionOutcome, TrapCode> {
760        let val = self.value_stack.pop();
761        let global = context
762            .module()
763            .global_by_index(index)
764            .expect("Due to validation global should exists");
765        global
766            .set(val.with_type(global.value_type()))
767            .expect("Due to validation set to a global should succeed");
768        Ok(InstructionOutcome::RunNextInstruction)
769    }
770
771    fn run_load<T>(
772        &mut self,
773        context: &mut FunctionContext,
774        offset: u32,
775    ) -> Result<InstructionOutcome, TrapCode>
776    where
777        ValueInternal: From<T>,
778        T: LittleEndianConvert,
779    {
780        let raw_address = self.value_stack.pop_as();
781        let address = effective_address(offset, raw_address)?;
782        let m = context
783            .memory()
784            .expect("Due to validation memory should exists");
785        let n: T = m
786            .get_value(address)
787            .map_err(|_| TrapCode::MemoryAccessOutOfBounds)?;
788        self.value_stack.push(n.into())?;
789        Ok(InstructionOutcome::RunNextInstruction)
790    }
791
792    fn run_load_extend<T, U>(
793        &mut self,
794        context: &mut FunctionContext,
795        offset: u32,
796    ) -> Result<InstructionOutcome, TrapCode>
797    where
798        T: ExtendInto<U>,
799        ValueInternal: From<U>,
800        T: LittleEndianConvert,
801    {
802        let raw_address = self.value_stack.pop_as();
803        let address = effective_address(offset, raw_address)?;
804        let m = context
805            .memory()
806            .expect("Due to validation memory should exists");
807        let v: T = m
808            .get_value(address)
809            .map_err(|_| TrapCode::MemoryAccessOutOfBounds)?;
810        let stack_value: U = v.extend_into();
811        self.value_stack
812            .push(stack_value.into())
813            .map_err(Into::into)
814            .map(|_| InstructionOutcome::RunNextInstruction)
815    }
816
817    fn run_store<T>(
818        &mut self,
819        context: &mut FunctionContext,
820        offset: u32,
821    ) -> Result<InstructionOutcome, TrapCode>
822    where
823        T: FromValueInternal,
824        T: LittleEndianConvert,
825    {
826        let stack_value = self.value_stack.pop_as::<T>();
827        let raw_address = self.value_stack.pop_as::<u32>();
828        let address = effective_address(offset, raw_address)?;
829
830        let m = context
831            .memory()
832            .expect("Due to validation memory should exists");
833        m.set_value(address, stack_value)
834            .map_err(|_| TrapCode::MemoryAccessOutOfBounds)?;
835        Ok(InstructionOutcome::RunNextInstruction)
836    }
837
838    fn run_store_wrap<T, U>(
839        &mut self,
840        context: &mut FunctionContext,
841        offset: u32,
842    ) -> Result<InstructionOutcome, TrapCode>
843    where
844        T: FromValueInternal,
845        T: WrapInto<U>,
846        U: LittleEndianConvert,
847    {
848        let stack_value: T = <_>::from_value_internal(self.value_stack.pop());
849        let stack_value = stack_value.wrap_into();
850        let raw_address = self.value_stack.pop_as::<u32>();
851        let address = effective_address(offset, raw_address)?;
852        let m = context
853            .memory()
854            .expect("Due to validation memory should exists");
855        m.set_value(address, stack_value)
856            .map_err(|_| TrapCode::MemoryAccessOutOfBounds)?;
857        Ok(InstructionOutcome::RunNextInstruction)
858    }
859
860    fn run_current_memory(
861        &mut self,
862        context: &mut FunctionContext,
863    ) -> Result<InstructionOutcome, TrapCode> {
864        let m = context
865            .memory()
866            .expect("Due to validation memory should exists");
867        let s = m.current_size().0;
868        self.value_stack.push(ValueInternal(s as _))?;
869        Ok(InstructionOutcome::RunNextInstruction)
870    }
871
872    fn run_grow_memory(
873        &mut self,
874        context: &mut FunctionContext,
875    ) -> Result<InstructionOutcome, TrapCode> {
876        let pages: u32 = self.value_stack.pop_as();
877        let m = context
878            .memory()
879            .expect("Due to validation memory should exists");
880        let m = match m.grow(Pages(pages as usize)) {
881            Ok(Pages(new_size)) => new_size as u32,
882            Err(_) => u32::MAX, // Returns -1 (or 0xFFFFFFFF) in case of error.
883        };
884        self.value_stack.push(ValueInternal(m as _))?;
885        Ok(InstructionOutcome::RunNextInstruction)
886    }
887
888    fn run_const(&mut self, val: RuntimeValue) -> Result<InstructionOutcome, TrapCode> {
889        self.value_stack
890            .push(val.into())
891            .map_err(Into::into)
892            .map(|_| InstructionOutcome::RunNextInstruction)
893    }
894
895    fn run_relop<T, F>(&mut self, f: F) -> Result<InstructionOutcome, TrapCode>
896    where
897        T: FromValueInternal,
898        F: FnOnce(T, T) -> bool,
899    {
900        let (left, right) = self.value_stack.pop_pair_as::<T>();
901        let v = if f(left, right) {
902            ValueInternal(1)
903        } else {
904            ValueInternal(0)
905        };
906        self.value_stack.push(v)?;
907        Ok(InstructionOutcome::RunNextInstruction)
908    }
909
910    fn run_eqz<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
911    where
912        T: FromValueInternal,
913        T: PartialEq<T> + Default,
914    {
915        let v = self.value_stack.pop_as::<T>();
916        let v = ValueInternal(if v == Default::default() { 1 } else { 0 });
917        self.value_stack.push(v)?;
918        Ok(InstructionOutcome::RunNextInstruction)
919    }
920
921    fn run_eq<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
922    where
923        T: FromValueInternal + PartialEq<T>,
924    {
925        self.run_relop(|left: T, right: T| left == right)
926    }
927
928    fn run_ne<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
929    where
930        T: FromValueInternal + PartialEq<T>,
931    {
932        self.run_relop(|left: T, right: T| left != right)
933    }
934
935    fn run_lt<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
936    where
937        T: FromValueInternal + PartialOrd<T>,
938    {
939        self.run_relop(|left: T, right: T| left < right)
940    }
941
942    fn run_gt<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
943    where
944        T: FromValueInternal + PartialOrd<T>,
945    {
946        self.run_relop(|left: T, right: T| left > right)
947    }
948
949    fn run_lte<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
950    where
951        T: FromValueInternal + PartialOrd<T>,
952    {
953        self.run_relop(|left: T, right: T| left <= right)
954    }
955
956    fn run_gte<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
957    where
958        T: FromValueInternal + PartialOrd<T>,
959    {
960        self.run_relop(|left: T, right: T| left >= right)
961    }
962
963    fn run_unop<T, U, F>(&mut self, f: F) -> Result<InstructionOutcome, TrapCode>
964    where
965        F: FnOnce(T) -> U,
966        T: FromValueInternal,
967        ValueInternal: From<U>,
968    {
969        let v = self.value_stack.pop_as::<T>();
970        let v = f(v);
971        self.value_stack.push(v.into())?;
972        Ok(InstructionOutcome::RunNextInstruction)
973    }
974
975    fn run_clz<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
976    where
977        ValueInternal: From<T>,
978        T: Integer<T> + FromValueInternal,
979    {
980        self.run_unop(|v: T| v.leading_zeros())
981    }
982
983    fn run_ctz<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
984    where
985        ValueInternal: From<T>,
986        T: Integer<T> + FromValueInternal,
987    {
988        self.run_unop(|v: T| v.trailing_zeros())
989    }
990
991    fn run_popcnt<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
992    where
993        ValueInternal: From<T>,
994        T: Integer<T> + FromValueInternal,
995    {
996        self.run_unop(|v: T| v.count_ones())
997    }
998
999    fn run_add<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1000    where
1001        ValueInternal: From<T>,
1002        T: ArithmeticOps<T> + FromValueInternal,
1003    {
1004        let (left, right) = self.value_stack.pop_pair_as::<T>();
1005        let v = left.add(right);
1006        self.value_stack.push(v.into())?;
1007        Ok(InstructionOutcome::RunNextInstruction)
1008    }
1009
1010    fn run_sub<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1011    where
1012        ValueInternal: From<T>,
1013        T: ArithmeticOps<T> + FromValueInternal,
1014    {
1015        let (left, right) = self.value_stack.pop_pair_as::<T>();
1016        let v = left.sub(right);
1017        self.value_stack.push(v.into())?;
1018        Ok(InstructionOutcome::RunNextInstruction)
1019    }
1020
1021    fn run_mul<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1022    where
1023        ValueInternal: From<T>,
1024        T: ArithmeticOps<T> + FromValueInternal,
1025    {
1026        let (left, right) = self.value_stack.pop_pair_as::<T>();
1027        let v = left.mul(right);
1028        self.value_stack.push(v.into())?;
1029        Ok(InstructionOutcome::RunNextInstruction)
1030    }
1031
1032    fn run_div<T, U>(&mut self) -> Result<InstructionOutcome, TrapCode>
1033    where
1034        ValueInternal: From<T>,
1035        T: TransmuteInto<U> + FromValueInternal,
1036        U: ArithmeticOps<U> + TransmuteInto<T>,
1037    {
1038        let (left, right) = self.value_stack.pop_pair_as::<T>();
1039        let (left, right) = (left.transmute_into(), right.transmute_into());
1040        let v = left.div(right)?;
1041        let v = v.transmute_into();
1042        self.value_stack.push(v.into())?;
1043        Ok(InstructionOutcome::RunNextInstruction)
1044    }
1045
1046    fn run_rem<T, U>(&mut self) -> Result<InstructionOutcome, TrapCode>
1047    where
1048        ValueInternal: From<T>,
1049        T: TransmuteInto<U> + FromValueInternal,
1050        U: Integer<U> + TransmuteInto<T>,
1051    {
1052        let (left, right) = self.value_stack.pop_pair_as::<T>();
1053        let (left, right) = (left.transmute_into(), right.transmute_into());
1054        let v = left.rem(right)?;
1055        let v = v.transmute_into();
1056        self.value_stack.push(v.into())?;
1057        Ok(InstructionOutcome::RunNextInstruction)
1058    }
1059
1060    fn run_and<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1061    where
1062        ValueInternal: From<<T as ops::BitAnd>::Output>,
1063        T: ops::BitAnd<T> + FromValueInternal,
1064    {
1065        let (left, right) = self.value_stack.pop_pair_as::<T>();
1066        let v = left.bitand(right);
1067        self.value_stack.push(v.into())?;
1068        Ok(InstructionOutcome::RunNextInstruction)
1069    }
1070
1071    fn run_or<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1072    where
1073        ValueInternal: From<<T as ops::BitOr>::Output>,
1074        T: ops::BitOr<T> + FromValueInternal,
1075    {
1076        let (left, right) = self.value_stack.pop_pair_as::<T>();
1077        let v = left.bitor(right);
1078        self.value_stack.push(v.into())?;
1079        Ok(InstructionOutcome::RunNextInstruction)
1080    }
1081
1082    fn run_xor<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1083    where
1084        ValueInternal: From<<T as ops::BitXor>::Output>,
1085        T: ops::BitXor<T> + FromValueInternal,
1086    {
1087        let (left, right) = self.value_stack.pop_pair_as::<T>();
1088        let v = left.bitxor(right);
1089        self.value_stack.push(v.into())?;
1090        Ok(InstructionOutcome::RunNextInstruction)
1091    }
1092
1093    fn run_shl<T>(&mut self, mask: T) -> Result<InstructionOutcome, TrapCode>
1094    where
1095        ValueInternal: From<<T as ops::Shl<T>>::Output>,
1096        T: ops::Shl<T> + ops::BitAnd<T, Output = T> + FromValueInternal,
1097    {
1098        let (left, right) = self.value_stack.pop_pair_as::<T>();
1099        let v = left.shl(right & mask);
1100        self.value_stack.push(v.into())?;
1101        Ok(InstructionOutcome::RunNextInstruction)
1102    }
1103
1104    fn run_shr<T, U>(&mut self, mask: U) -> Result<InstructionOutcome, TrapCode>
1105    where
1106        ValueInternal: From<T>,
1107        T: TransmuteInto<U> + FromValueInternal,
1108        U: ops::Shr<U> + ops::BitAnd<U, Output = U>,
1109        <U as ops::Shr<U>>::Output: TransmuteInto<T>,
1110    {
1111        let (left, right) = self.value_stack.pop_pair_as::<T>();
1112        let (left, right) = (left.transmute_into(), right.transmute_into());
1113        let v = left.shr(right & mask);
1114        let v = v.transmute_into();
1115        self.value_stack.push(v.into())?;
1116        Ok(InstructionOutcome::RunNextInstruction)
1117    }
1118
1119    fn run_rotl<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1120    where
1121        ValueInternal: From<T>,
1122        T: Integer<T> + FromValueInternal,
1123    {
1124        let (left, right) = self.value_stack.pop_pair_as::<T>();
1125        let v = left.rotl(right);
1126        self.value_stack.push(v.into())?;
1127        Ok(InstructionOutcome::RunNextInstruction)
1128    }
1129
1130    fn run_rotr<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1131    where
1132        ValueInternal: From<T>,
1133        T: Integer<T> + FromValueInternal,
1134    {
1135        let (left, right) = self.value_stack.pop_pair_as::<T>();
1136        let v = left.rotr(right);
1137        self.value_stack.push(v.into())?;
1138        Ok(InstructionOutcome::RunNextInstruction)
1139    }
1140
1141    fn run_abs<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1142    where
1143        ValueInternal: From<T>,
1144        T: Float<T> + FromValueInternal,
1145    {
1146        self.run_unop(|v: T| v.abs())
1147    }
1148
1149    fn run_neg<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1150    where
1151        ValueInternal: From<<T as ops::Neg>::Output>,
1152        T: ops::Neg + FromValueInternal,
1153    {
1154        self.run_unop(|v: T| v.neg())
1155    }
1156
1157    fn run_ceil<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1158    where
1159        ValueInternal: From<T>,
1160        T: Float<T> + FromValueInternal,
1161    {
1162        self.run_unop(|v: T| v.ceil())
1163    }
1164
1165    fn run_floor<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1166    where
1167        ValueInternal: From<T>,
1168        T: Float<T> + FromValueInternal,
1169    {
1170        self.run_unop(|v: T| v.floor())
1171    }
1172
1173    fn run_trunc<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1174    where
1175        ValueInternal: From<T>,
1176        T: Float<T> + FromValueInternal,
1177    {
1178        self.run_unop(|v: T| v.trunc())
1179    }
1180
1181    fn run_nearest<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1182    where
1183        ValueInternal: From<T>,
1184        T: Float<T> + FromValueInternal,
1185    {
1186        self.run_unop(|v: T| v.nearest())
1187    }
1188
1189    fn run_sqrt<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1190    where
1191        ValueInternal: From<T>,
1192        T: Float<T> + FromValueInternal,
1193    {
1194        self.run_unop(|v: T| v.sqrt())
1195    }
1196
1197    fn run_min<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1198    where
1199        ValueInternal: From<T>,
1200        T: Float<T> + FromValueInternal,
1201    {
1202        let (left, right) = self.value_stack.pop_pair_as::<T>();
1203        let v = left.min(right);
1204        self.value_stack.push(v.into())?;
1205        Ok(InstructionOutcome::RunNextInstruction)
1206    }
1207
1208    fn run_max<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1209    where
1210        ValueInternal: From<T>,
1211        T: Float<T> + FromValueInternal,
1212    {
1213        let (left, right) = self.value_stack.pop_pair_as::<T>();
1214        let v = left.max(right);
1215        self.value_stack.push(v.into())?;
1216        Ok(InstructionOutcome::RunNextInstruction)
1217    }
1218
1219    fn run_copysign<T>(&mut self) -> Result<InstructionOutcome, TrapCode>
1220    where
1221        ValueInternal: From<T>,
1222        T: Float<T> + FromValueInternal,
1223    {
1224        let (left, right) = self.value_stack.pop_pair_as::<T>();
1225        let v = left.copysign(right);
1226        self.value_stack.push(v.into())?;
1227        Ok(InstructionOutcome::RunNextInstruction)
1228    }
1229
1230    fn run_wrap<T, U>(&mut self) -> Result<InstructionOutcome, TrapCode>
1231    where
1232        ValueInternal: From<U>,
1233        T: WrapInto<U> + FromValueInternal,
1234    {
1235        self.run_unop(|v: T| v.wrap_into())
1236    }
1237
1238    fn run_trunc_to_int<T, U, V>(&mut self) -> Result<InstructionOutcome, TrapCode>
1239    where
1240        ValueInternal: From<V>,
1241        T: TryTruncateInto<U, TrapCode> + FromValueInternal,
1242        U: TransmuteInto<V>,
1243    {
1244        let v = self.value_stack.pop_as::<T>();
1245
1246        v.try_truncate_into()
1247            .map(|v| v.transmute_into())
1248            .map(|v| self.value_stack.push(v.into()))
1249            .map(|_| InstructionOutcome::RunNextInstruction)
1250    }
1251
1252    fn run_extend<T, U, V>(&mut self) -> Result<InstructionOutcome, TrapCode>
1253    where
1254        ValueInternal: From<V>,
1255        T: ExtendInto<U> + FromValueInternal,
1256        U: TransmuteInto<V>,
1257    {
1258        let v = self.value_stack.pop_as::<T>();
1259
1260        let v = v.extend_into().transmute_into();
1261        self.value_stack.push(v.into())?;
1262
1263        Ok(InstructionOutcome::RunNextInstruction)
1264    }
1265
1266    fn run_reinterpret<T, U>(&mut self) -> Result<InstructionOutcome, TrapCode>
1267    where
1268        ValueInternal: From<U>,
1269        T: FromValueInternal,
1270        T: TransmuteInto<U>,
1271    {
1272        let v = self.value_stack.pop_as::<T>();
1273
1274        let v = v.transmute_into();
1275        self.value_stack.push(v.into())?;
1276
1277        Ok(InstructionOutcome::RunNextInstruction)
1278    }
1279
1280    #[cfg(feature = "sign_ext")]
1281    fn run_iextend<T, U>(&mut self) -> Result<InstructionOutcome, TrapCode>
1282    where
1283        ValueInternal: From<U>,
1284        U: SignExtendFrom<T> + FromValueInternal,
1285    {
1286        let v = self.value_stack.pop_as::<U>();
1287
1288        let v = v.sign_extend_from();
1289        self.value_stack.push(v.into())?;
1290
1291        Ok(InstructionOutcome::RunNextInstruction)
1292    }
1293}
1294
1295/// Function execution context.
1296struct FunctionContext {
1297    /// Is context initialized.
1298    pub is_initialized: bool,
1299    /// Internal function reference.
1300    pub function: FuncRef,
1301    pub module: ModuleRef,
1302    pub memory: Option<MemoryRef>,
1303    /// Current instruction position.
1304    pub position: u32,
1305}
1306
1307impl FunctionContext {
1308    pub fn new(function: FuncRef) -> Self {
1309        let module = match function.as_internal() {
1310			FuncInstanceInternal::Internal { module, .. } => module.upgrade().expect("module deallocated"),
1311			FuncInstanceInternal::Host { .. } => panic!("Host functions can't be called as internally defined functions; Thus FunctionContext can be created only with internally defined functions; qed"),
1312		};
1313        let memory = module.memory_by_index(DEFAULT_MEMORY_INDEX);
1314        FunctionContext {
1315            is_initialized: false,
1316            function,
1317            module: ModuleRef(module),
1318            memory,
1319            position: 0,
1320        }
1321    }
1322
1323    pub fn is_initialized(&self) -> bool {
1324        self.is_initialized
1325    }
1326
1327    pub fn initialize(
1328        &mut self,
1329        locals: &[Local],
1330        value_stack: &mut ValueStack,
1331    ) -> Result<(), TrapCode> {
1332        debug_assert!(!self.is_initialized);
1333
1334        let num_locals = locals.iter().map(|l| l.count() as usize).sum();
1335
1336        value_stack.extend(num_locals)?;
1337
1338        self.is_initialized = true;
1339        Ok(())
1340    }
1341
1342    pub fn module(&self) -> ModuleRef {
1343        self.module.clone()
1344    }
1345
1346    pub fn memory(&self) -> Option<&MemoryRef> {
1347        self.memory.as_ref()
1348    }
1349}
1350
1351impl fmt::Debug for FunctionContext {
1352    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1353        write!(f, "FunctionContext")
1354    }
1355}
1356
1357fn effective_address(address: u32, offset: u32) -> Result<u32, TrapCode> {
1358    match offset.checked_add(address) {
1359        None => Err(TrapCode::MemoryAccessOutOfBounds),
1360        Some(address) => Ok(address),
1361    }
1362}
1363
1364fn prepare_function_args(
1365    signature: &Signature,
1366    caller_stack: &mut ValueStack,
1367    host_args: &mut Vec<RuntimeValue>,
1368) {
1369    let req_args = signature.params();
1370    let len_args = req_args.len();
1371    let stack_args = caller_stack.pop_slice(len_args);
1372    assert_eq!(len_args, stack_args.len());
1373    host_args.clear();
1374    let prepared_args = req_args
1375        .iter()
1376        .zip(stack_args)
1377        .map(|(req_arg, stack_arg)| stack_arg.with_type(*req_arg));
1378    host_args.extend(prepared_args);
1379}
1380
1381pub fn check_function_args(signature: &Signature, args: &[RuntimeValue]) -> Result<(), Trap> {
1382    if signature.params().len() != args.len() {
1383        return Err(TrapCode::UnexpectedSignature.into());
1384    }
1385
1386    if signature
1387        .params()
1388        .iter()
1389        .zip(args.iter().map(|param_value| param_value.value_type()))
1390        .any(|(expected_type, actual_type)| &actual_type != expected_type)
1391    {
1392        return Err(TrapCode::UnexpectedSignature.into());
1393    }
1394
1395    Ok(())
1396}
1397
1398struct ValueStack {
1399    buf: Box<[ValueInternal]>,
1400    /// Index of the first free place in the stack.
1401    sp: usize,
1402}
1403
1404impl core::fmt::Debug for ValueStack {
1405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1406        f.debug_struct("ValueStack")
1407            .field("entries", &&self.buf[..self.sp])
1408            .field("stack_ptr", &self.sp)
1409            .finish()
1410    }
1411}
1412
1413impl ValueStack {
1414    #[inline]
1415    fn drop_keep(&mut self, drop_keep: isa::DropKeep) {
1416        if drop_keep.keep == isa::Keep::Single {
1417            let top = *self.top();
1418            *self.pick_mut(drop_keep.drop as usize + 1) = top;
1419        }
1420
1421        let cur_stack_len = self.len();
1422        self.sp = cur_stack_len - drop_keep.drop as usize;
1423    }
1424
1425    #[inline]
1426    fn pop_as<T>(&mut self) -> T
1427    where
1428        T: FromValueInternal,
1429    {
1430        let value = self.pop();
1431
1432        T::from_value_internal(value)
1433    }
1434
1435    #[inline]
1436    fn pop_pair_as<T>(&mut self) -> (T, T)
1437    where
1438        T: FromValueInternal,
1439    {
1440        let right = self.pop_as();
1441        let left = self.pop_as();
1442        (left, right)
1443    }
1444
1445    #[inline]
1446    fn pop_triple(&mut self) -> (ValueInternal, ValueInternal, ValueInternal) {
1447        let right = self.pop();
1448        let mid = self.pop();
1449        let left = self.pop();
1450        (left, mid, right)
1451    }
1452
1453    #[inline]
1454    fn top(&self) -> &ValueInternal {
1455        self.pick(1)
1456    }
1457
1458    fn pick(&self, depth: usize) -> &ValueInternal {
1459        &self.buf[self.sp - depth]
1460    }
1461
1462    #[inline]
1463    fn pick_mut(&mut self, depth: usize) -> &mut ValueInternal {
1464        &mut self.buf[self.sp - depth]
1465    }
1466
1467    #[inline]
1468    fn pop(&mut self) -> ValueInternal {
1469        self.sp -= 1;
1470        self.buf[self.sp]
1471    }
1472
1473    #[inline]
1474    fn push(&mut self, value: ValueInternal) -> Result<(), TrapCode> {
1475        let cell = self.buf.get_mut(self.sp).ok_or(TrapCode::StackOverflow)?;
1476        *cell = value;
1477        self.sp += 1;
1478        Ok(())
1479    }
1480
1481    fn extend(&mut self, len: usize) -> Result<(), TrapCode> {
1482        let cells = self
1483            .buf
1484            .get_mut(self.sp..self.sp + len)
1485            .ok_or(TrapCode::StackOverflow)?;
1486        for cell in cells {
1487            *cell = Default::default();
1488        }
1489        self.sp += len;
1490        Ok(())
1491    }
1492
1493    #[inline]
1494    fn len(&self) -> usize {
1495        self.sp
1496    }
1497
1498    /// Pops the last `depth` stack entries and returns them as slice.
1499    ///
1500    /// Stack entries are returned in the order in which they got pushed
1501    /// onto the value stack.
1502    ///
1503    /// # Panics
1504    ///
1505    /// If the value stack does not have at least `depth` stack entries.
1506    pub fn pop_slice(&mut self, depth: usize) -> &[ValueInternal] {
1507        self.sp -= depth;
1508        let start = self.sp;
1509        let end = self.sp + depth;
1510        &self.buf[start..end]
1511    }
1512}
1513
1514struct CallStack {
1515    buf: Vec<FunctionContext>,
1516    limit: usize,
1517}
1518
1519impl CallStack {
1520    fn push(&mut self, ctx: FunctionContext) {
1521        self.buf.push(ctx);
1522    }
1523
1524    fn pop(&mut self) -> Option<FunctionContext> {
1525        self.buf.pop()
1526    }
1527
1528    fn is_empty(&self) -> bool {
1529        self.buf.is_empty()
1530    }
1531
1532    fn is_full(&self) -> bool {
1533        self.buf.len() + 1 >= self.limit
1534    }
1535}
1536
1537/// Used to recycle stacks instead of allocating them repeatedly.
1538pub struct StackRecycler {
1539    value_stack_buf: Option<Box<[ValueInternal]>>,
1540    value_stack_limit: usize,
1541    call_stack_buf: Option<Vec<FunctionContext>>,
1542    call_stack_limit: usize,
1543}
1544
1545impl StackRecycler {
1546    /// Limit stacks created by this recycler to
1547    /// - `value_stack_limit` bytes for values and
1548    /// - `call_stack_limit` levels for calls.
1549    pub fn with_limits(value_stack_limit: usize, call_stack_limit: usize) -> Self {
1550        Self {
1551            value_stack_buf: None,
1552            value_stack_limit,
1553            call_stack_buf: None,
1554            call_stack_limit,
1555        }
1556    }
1557
1558    /// Clears any values left on the stack to avoid
1559    /// leaking them to future export invocations.
1560    ///
1561    /// This is a secondary defense to prevent modules from
1562    /// exploiting faulty stack handling in the interpreter.
1563    ///
1564    /// Do note that there are additional channels that
1565    /// can leak information into an untrusted module.
1566    pub fn clear(&mut self) {
1567        if let Some(buf) = &mut self.value_stack_buf {
1568            for cell in buf.iter_mut() {
1569                *cell = ValueInternal(0);
1570            }
1571        }
1572    }
1573
1574    fn recreate_value_stack(this: &mut Option<&mut Self>) -> ValueStack {
1575        let limit = this
1576            .as_ref()
1577            .map_or(DEFAULT_VALUE_STACK_LIMIT, |this| this.value_stack_limit)
1578            / ::core::mem::size_of::<ValueInternal>();
1579
1580        let buf = this
1581            .as_mut()
1582            .and_then(|this| this.value_stack_buf.take())
1583            .unwrap_or_else(|| {
1584                let mut buf = Vec::new();
1585                buf.reserve_exact(limit);
1586                buf.resize(limit, ValueInternal(0));
1587                buf.into_boxed_slice()
1588            });
1589
1590        ValueStack { buf, sp: 0 }
1591    }
1592
1593    fn recreate_call_stack(this: &mut Option<&mut Self>) -> CallStack {
1594        let limit = this
1595            .as_ref()
1596            .map_or(DEFAULT_CALL_STACK_LIMIT, |this| this.call_stack_limit);
1597
1598        let buf = this
1599            .as_mut()
1600            .and_then(|this| this.call_stack_buf.take())
1601            .unwrap_or_default();
1602
1603        CallStack { buf, limit }
1604    }
1605
1606    pub(crate) fn recycle(&mut self, mut interpreter: Interpreter) {
1607        interpreter.call_stack.buf.clear();
1608
1609        self.value_stack_buf = Some(interpreter.value_stack.buf);
1610        self.call_stack_buf = Some(interpreter.call_stack.buf);
1611    }
1612}
1613
1614impl Default for StackRecycler {
1615    fn default() -> Self {
1616        Self::with_limits(DEFAULT_VALUE_STACK_LIMIT, DEFAULT_CALL_STACK_LIMIT)
1617    }
1618}