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    // Test conversions that trap. These are tested here instead of in Clif runtests because runtests can't test
642    // trapping behavior.
643    #[test]
644    fn fcvt_to_int_i128_traps() {
645        const OVERFLOW: TrapCode = TrapCode::INTEGER_OVERFLOW;
646        const BAD: TrapCode = TrapCode::BAD_CONVERSION_TO_INTEGER;
647        for (op, ty, x, trap) in [
648            // Signed: the range is [-2^127, 2^127).
649            ("fcvt_to_sint", "f32", "0x1.0p127", OVERFLOW),
650            ("fcvt_to_sint", "f32", "0x1.fffffep127", OVERFLOW),
651            ("fcvt_to_sint", "f32", "-0x1.000002p127", OVERFLOW),
652            ("fcvt_to_sint", "f32", "-0x1.fffffep127", OVERFLOW),
653            ("fcvt_to_sint", "f32", "+Inf", OVERFLOW),
654            ("fcvt_to_sint", "f32", "-Inf", OVERFLOW),
655            ("fcvt_to_sint", "f32", "+NaN", BAD),
656            ("fcvt_to_sint", "f64", "0x1.0p127", OVERFLOW),
657            ("fcvt_to_sint", "f64", "-0x1.0000000000001p127", OVERFLOW),
658            ("fcvt_to_sint", "f64", "0x1.fffffffffffffp1023", OVERFLOW),
659            ("fcvt_to_sint", "f64", "-0x1.fffffffffffffp1023", OVERFLOW),
660            ("fcvt_to_sint", "f64", "+Inf", OVERFLOW),
661            ("fcvt_to_sint", "f64", "-Inf", OVERFLOW),
662            ("fcvt_to_sint", "f64", "-NaN", BAD),
663            // Unsigned: the range is [0, 2^128). Every finite f32 below
664            // -1.0 is out of range, but none above: f32::MAX < 2^128.
665            ("fcvt_to_uint", "f32", "-0x1.0", OVERFLOW),
666            ("fcvt_to_uint", "f32", "-0x1.fffffep127", OVERFLOW),
667            ("fcvt_to_uint", "f32", "+Inf", OVERFLOW),
668            ("fcvt_to_uint", "f32", "-Inf", OVERFLOW),
669            ("fcvt_to_uint", "f32", "+NaN", BAD),
670            ("fcvt_to_uint", "f64", "-0x1.0", OVERFLOW),
671            ("fcvt_to_uint", "f64", "-0x1.fffffffffffffp1023", OVERFLOW),
672            ("fcvt_to_uint", "f64", "-Inf", OVERFLOW),
673            ("fcvt_to_uint", "f64", "0x1.0p128", OVERFLOW),
674            ("fcvt_to_uint", "f64", "0x1.fffffffffffffp1023", OVERFLOW),
675            ("fcvt_to_uint", "f64", "+Inf", OVERFLOW),
676            ("fcvt_to_uint", "f64", "-NaN", BAD),
677        ] {
678            let code = format!(
679                "function %test() -> i128 {{
680                block0:
681                    v0 = {ty}const {x}
682                    v1 = {op}.i128 v0
683                    return v1
684                }}"
685            );
686
687            let func = parse_functions(&code).unwrap().into_iter().next().unwrap();
688            let mut env = FunctionStore::default();
689            env.add(func.name.to_string(), &func);
690            let state = InterpreterState::default().with_function_store(env);
691            let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
692
693            assert_eq!(
694                result,
695                ControlFlow::Trap(CraneliftTrap::User(trap)),
696                "{op}.i128 {ty} {x}"
697            );
698        }
699    }
700
701    // This test verifies that functions can refer to each other using the function store. A double indirection is
702    // required, which is tricky to get right: a referenced function is a FuncRef when called but a FuncIndex inside the
703    // function store. This test would preferably be a CLIF filetest but the filetest infrastructure only looks at a
704    // single function at a time--we need more than one function in the store for this test.
705    #[test]
706    fn function_references() {
707        let code = "
708        function %child(i32) -> i32 {
709        block0(v0: i32):
710            v2 = iconst.i32 -1
711            v1 = iadd v0, v2
712            return v1
713        }
714
715        function %parent(i32) -> i32 {
716            fn42 = %child(i32) -> i32
717        block0(v0: i32):
718            v3 = iconst.i32 1
719            v1 = iadd v0, v3
720            v2 = call fn42(v1)
721            return v2
722        }";
723
724        let mut env = FunctionStore::default();
725        let funcs = parse_functions(code).unwrap().to_vec();
726        funcs.iter().for_each(|f| env.add(f.name.to_string(), f));
727
728        let state = InterpreterState::default().with_function_store(env);
729        let result = Interpreter::new(state)
730            .call_by_name("%parent", &[DataValue::I32(0)])
731            .unwrap();
732
733        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(0)]));
734    }
735
736    #[test]
737    fn fuel() {
738        let code = "function %test() -> i8 {
739        block0:
740            v0 = iconst.i32 1
741            v2 = iconst.i32 1
742            v1 = iadd v0, v2
743            return v1
744        }";
745
746        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
747        let mut env = FunctionStore::default();
748        env.add(func.name.to_string(), &func);
749
750        // The default interpreter should not enable the fuel mechanism
751        let state = InterpreterState::default().with_function_store(env.clone());
752        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
753
754        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(2)]));
755
756        // With 3 fuel, we should execute the two iconsts and the iadd, but not the return thus
757        // giving a fuel exhausted error
758        let state = InterpreterState::default().with_function_store(env.clone());
759        let result = Interpreter::new(state)
760            .with_fuel(Some(3))
761            .call_by_name("%test", &[]);
762        match result {
763            Err(InterpreterError::FuelExhausted) => {}
764            _ => panic!("Expected Err(FuelExhausted), but got {result:?}"),
765        }
766
767        // With 4 fuel, we should be able to execute the return instruction, and complete the test
768        let state = InterpreterState::default().with_function_store(env.clone());
769        let result = Interpreter::new(state)
770            .with_fuel(Some(4))
771            .call_by_name("%test", &[])
772            .unwrap();
773
774        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I32(2)]));
775    }
776
777    // Verifies that writing to the stack on a called function does not overwrite the parents
778    // stack slots.
779    #[test]
780    fn stack_slots_multi_functions() {
781        let code = "
782        function %callee(i64, i64) -> i64 {
783            ss0 = explicit_slot 8
784            ss1 = explicit_slot 8
785
786        block0(v0: i64, v1: i64):
787            v5 = stack_addr.i64 ss0
788            store.i64 v0, v5
789            v6 = stack_addr.i64 ss1
790            store.i64 v1, v6
791            v7 = stack_addr.i64 ss0
792            v2 = load.i64 v7
793            v8 = stack_addr.i64 ss1
794            v3 = load.i64 v8
795            v4 = iadd.i64 v2, v3
796            return v4
797        }
798
799        function %caller(i64, i64, i64, i64) -> i64 {
800            fn0 = %callee(i64, i64) -> i64
801            ss0 = explicit_slot 8
802            ss1 = explicit_slot 8
803
804        block0(v0: i64, v1: i64, v2: i64, v3: i64):
805            v9 = stack_addr.i64 ss0
806            store.i64 v0, v9
807            v10 = stack_addr.i64 ss1
808            store.i64 v1, v10
809
810            v4 = call fn0(v2, v3)
811
812            v11 = stack_addr.i64 ss0
813            v5 = load.i64 v11
814            v12 = stack_addr.i64 ss1
815            v6 = load.i64 v12
816
817            v7 = iadd.i64 v4, v5
818            v8 = iadd.i64 v7, v6
819
820            return v8
821        }";
822
823        let mut env = FunctionStore::default();
824        let funcs = parse_functions(code).unwrap().to_vec();
825        funcs.iter().for_each(|f| env.add(f.name.to_string(), f));
826
827        let state = InterpreterState::default().with_function_store(env);
828        let result = Interpreter::new(state)
829            .call_by_name(
830                "%caller",
831                &[
832                    DataValue::I64(3),
833                    DataValue::I64(5),
834                    DataValue::I64(7),
835                    DataValue::I64(11),
836                ],
837            )
838            .unwrap();
839
840        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I64(26)]))
841    }
842
843    #[test]
844    fn out_of_slot_write_traps() {
845        let code = "
846        function %stack_write() {
847            ss0 = explicit_slot 8
848
849        block0:
850            v0 = iconst.i64 10
851            v1 = stack_addr.i64 ss0+8
852            store.i64 v0, v1
853            return
854        }";
855
856        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
857        let mut env = FunctionStore::default();
858        env.add(func.name.to_string(), &func);
859        let state = InterpreterState::default().with_function_store(env);
860        let trap = Interpreter::new(state)
861            .call_by_name("%stack_write", &[])
862            .unwrap();
863
864        assert_eq!(
865            trap,
866            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
867        );
868    }
869
870    #[test]
871    fn partial_out_of_slot_write_traps() {
872        let code = "
873        function %stack_write() {
874            ss0 = explicit_slot 8
875
876        block0:
877            v0 = iconst.i64 10
878            v1 = stack_addr.i64 ss0+4
879            store.i64 v0, v1
880            return
881        }";
882
883        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
884        let mut env = FunctionStore::default();
885        env.add(func.name.to_string(), &func);
886        let state = InterpreterState::default().with_function_store(env);
887        let trap = Interpreter::new(state)
888            .call_by_name("%stack_write", &[])
889            .unwrap();
890
891        assert_eq!(
892            trap,
893            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
894        );
895    }
896
897    #[test]
898    fn out_of_slot_read_traps() {
899        let code = "
900        function %stack_load() {
901            ss0 = explicit_slot 8
902
903        block0:
904            v1 = stack_addr.i64 ss0+8
905            v0 = load.i64 v1
906            return
907        }";
908
909        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
910        let mut env = FunctionStore::default();
911        env.add(func.name.to_string(), &func);
912        let state = InterpreterState::default().with_function_store(env);
913        let trap = Interpreter::new(state)
914            .call_by_name("%stack_load", &[])
915            .unwrap();
916
917        assert_eq!(
918            trap,
919            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
920        );
921    }
922
923    #[test]
924    fn partial_out_of_slot_read_traps() {
925        let code = "
926        function %stack_load() {
927            ss0 = explicit_slot 8
928
929        block0:
930            v1 = stack_addr.i64 ss0+4
931            v0 = load.i64 v1
932            return
933        }";
934
935        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
936        let mut env = FunctionStore::default();
937        env.add(func.name.to_string(), &func);
938        let state = InterpreterState::default().with_function_store(env);
939        let trap = Interpreter::new(state)
940            .call_by_name("%stack_load", &[])
941            .unwrap();
942
943        assert_eq!(
944            trap,
945            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
946        );
947    }
948
949    #[test]
950    fn partial_out_of_slot_read_by_addr_traps() {
951        let code = "
952        function %stack_load() {
953            ss0 = explicit_slot 8
954
955        block0:
956            v0 = stack_addr.i64 ss0
957            v1 = iconst.i64 4
958            v2 = iadd.i64 v0, v1
959            v3 = load.i64 v2
960            return
961        }";
962
963        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
964        let mut env = FunctionStore::default();
965        env.add(func.name.to_string(), &func);
966        let state = InterpreterState::default().with_function_store(env);
967        let trap = Interpreter::new(state)
968            .call_by_name("%stack_load", &[])
969            .unwrap();
970
971        assert_eq!(
972            trap,
973            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
974        );
975    }
976
977    #[test]
978    fn partial_out_of_slot_write_by_addr_traps() {
979        let code = "
980        function %stack_store() {
981            ss0 = explicit_slot 8
982
983        block0:
984            v0 = stack_addr.i64 ss0
985            v1 = iconst.i64 4
986            v2 = iadd.i64 v0, v1
987            store.i64 v1, v2
988            return
989        }";
990
991        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
992        let mut env = FunctionStore::default();
993        env.add(func.name.to_string(), &func);
994        let state = InterpreterState::default().with_function_store(env);
995        let trap = Interpreter::new(state)
996            .call_by_name("%stack_store", &[])
997            .unwrap();
998
999        assert_eq!(
1000            trap,
1001            ControlFlow::Trap(CraneliftTrap::User(TrapCode::HEAP_OUT_OF_BOUNDS))
1002        );
1003    }
1004
1005    #[test]
1006    fn srem_min_by_neg_one_is_zero() {
1007        let code = "function %test() -> i64 {
1008        block0:
1009            v0 = iconst.i64 0x8000_0000_0000_0000
1010            v1 = iconst.i64 -1
1011            v2 = srem.i64 v0, v1
1012            return v2
1013        }";
1014
1015        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1016        let mut env = FunctionStore::default();
1017        env.add(func.name.to_string(), &func);
1018        let state = InterpreterState::default().with_function_store(env);
1019        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1020
1021        assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I64(0)]));
1022    }
1023
1024    #[test]
1025    fn libcall() {
1026        let code = "function %test() -> i64 {
1027            fn0 = colocated %CeilF32 (f32) -> f32 fast
1028        block0:
1029            v1 = f32const 0x0.5
1030            v2 = call fn0(v1)
1031            return v2
1032        }";
1033
1034        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1035        let mut env = FunctionStore::default();
1036        env.add(func.name.to_string(), &func);
1037        let state = InterpreterState::default()
1038            .with_function_store(env)
1039            .with_libcall_handler(|libcall, args| {
1040                Ok(smallvec![match (libcall, &args[..]) {
1041                    (LibCall::CeilF32, [DataValue::F32(a)]) => DataValue::F32(a.ceil()),
1042                    _ => panic!("Unexpected args"),
1043                }])
1044            });
1045
1046        let result = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1047
1048        assert_eq!(
1049            result,
1050            ControlFlow::Return(smallvec![DataValue::F32(Ieee32::with_float(1.0))])
1051        )
1052    }
1053
1054    #[test]
1055    fn misaligned_store_traps() {
1056        let code = "
1057        function %test() {
1058            ss0 = explicit_slot 16
1059
1060        block0:
1061            v0 = stack_addr.i64 ss0
1062            v1 = iconst.i64 1
1063            store.i64 aligned v1, v0+2
1064            return
1065        }";
1066
1067        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1068        let mut env = FunctionStore::default();
1069        env.add(func.name.to_string(), &func);
1070        let state = InterpreterState::default().with_function_store(env);
1071        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1072
1073        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1074    }
1075
1076    #[test]
1077    fn misaligned_load_traps() {
1078        let code = "
1079        function %test() {
1080            ss0 = explicit_slot 16
1081
1082        block0:
1083            v0 = stack_addr.i64 ss0
1084            v1 = iconst.i64 1
1085            store.i64 aligned v1, v0
1086            v2 = load.i64 aligned v0+2
1087            return
1088        }";
1089
1090        let func = parse_functions(code).unwrap().into_iter().next().unwrap();
1091        let mut env = FunctionStore::default();
1092        env.add(func.name.to_string(), &func);
1093        let state = InterpreterState::default().with_function_store(env);
1094        let trap = Interpreter::new(state).call_by_name("%test", &[]).unwrap();
1095
1096        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1097    }
1098
1099    // When a trap occurs in a function called by another function, the trap was not being propagated
1100    // correctly. Instead the interpterer panicked with a invalid control flow state.
1101    // See this issue for more details: https://github.com/bytecodealliance/wasmtime/issues/6155
1102    #[test]
1103    fn trap_across_call_propagates_correctly() {
1104        let code = "
1105        function %u2() -> f32 system_v {
1106            ss0 = explicit_slot 69
1107            ss1 = explicit_slot 69
1108            ss2 = explicit_slot 69
1109
1110        block0:
1111            v0 = f32const -0x1.434342p-60
1112            v1 = stack_addr.i64 ss2+24
1113            store notrap aligned v0, v1
1114            return v0
1115        }
1116
1117        function %u1() -> f32 system_v {
1118            sig0 = () -> f32 system_v
1119            fn0 = colocated %u2 sig0
1120
1121        block0:
1122            v57 = call fn0()
1123            return v57
1124        }";
1125
1126        let mut env = FunctionStore::default();
1127
1128        let funcs = parse_functions(code).unwrap();
1129        for func in &funcs {
1130            env.add(func.name.to_string(), func);
1131        }
1132
1133        let state = InterpreterState::default().with_function_store(env);
1134        let trap = Interpreter::new(state).call_by_name("%u1", &[]).unwrap();
1135
1136        // Ensure that the correct trap was propagated.
1137        assert_eq!(trap, ControlFlow::Trap(CraneliftTrap::HeapMisaligned));
1138    }
1139}