Skip to main content

cranelift_interpreter/
interpreter.rs

1//! Cranelift IR interpreter.
2//!
3//! This module partially contains the logic for interpreting Cranelift IR.
4
5use crate::address::{Address, AddressFunctionEntry, AddressRegion, AddressSize};
6use crate::environment::{FuncIndex, FunctionStore};
7use crate::frame::Frame;
8use crate::instruction::DfgInstructionContext;
9use crate::state::{InterpreterFunctionRef, MemoryError, State};
10use crate::step::{ControlFlow, CraneliftTrap, StepError, step};
11use crate::value::{DataValueExt, ValueError};
12use cranelift_codegen::data_value::DataValue;
13use cranelift_codegen::ir::{
14    ArgumentPurpose, Block, Endianness, ExternalName, FuncRef, Function, GlobalValue,
15    GlobalValueData, LibCall, MemFlagsData, StackSlot, Type,
16};
17use log::trace;
18use smallvec::SmallVec;
19use std::fmt::Debug;
20use std::iter;
21use thiserror::Error;
22
23/// The Cranelift interpreter; this contains some high-level functions to control the interpreter's
24/// flow. The interpreter state is defined separately (see [InterpreterState]) as the execution
25/// semantics for each Cranelift instruction (see [step]).
26pub struct Interpreter<'a> {
27    state: InterpreterState<'a>,
28    fuel: Option<u64>,
29}
30
31impl<'a> Interpreter<'a> {
32    pub fn new(state: InterpreterState<'a>) -> Self {
33        Self { state, fuel: None }
34    }
35
36    /// The `fuel` mechanism sets a number of instructions that
37    /// the interpreter can execute before stopping. If this
38    /// value is `None` (the default), no limit is imposed.
39    pub fn with_fuel(self, fuel: Option<u64>) -> Self {
40        Self { fuel, ..self }
41    }
42
43    /// Call a function by name; this is a helpful proxy for [Interpreter::call_by_index].
44    pub fn call_by_name(
45        &mut self,
46        func_name: &str,
47        arguments: &[DataValue],
48    ) -> Result<ControlFlow<'a>, InterpreterError> {
49        let index = self
50            .state
51            .functions
52            .index_of(func_name)
53            .ok_or_else(|| InterpreterError::UnknownFunctionName(func_name.to_string()))?;
54        self.call_by_index(index, arguments)
55    }
56
57    /// Call a function by its index in the [FunctionStore]; this is a proxy for
58    /// `Interpreter::call`.
59    pub fn call_by_index(
60        &mut self,
61        index: FuncIndex,
62        arguments: &[DataValue],
63    ) -> Result<ControlFlow<'a>, InterpreterError> {
64        match self.state.functions.get_by_index(index) {
65            None => Err(InterpreterError::UnknownFunctionIndex(index)),
66            Some(func) => self.call(func, arguments),
67        }
68    }
69
70    /// Interpret a call to a [Function] given its [DataValue] arguments.
71    fn call(
72        &mut self,
73        function: &'a Function,
74        arguments: &[DataValue],
75    ) -> Result<ControlFlow<'a>, InterpreterError> {
76        trace!("Call: {}({:?})", function.name, arguments);
77        let first_block = function
78            .layout
79            .blocks()
80            .next()
81            .expect("to have a first block");
82        let parameters = function.dfg.block_params(first_block);
83        self.state.push_frame(function);
84        self.state
85            .current_frame_mut()
86            .set_all(parameters, arguments.to_vec());
87
88        self.block(first_block)
89    }
90
91    /// Interpret a [Block] in a [Function]. This drives the interpretation over sequences of
92    /// instructions, which may continue in other blocks, until the function returns.
93    fn block(&mut self, block: Block) -> Result<ControlFlow<'a>, InterpreterError> {
94        trace!("Block: {block}");
95        let function = self.state.current_frame_mut().function();
96        let layout = &function.layout;
97        let mut maybe_inst = layout.first_inst(block);
98        while let Some(inst) = maybe_inst {
99            if self.consume_fuel() == FuelResult::Stop {
100                return Err(InterpreterError::FuelExhausted);
101            }
102
103            let inst_context = DfgInstructionContext::new(inst, &function.dfg);
104            match step(&mut self.state, inst_context)? {
105                ControlFlow::Assign(values) => {
106                    self.state
107                        .current_frame_mut()
108                        .set_all(function.dfg.inst_results(inst), values.to_vec());
109                    maybe_inst = layout.next_inst(inst)
110                }
111                ControlFlow::Continue => maybe_inst = layout.next_inst(inst),
112                ControlFlow::ContinueAt(block, block_arguments) => {
113                    trace!("Block: {block}");
114                    self.state
115                        .current_frame_mut()
116                        .set_all(function.dfg.block_params(block), block_arguments.to_vec());
117                    maybe_inst = layout.first_inst(block)
118                }
119                ControlFlow::Call(called_function, arguments) => {
120                    match self.call(called_function, &arguments)? {
121                        ControlFlow::Return(rets) => {
122                            self.state
123                                .current_frame_mut()
124                                .set_all(function.dfg.inst_results(inst), rets.to_vec());
125                            maybe_inst = layout.next_inst(inst)
126                        }
127                        ControlFlow::Trap(trap) => return Ok(ControlFlow::Trap(trap)),
128                        cf => {
129                            panic!("invalid control flow after call: {cf:?}")
130                        }
131                    }
132                }
133                ControlFlow::ReturnCall(callee, args) => {
134                    self.state.pop_frame();
135
136                    return match self.call(callee, &args)? {
137                        ControlFlow::Return(rets) => Ok(ControlFlow::Return(rets)),
138                        ControlFlow::Trap(trap) => Ok(ControlFlow::Trap(trap)),
139                        cf => {
140                            panic!("invalid control flow after return_call: {cf:?}")
141                        }
142                    };
143                }
144                ControlFlow::Return(returned_values) => {
145                    self.state.pop_frame();
146                    return Ok(ControlFlow::Return(returned_values));
147                }
148                ControlFlow::Trap(trap) => return Ok(ControlFlow::Trap(trap)),
149            }
150        }
151        Err(InterpreterError::Unreachable)
152    }
153
154    fn consume_fuel(&mut self) -> FuelResult {
155        match self.fuel {
156            Some(0) => FuelResult::Stop,
157            Some(ref mut n) => {
158                *n -= 1;
159                FuelResult::Continue
160            }
161
162            // We do not have fuel enabled, so unconditionally continue
163            None => FuelResult::Continue,
164        }
165    }
166}
167
168#[derive(Debug, PartialEq, Clone)]
169/// The result of consuming fuel. Signals if the caller should stop or continue.
170pub enum FuelResult {
171    /// We still have `fuel` available and should continue execution.
172    Continue,
173    /// The available `fuel` has been exhausted, we should stop now.
174    Stop,
175}
176
177/// The ways interpretation can fail.
178#[derive(Error, Debug)]
179pub enum InterpreterError {
180    #[error("failed to interpret instruction")]
181    StepError(#[from] StepError),
182    #[error("reached an unreachable statement")]
183    Unreachable,
184    #[error("unknown function index (has it been added to the function store?): {0}")]
185    UnknownFunctionIndex(FuncIndex),
186    #[error("unknown function with name (has it been added to the function store?): {0}")]
187    UnknownFunctionName(String),
188    #[error("value error")]
189    ValueError(#[from] ValueError),
190    #[error("fuel exhausted")]
191    FuelExhausted,
192}
193
194pub type LibCallValues = SmallVec<[DataValue; 1]>;
195pub type LibCallHandler = fn(LibCall, LibCallValues) -> Result<LibCallValues, CraneliftTrap>;
196
197/// Maintains the [Interpreter]'s state, implementing the [State] trait.
198pub struct InterpreterState<'a> {
199    pub functions: FunctionStore<'a>,
200    pub libcall_handler: LibCallHandler,
201    pub frame_stack: Vec<Frame<'a>>,
202    /// Number of bytes from the bottom of the stack where the current frame's stack space is
203    pub frame_offset: usize,
204    pub stack: Vec<u8>,
205    pub pinned_reg: DataValue,
206    pub native_endianness: Endianness,
207}
208
209impl Default for InterpreterState<'_> {
210    fn default() -> Self {
211        let native_endianness = if cfg!(target_endian = "little") {
212            Endianness::Little
213        } else {
214            Endianness::Big
215        };
216        Self {
217            functions: FunctionStore::default(),
218            libcall_handler: |_, _| Err(CraneliftTrap::UnreachableCodeReached),
219            frame_stack: vec![],
220            frame_offset: 0,
221            stack: Vec::with_capacity(1024),
222            pinned_reg: DataValue::I64(0),
223            native_endianness,
224        }
225    }
226}
227
228impl<'a> InterpreterState<'a> {
229    pub fn with_function_store(self, functions: FunctionStore<'a>) -> Self {
230        Self { functions, ..self }
231    }
232
233    /// Registers a libcall handler
234    pub fn with_libcall_handler(mut self, handler: LibCallHandler) -> Self {
235        self.libcall_handler = handler;
236        self
237    }
238}
239
240impl<'a> State<'a> for InterpreterState<'a> {
241    fn get_function(&self, func_ref: FuncRef) -> Option<&'a Function> {
242        self.functions
243            .get_from_func_ref(func_ref, self.frame_stack.last().unwrap().function())
244    }
245    fn get_current_function(&self) -> &'a Function {
246        self.current_frame().function()
247    }
248
249    fn get_libcall_handler(&self) -> LibCallHandler {
250        self.libcall_handler
251    }
252
253    fn push_frame(&mut self, function: &'a Function) {
254        if let Some(frame) = self.frame_stack.iter().last() {
255            self.frame_offset += frame.function().fixed_stack_size() as usize;
256        }
257
258        // Grow the stack by the space necessary for this frame
259        self.stack
260            .extend(iter::repeat(0).take(function.fixed_stack_size() as usize));
261
262        self.frame_stack.push(Frame::new(function));
263    }
264    fn pop_frame(&mut self) {
265        if let Some(frame) = self.frame_stack.pop() {
266            // Shorten the stack after exiting the frame
267            self.stack
268                .truncate(self.stack.len() - frame.function().fixed_stack_size() as usize);
269
270            // Reset frame_offset to the start of this function
271            if let Some(frame) = self.frame_stack.iter().last() {
272                self.frame_offset -= frame.function().fixed_stack_size() as usize;
273            }
274        }
275    }
276
277    fn current_frame_mut(&mut self) -> &mut Frame<'a> {
278        let num_frames = self.frame_stack.len();
279        match num_frames {
280            0 => panic!("unable to retrieve the current frame because no frames were pushed"),
281            _ => &mut self.frame_stack[num_frames - 1],
282        }
283    }
284
285    fn current_frame(&self) -> &Frame<'a> {
286        let num_frames = self.frame_stack.len();
287        match num_frames {
288            0 => panic!("unable to retrieve the current frame because no frames were pushed"),
289            _ => &self.frame_stack[num_frames - 1],
290        }
291    }
292
293    fn stack_address(
294        &self,
295        size: AddressSize,
296        slot: StackSlot,
297        offset: u64,
298    ) -> Result<Address, MemoryError> {
299        let stack_slots = &self.get_current_function().sized_stack_slots;
300        let stack_slot = &stack_slots[slot];
301
302        // offset must be `0 <= Offset < sizeof(SS)`
303        if offset >= stack_slot.size as u64 {
304            return Err(MemoryError::InvalidOffset {
305                offset,
306                max: stack_slot.size as u64,
307            });
308        }
309
310        // Calculate the offset from the current frame to the requested stack slot
311        let slot_offset: u64 = stack_slots
312            .keys()
313            .filter(|k| k < &slot)
314            .map(|k| stack_slots[k].size as u64)
315            .sum();
316
317        let final_offset = self.frame_offset as u64 + slot_offset + offset;
318        Address::from_parts(size, AddressRegion::Stack, 0, final_offset)
319    }
320
321    fn checked_load(
322        &self,
323        addr: Address,
324        ty: Type,
325        mem_flags: MemFlagsData,
326    ) -> Result<DataValue, MemoryError> {
327        let load_size = ty.bytes() as usize;
328        let addr_start = addr.offset as usize;
329        let addr_end = addr_start + load_size;
330
331        let src = match addr.region {
332            AddressRegion::Stack => {
333                if addr_end > self.stack.len() {
334                    return Err(MemoryError::OutOfBoundsLoad {
335                        addr,
336                        load_size,
337                        mem_flags,
338                    });
339                }
340
341                &self.stack[addr_start..addr_end]
342            }
343            _ => unimplemented!(),
344        };
345
346        // Aligned flag is set and address is not aligned for the given type
347        if mem_flags.aligned() && addr_start % load_size != 0 {
348            return Err(MemoryError::MisalignedLoad { addr, load_size });
349        }
350
351        Ok(match mem_flags.endianness(self.native_endianness) {
352            Endianness::Big => DataValue::read_from_slice_be(src, ty),
353            Endianness::Little => DataValue::read_from_slice_le(src, ty),
354        })
355    }
356
357    fn checked_store(
358        &mut self,
359        addr: Address,
360        v: DataValue,
361        mem_flags: MemFlagsData,
362    ) -> Result<(), MemoryError> {
363        let store_size = v.ty().bytes() as usize;
364        let addr_start = addr.offset as usize;
365        let addr_end = addr_start + store_size;
366
367        let dst = match addr.region {
368            AddressRegion::Stack => {
369                if addr_end > self.stack.len() {
370                    return Err(MemoryError::OutOfBoundsStore {
371                        addr,
372                        store_size,
373                        mem_flags,
374                    });
375                }
376
377                &mut self.stack[addr_start..addr_end]
378            }
379            _ => unimplemented!(),
380        };
381
382        // Aligned flag is set and address is not aligned for the given type
383        if mem_flags.aligned() && addr_start % store_size != 0 {
384            return Err(MemoryError::MisalignedStore { addr, store_size });
385        }
386
387        Ok(match mem_flags.endianness(self.native_endianness) {
388            Endianness::Big => v.write_to_slice_be(dst),
389            Endianness::Little => v.write_to_slice_le(dst),
390        })
391    }
392
393    fn function_address(
394        &self,
395        size: AddressSize,
396        name: &ExternalName,
397    ) -> Result<Address, MemoryError> {
398        let curr_func = self.get_current_function();
399        let (entry, index) = match name {
400            ExternalName::User(username) => {
401                let ext_name = &curr_func.params.user_named_funcs()[*username];
402
403                // TODO: This is not optimal since we are looking up by string name
404                let index = self.functions.index_of(&ext_name.to_string()).unwrap();
405
406                (AddressFunctionEntry::UserFunction, index.as_u32())
407            }
408
409            ExternalName::TestCase(testname) => {
410                // TODO: This is not optimal since we are looking up by string name
411                let index = self.functions.index_of(&testname.to_string()).unwrap();
412
413                (AddressFunctionEntry::UserFunction, index.as_u32())
414            }
415            ExternalName::LibCall(libcall) => {
416                // We don't properly have a "libcall" store, but we can use `LibCall::all()`
417                // and index into that.
418                let index = LibCall::all_libcalls()
419                    .iter()
420                    .position(|lc| lc == libcall)
421                    .unwrap();
422
423                (AddressFunctionEntry::LibCall, index as u32)
424            }
425            _ => unimplemented!("function_address: {:?}", name),
426        };
427
428        Address::from_parts(size, AddressRegion::Function, entry as u64, index as u64)
429    }
430
431    fn get_function_from_address(&self, address: Address) -> Option<InterpreterFunctionRef<'a>> {
432        let index = address.offset as u32;
433        if address.region != AddressRegion::Function {
434            return None;
435        }
436
437        match AddressFunctionEntry::from(address.entry) {
438            AddressFunctionEntry::UserFunction => self
439                .functions
440                .get_by_index(FuncIndex::from_u32(index))
441                .map(InterpreterFunctionRef::from),
442
443            AddressFunctionEntry::LibCall => LibCall::all_libcalls()
444                .get(index as usize)
445                .copied()
446                .map(InterpreterFunctionRef::from),
447        }
448    }
449
450    /// Non-Recursively resolves a global value until its address is found
451    fn resolve_global_value(&self, gv: GlobalValue) -> Result<DataValue, MemoryError> {
452        // Resolving a Global Value is a "pointer" chasing operation that lends itself to
453        // using a recursive solution. However, resolving this in a recursive manner
454        // is a bad idea because its very easy to add a bunch of global values and
455        // blow up the call stack.
456        //
457        // Adding to the challenges of this, is that the operations possible with GlobalValues
458        // mean that we cannot use a simple loop to resolve each global value, we must keep
459        // a pending list of operations.
460
461        // These are the possible actions that we can perform
462        #[derive(Debug)]
463        enum ResolveAction {
464            Resolve(GlobalValue),
465            /// Perform an add on the current address
466            Add(DataValue),
467            /// Load From the current address and replace it with the loaded value
468            Load {
469                /// Offset added to the base pointer before doing the load.
470                offset: i32,
471
472                /// Type of the loaded value.
473                global_type: Type,
474            },
475        }
476
477        let func = self.get_current_function();
478
479        // We start with a sentinel value that will fail if we try to load / add to it
480        // without resolving the base GV First.
481        let mut current_val = DataValue::I8(0);
482        let mut action_stack = vec![ResolveAction::Resolve(gv)];
483
484        loop {
485            match action_stack.pop() {
486                Some(ResolveAction::Resolve(gv)) => match func.global_values[gv] {
487                    GlobalValueData::VMContext => {
488                        // Fetch the VMContext value from the values of the first block in the function
489                        let index = func
490                            .signature
491                            .params
492                            .iter()
493                            .enumerate()
494                            .find(|(_, p)| p.purpose == ArgumentPurpose::VMContext)
495                            .map(|(i, _)| i)
496                            // This should be validated by the verifier
497                            .expect("No VMCtx argument was found, but one is referenced");
498
499                        let first_block =
500                            func.layout.blocks().next().expect("to have a first block");
501                        let vmctx_value = func.dfg.block_params(first_block)[index];
502                        current_val = self.current_frame().get(vmctx_value).clone();
503                    }
504                    GlobalValueData::Load {
505                        base,
506                        offset,
507                        global_type,
508                        ..
509                    } => {
510                        action_stack.push(ResolveAction::Load {
511                            offset: offset.into(),
512                            global_type,
513                        });
514                        action_stack.push(ResolveAction::Resolve(base));
515                    }
516                    GlobalValueData::IAddImm {
517                        base,
518                        offset,
519                        global_type,
520                    } => {
521                        let offset: i64 = offset.into();
522                        let dv = DataValue::int(offset as i128, global_type)
523                            .map_err(|_| MemoryError::InvalidAddressType(global_type))?;
524                        action_stack.push(ResolveAction::Add(dv));
525                        action_stack.push(ResolveAction::Resolve(base));
526                    }
527                    GlobalValueData::Symbol { .. } => unimplemented!(),
528                    GlobalValueData::DynScaleTargetConst { .. } => unimplemented!(),
529                },
530                Some(ResolveAction::Add(dv)) => {
531                    current_val = current_val
532                        .add(dv.clone())
533                        .map_err(|_| MemoryError::InvalidAddress(dv))?;
534                }
535                Some(ResolveAction::Load {
536                    offset,
537                    global_type,
538                }) => {
539                    let mut addr = Address::try_from(current_val)?;
540                    let mem_flags = MemFlagsData::trusted();
541                    // We can forego bounds checking here since its performed in `checked_load`
542                    addr.offset += offset as u64;
543                    current_val = self.checked_load(addr, global_type, mem_flags)?;
544                }
545
546                // We are done resolving this, return the current value
547                None => return Ok(current_val),
548            }
549        }
550    }
551
552    fn get_pinned_reg(&self) -> DataValue {
553        self.pinned_reg.clone()
554    }
555
556    fn set_pinned_reg(&mut self, v: DataValue) {
557        self.pinned_reg = v;
558    }
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use crate::step::CraneliftTrap;
565    use cranelift_codegen::ir::TrapCode;
566    use cranelift_codegen::ir::immediates::Ieee32;
567    use cranelift_reader::parse_functions;
568    use smallvec::smallvec;
569
570    // Most interpreter tests should use the more ergonomic `test interpret` filetest but this
571    // unit test serves as a sanity check that the interpreter still works without all of the
572    // filetest infrastructure.
573    #[test]
574    fn sanity() {
575        let code = "function %test() -> i8 {
576        block0:
577            v0 = iconst.i32 1
578            v5 = iconst.i32 1
579            v1 = iadd v0, v5
580            v6 = iconst.i32 44
581            v2 = isub v6, v1  ; 44 - 2 == 42
582            v4 = iconst.i32 42
583            v3 = icmp eq v2, v4
584            return v3
585        }";
586
587        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
588        let mut env = FunctionStore::default();
589        env.add(func.name.to_string(), &func);
590        let state = InterpreterState::default().with_function_store(env);
591        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
592
593        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I8(1)]));
594    }
595
596    // We don't have a way to check for traps with the current filetest infrastructure
597    #[test]
598    fn udiv_by_zero_traps() {
599        let code = "function %test() -> i32 {
600        block0:
601            v0 = iconst.i32 1
602            v2 = iconst.i32 0
603            v1 = udiv v0, v2
604            return v1
605        }";
606
607        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
608        let mut env = FunctionStore::default();
609        env.add(func.name.to_string(), &func);
610        let state = InterpreterState::default().with_function_store(env);
611        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
612
613        assert_eq!(
614            trap,
615            ControlFlow::Trap(CraneliftTrap::User(TrapCode::INTEGER_DIVISION_BY_ZERO))
616        );
617    }
618
619    #[test]
620    fn sdiv_min_by_neg_one_traps_with_overflow() {
621        let code = "function %test() -> i8 {
622        block0:
623            v0 = iconst.i32 -2147483648
624            v2 = iconst.i32 -1
625            v1 = sdiv v0, v2
626            return v1
627        }";
628
629        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
630        let mut env = FunctionStore::default();
631        env.add(func.name.to_string(), &func);
632        let state = InterpreterState::default().with_function_store(env);
633        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
634
635        match result {
636            ControlFlow::Trap(CraneliftTrap::User(TrapCode::INTEGER_OVERFLOW)) => {}
637            _ => panic!("Unexpected ControlFlow: {result:?}"),
638        }
639    }
640
641    // This test verifies that functions can refer to each other using the function store. A double indirection is
642    // required, which is tricky to get right: a referenced function is a FuncRef when called but a FuncIndex inside the
643    // function store. This test would preferably be a CLIF filetest but the filetest infrastructure only looks at a
644    // single function at a time--we need more than one function in the store for this test.
645    #[test]
646    fn function_references() {
647        let code = "
648        function %child(i32) -> i32 {
649        block0(v0: i32):
650            v2 = iconst.i32 -1
651            v1 = iadd v0, v2
652            return v1
653        }
654
655        function %parent(i32) -> i32 {
656            fn42 = %child(i32) -> i32
657        block0(v0: i32):
658            v3 = iconst.i32 1
659            v1 = iadd v0, v3
660            v2 = call fn42(v1)
661            return v2
662        }";
663
664        let mut env = FunctionStore::default();
665        let funcs = parse_functions(code).unwrap().to_vec();
666        funcs.iter().for_each(|f| env.add(f.name.to_string(), f));
667
668        let state = InterpreterState::default().with_function_store(env);
669        let result = Interpreter::new(state)
670            .call_by_name("%parent", &[DataValue::I32(0)])
671            .unwrap();
672
673        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(0)]));
674    }
675
676    #[test]
677    fn fuel() {
678        let code = "function %test() -> i8 {
679        block0:
680            v0 = iconst.i32 1
681            v2 = iconst.i32 1
682            v1 = iadd v0, v2
683            return v1
684        }";
685
686        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
687        let mut env = FunctionStore::default();
688        env.add(func.name.to_string(), &func);
689
690        // The default interpreter should not enable the fuel mechanism
691        let state = InterpreterState::default().with_function_store(env.clone());
692        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
693
694        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(2)]));
695
696        // With 3 fuel, we should execute the two iconsts and the iadd, but not the return thus
697        // giving a fuel exhausted error
698        let state = InterpreterState::default().with_function_store(env.clone());
699        let result = Interpreter::new(state)
700            .with_fuel(Some(3))
701            .call_by_name("%test", &[]);
702        match result {
703            Err(InterpreterError::FuelExhausted) => {}
704            _ => panic!("Expected Err(FuelExhausted), but got {result:?}"),
705        }
706
707        // With 4 fuel, we should be able to execute the return instruction, and complete the test
708        let state = InterpreterState::default().with_function_store(env.clone());
709        let result = Interpreter::new(state)
710            .with_fuel(Some(4))
711            .call_by_name("%test", &[])
712            .unwrap();
713
714        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(2)]));
715    }
716
717    // Verifies that writing to the stack on a called function does not overwrite the parents
718    // stack slots.
719    #[test]
720    fn stack_slots_multi_functions() {
721        let code = "
722        function %callee(i64, i64) -> i64 {
723            ss0 = explicit_slot 8
724            ss1 = explicit_slot 8
725
726        block0(v0: i64, v1: i64):
727            v5 = stack_addr.i64 ss0
728            store.i64 v0, v5
729            v6 = stack_addr.i64 ss1
730            store.i64 v1, v6
731            v7 = stack_addr.i64 ss0
732            v2 = load.i64 v7
733            v8 = stack_addr.i64 ss1
734            v3 = load.i64 v8
735            v4 = iadd.i64 v2, v3
736            return v4
737        }
738
739        function %caller(i64, i64, i64, i64) -> i64 {
740            fn0 = %callee(i64, i64) -> i64
741            ss0 = explicit_slot 8
742            ss1 = explicit_slot 8
743
744        block0(v0: i64, v1: i64, v2: i64, v3: i64):
745            v9 = stack_addr.i64 ss0
746            store.i64 v0, v9
747            v10 = stack_addr.i64 ss1
748            store.i64 v1, v10
749
750            v4 = call fn0(v2, v3)
751
752            v11 = stack_addr.i64 ss0
753            v5 = load.i64 v11
754            v12 = stack_addr.i64 ss1
755            v6 = load.i64 v12
756
757            v7 = iadd.i64 v4, v5
758            v8 = iadd.i64 v7, v6
759
760            return v8
761        }";
762
763        let mut env = FunctionStore::default();
764        let funcs = parse_functions(code).unwrap().to_vec();
765        funcs.iter().for_each(|f| env.add(f.name.to_string(), f));
766
767        let state = InterpreterState::default().with_function_store(env);
768        let result = Interpreter::new(state)
769            .call_by_name(
770                "%caller",
771                &[
772                    DataValue::I64(3),
773                    DataValue::I64(5),
774                    DataValue::I64(7),
775                    DataValue::I64(11),
776                ],
777            )
778            .unwrap();
779
780        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I64(26)]))
781    }
782
783    #[test]
784    fn out_of_slot_write_traps() {
785        let code = "
786        function %stack_write() {
787            ss0 = explicit_slot 8
788
789        block0:
790            v0 = iconst.i64 10
791            v1 = stack_addr.i64 ss0+8
792            store.i64 v0, v1
793            return
794        }";
795
796        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
797        let mut env = FunctionStore::default();
798        env.add(func.name.to_string(), &func);
799        let state = InterpreterState::default().with_function_store(env);
800        let trap = Interpreter::new(state)
801            .call_by_name("%stack_write", &[])
802            .unwrap();
803
804        assert_eq!(
805            trap,
806            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
807        );
808    }
809
810    #[test]
811    fn partial_out_of_slot_write_traps() {
812        let code = "
813        function %stack_write() {
814            ss0 = explicit_slot 8
815
816        block0:
817            v0 = iconst.i64 10
818            v1 = stack_addr.i64 ss0+4
819            store.i64 v0, v1
820            return
821        }";
822
823        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
824        let mut env = FunctionStore::default();
825        env.add(func.name.to_string(), &func);
826        let state = InterpreterState::default().with_function_store(env);
827        let trap = Interpreter::new(state)
828            .call_by_name("%stack_write", &[])
829            .unwrap();
830
831        assert_eq!(
832            trap,
833            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
834        );
835    }
836
837    #[test]
838    fn out_of_slot_read_traps() {
839        let code = "
840        function %stack_load() {
841            ss0 = explicit_slot 8
842
843        block0:
844            v1 = stack_addr.i64 ss0+8
845            v0 = load.i64 v1
846            return
847        }";
848
849        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
850        let mut env = FunctionStore::default();
851        env.add(func.name.to_string(), &func);
852        let state = InterpreterState::default().with_function_store(env);
853        let trap = Interpreter::new(state)
854            .call_by_name("%stack_load", &[])
855            .unwrap();
856
857        assert_eq!(
858            trap,
859            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
860        );
861    }
862
863    #[test]
864    fn partial_out_of_slot_read_traps() {
865        let code = "
866        function %stack_load() {
867            ss0 = explicit_slot 8
868
869        block0:
870            v1 = stack_addr.i64 ss0+4
871            v0 = load.i64 v1
872            return
873        }";
874
875        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
876        let mut env = FunctionStore::default();
877        env.add(func.name.to_string(), &func);
878        let state = InterpreterState::default().with_function_store(env);
879        let trap = Interpreter::new(state)
880            .call_by_name("%stack_load", &[])
881            .unwrap();
882
883        assert_eq!(
884            trap,
885            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
886        );
887    }
888
889    #[test]
890    fn partial_out_of_slot_read_by_addr_traps() {
891        let code = "
892        function %stack_load() {
893            ss0 = explicit_slot 8
894
895        block0:
896            v0 = stack_addr.i64 ss0
897            v1 = iconst.i64 4
898            v2 = iadd.i64 v0, v1
899            v3 = load.i64 v2
900            return
901        }";
902
903        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
904        let mut env = FunctionStore::default();
905        env.add(func.name.to_string(), &func);
906        let state = InterpreterState::default().with_function_store(env);
907        let trap = Interpreter::new(state)
908            .call_by_name("%stack_load", &[])
909            .unwrap();
910
911        assert_eq!(
912            trap,
913            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
914        );
915    }
916
917    #[test]
918    fn partial_out_of_slot_write_by_addr_traps() {
919        let code = "
920        function %stack_store() {
921            ss0 = explicit_slot 8
922
923        block0:
924            v0 = stack_addr.i64 ss0
925            v1 = iconst.i64 4
926            v2 = iadd.i64 v0, v1
927            store.i64 v1, v2
928            return
929        }";
930
931        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
932        let mut env = FunctionStore::default();
933        env.add(func.name.to_string(), &func);
934        let state = InterpreterState::default().with_function_store(env);
935        let trap = Interpreter::new(state)
936            .call_by_name("%stack_store", &[])
937            .unwrap();
938
939        assert_eq!(
940            trap,
941            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
942        );
943    }
944
945    #[test]
946    fn srem_trap() {
947        let code = "function %test() -> i64 {
948        block0:
949            v0 = iconst.i64 0x8000_0000_0000_0000
950            v1 = iconst.i64 -1
951            v2 = srem.i64 v0, v1
952            return v2
953        }";
954
955        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
956        let mut env = FunctionStore::default();
957        env.add(func.name.to_string(), &func);
958        let state = InterpreterState::default().with_function_store(env);
959        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
960
961        assert_eq!(
962            trap,
963            ControlFlow::Trap(CraneliftTrap::User(TrapCode::INTEGER_OVERFLOW))
964        );
965    }
966
967    #[test]
968    fn libcall() {
969        let code = "function %test() -> i64 {
970            fn0 = colocated %CeilF32 (f32) -> f32 fast
971        block0:
972            v1 = f32const 0x0.5
973            v2 = call fn0(v1)
974            return v2
975        }";
976
977        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
978        let mut env = FunctionStore::default();
979        env.add(func.name.to_string(), &func);
980        let state = InterpreterState::default()
981            .with_function_store(env)
982            .with_libcall_handler(|libcall, args| {
983                Ok(smallvec![match (libcall, &args[..]) {
984                    (LibCall::CeilF32, [DataValue::F32(a)]) => DataValue::F32(a.ceil()),
985                    _ => panic!("Unexpected args"),
986                }])
987            });
988
989        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
990
991        assert_eq!(
992            result,
993            ControlFlow::Return(smallvec![DataValue::F32(Ieee32::with_float(1.0))])
994        )
995    }
996
997    #[test]
998    fn misaligned_store_traps() {
999        let code = "
1000        function %test() {
1001            ss0 = explicit_slot 16
1002
1003        block0:
1004            v0 = stack_addr.i64 ss0
1005            v1 = iconst.i64 1
1006            store.i64 aligned v1, v0+2
1007            return
1008        }";
1009
1010        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1011        let mut env = FunctionStore::default();
1012        env.add(func.name.to_string(), &func);
1013        let state = InterpreterState::default().with_function_store(env);
1014        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1015
1016        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1017    }
1018
1019    #[test]
1020    fn misaligned_load_traps() {
1021        let code = "
1022        function %test() {
1023            ss0 = explicit_slot 16
1024
1025        block0:
1026            v0 = stack_addr.i64 ss0
1027            v1 = iconst.i64 1
1028            store.i64 aligned v1, v0
1029            v2 = load.i64 aligned v0+2
1030            return
1031        }";
1032
1033        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1034        let mut env = FunctionStore::default();
1035        env.add(func.name.to_string(), &func);
1036        let state = InterpreterState::default().with_function_store(env);
1037        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1038
1039        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1040    }
1041
1042    // When a trap occurs in a function called by another function, the trap was not being propagated
1043    // correctly. Instead the interpterer panicked with a invalid control flow state.
1044    // See this issue for more details: https://github.com/bytecodealliance/wasmtime/issues/6155
1045    #[test]
1046    fn trap_across_call_propagates_correctly() {
1047        let code = "
1048        function %u2() -> f32 system_v {
1049            ss0 = explicit_slot 69
1050            ss1 = explicit_slot 69
1051            ss2 = explicit_slot 69
1052
1053        block0:
1054            v0 = f32const -0x1.434342p-60
1055            v1 = stack_addr.i64 ss2+24
1056            store notrap aligned v0, v1
1057            return v0
1058        }
1059
1060        function %u1() -> f32 system_v {
1061            sig0 = () -> f32 system_v
1062            fn0 = colocated %u2 sig0
1063
1064        block0:
1065            v57 = call fn0()
1066            return v57
1067        }";
1068
1069        let mut env = FunctionStore::default();
1070
1071        let funcs = parse_functions(code).unwrap();
1072        for func in &funcs {
1073            env.add(func.name.to_string(), func);
1074        }
1075
1076        let state = InterpreterState::default().with_function_store(env);
1077        let trap = Interpreter::new(state).call_by_name("%u1", &[]).unwrap();
1078
1079        // Ensure that the correct trap was propagated.
1080        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1081    }
1082}