Skip to main content

solana_sbpf/
vm.rs

1#![allow(clippy::arithmetic_side_effects)]
2// Derived from uBPF <https://github.com/iovisor/ubpf>
3// Copyright 2015 Big Switch Networks, Inc
4//      (uBPF: VM architecture, parts of the interpreter, originally in C)
5// Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com>
6//      (Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls)
7// Copyright 2020 Solana Maintainers <maintainers@solana.com>
8//
9// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
10// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
11// copied, modified, or distributed except according to those terms.
12
13//! Virtual machine for eBPF programs.
14
15use crate::{
16    ebpf,
17    elf::Executable,
18    error::{EbpfError, ProgramResult},
19    interpreter::Interpreter,
20    memory_region::MemoryMapping,
21    program::{BuiltinFunction, BuiltinProgram, FunctionRegistry, SBPFVersion},
22    static_analysis::{Analysis, DummyContextObject, RegisterTraceEntry},
23};
24// Re-export defaults for direct access without the module path.
25pub use defaults::get_stack_frame_size;
26use std::{collections::BTreeMap, fmt::Debug, marker::PhantomData, mem::offset_of, ptr};
27
28#[cfg(feature = "shuttle-test")]
29use shuttle::sync::Arc;
30#[cfg(not(feature = "shuttle-test"))]
31use std::sync::Arc;
32
33#[cfg(all(feature = "jit", not(feature = "shuttle-test")))]
34use rand::{thread_rng, Rng};
35#[cfg(all(feature = "jit", feature = "shuttle-test"))]
36use shuttle::rand::{thread_rng, Rng};
37
38/// Returns (and if not done before generates) the encryption key for the VM pointer
39#[cfg(feature = "jit")]
40pub fn get_runtime_environment_key() -> i32 {
41    static RUNTIME_ENVIRONMENT_KEY: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
42    *RUNTIME_ENVIRONMENT_KEY.get_or_init(|| thread_rng().gen::<i32>() >> 1)
43}
44
45#[cfg(not(feature = "jit"))]
46pub fn get_runtime_environment_key() -> i32 {
47    0
48}
49
50/// Default VM configuration settings.
51pub(crate) mod defaults {
52    const DEFAULT_STACK_FRAME_SIZE: usize = 4_096;
53
54    /// Returns the stack frame size in bytes.
55    ///
56    /// With the `conf-stack-frame-size` feature enabled, the size can be overridden
57    /// at runtime via the `VM_STACK_FRAME_SIZE` environment variable. The value is
58    /// read once and cached. If not set, the default is always returned.
59    ///
60    /// Note: the `conf-stack-frame-size` variant can't be `const fn` (it uses
61    /// `OnceLock`), while the production variant is `const fn`. Callers that need
62    /// `const` evaluation (e.g. array sizes, const generics) should be aware that
63    /// those uses will not compile when `conf-stack-frame-size` is enabled.
64    #[cfg(feature = "conf-stack-frame-size")]
65    #[inline(always)]
66    pub fn get_stack_frame_size() -> usize {
67        static STACK_FRAME_SIZE_CACHE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
68        *STACK_FRAME_SIZE_CACHE.get_or_init(|| {
69            let size = std::env::var("VM_STACK_FRAME_SIZE")
70                .ok()
71                .and_then(|v| {
72                    v.parse::<usize>().ok().filter(|sfz| *sfz > 0).or_else(|| {
73                        log::warn!(
74                            "Invalid VM_STACK_FRAME_SIZE={}, falling back to {}.",
75                            v,
76                            DEFAULT_STACK_FRAME_SIZE
77                        );
78                        None
79                    })
80                })
81                .unwrap_or(DEFAULT_STACK_FRAME_SIZE);
82            if size != DEFAULT_STACK_FRAME_SIZE {
83                log::warn!(
84                    "VM_STACK_FRAME_SIZE is set to {} (default: {}).",
85                    size,
86                    DEFAULT_STACK_FRAME_SIZE
87                );
88            }
89            size
90        })
91    }
92
93    /// Returns the stack frame size in bytes.
94    #[cfg(not(feature = "conf-stack-frame-size"))]
95    pub const fn get_stack_frame_size() -> usize {
96        DEFAULT_STACK_FRAME_SIZE
97    }
98}
99
100/// Specify the execution method.
101pub enum ExecutionMode {
102    /// Execute the program in an interpreted mode.
103    Interpreted,
104    /// Execute the program in JIT mode.
105    ///
106    /// The program must be JIT compiled.
107    Jit,
108    /// Allow JIT execution, if compiled. Otherwise fallback to interpreted.
109    PreferJit,
110}
111
112/// VM configuration settings
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct Config {
115    /// Maximum call depth
116    pub max_call_depth: usize,
117    /// Size of a stack frame in bytes, must match the size specified in the LLVM BPF backend
118    pub stack_frame_size: usize,
119    /// Enables the use of MemoryMapping and MemoryRegion for address translation
120    pub enable_address_translation: bool,
121    /// Enables gaps in VM address space between the stack frames
122    pub enable_stack_frame_gaps: bool,
123    /// Maximal pc distance after which a new instruction meter validation is emitted by the JIT
124    pub instruction_meter_checkpoint_distance: usize,
125    /// Enable instruction meter and limiting
126    pub enable_instruction_meter: bool,
127    /// Enable instruction tracing
128    pub enable_register_tracing: bool,
129    /// Enable dynamic string allocation for labels
130    pub enable_symbol_and_section_labels: bool,
131    /// Reject ELF files containing issues that the verifier did not catch before (up to v0.2.21)
132    pub reject_broken_elfs: bool,
133    #[cfg(feature = "jit")]
134    /// Ratio of native host instructions per random no-op in JIT (0 = OFF)
135    pub noop_instruction_rate: u32,
136    #[cfg(feature = "jit")]
137    /// Enable disinfection of immediate values and offsets provided by the user in JIT
138    pub sanitize_user_provided_values: bool,
139    /// Avoid copying read only sections when possible
140    pub optimize_rodata: bool,
141    /// Use aligned memory mapping
142    pub aligned_memory_mapping: bool,
143    /// Allowed [SBPFVersion]s
144    pub enabled_sbpf_versions: std::ops::RangeInclusive<SBPFVersion>,
145}
146
147impl Config {
148    /// Returns the size of the stack memory region
149    pub fn stack_size(&self) -> usize {
150        self.stack_frame_size * self.max_call_depth
151    }
152}
153
154impl Default for Config {
155    fn default() -> Self {
156        Self {
157            max_call_depth: 64,
158            stack_frame_size: defaults::get_stack_frame_size(),
159            enable_address_translation: true,
160            enable_stack_frame_gaps: true,
161            instruction_meter_checkpoint_distance: 10000,
162            enable_instruction_meter: true,
163            enable_register_tracing: false,
164            enable_symbol_and_section_labels: false,
165            reject_broken_elfs: false,
166            #[cfg(feature = "jit")]
167            noop_instruction_rate: 256,
168            #[cfg(feature = "jit")]
169            sanitize_user_provided_values: true,
170            optimize_rodata: true,
171            aligned_memory_mapping: false,
172            enabled_sbpf_versions: SBPFVersion::V0..=SBPFVersion::V4,
173        }
174    }
175}
176
177/// Static constructors for Executable
178impl<C: ContextObject> Executable<C> {
179    /// Creates an executable from an ELF file
180    pub fn from_elf(elf_bytes: &[u8], loader: Arc<BuiltinProgram<C>>) -> Result<Self, EbpfError> {
181        let executable = Executable::load(elf_bytes, loader)?;
182        Ok(executable)
183    }
184    /// Creates an executable from machine code
185    pub fn from_text_bytes(
186        text_bytes: &[u8],
187        loader: Arc<BuiltinProgram<C>>,
188        sbpf_version: SBPFVersion,
189        function_registry: FunctionRegistry<usize>,
190    ) -> Result<Self, EbpfError> {
191        Executable::new_from_text_bytes(text_bytes, loader, sbpf_version, function_registry)
192            .map_err(EbpfError::ElfError)
193    }
194}
195
196/// Runtime context
197pub trait ContextObject {
198    /// Consume instructions from meter
199    fn consume(&mut self, amount: u64);
200    /// Get the number of remaining instructions allowed
201    fn get_remaining(&self) -> u64;
202    /// Return a mutable pointer to the active MemoryMapping
203    fn active_mapping_ptr(&mut self) -> ptr::NonNull<MemoryMapping>;
204}
205
206/// Statistic of taken branches (from a recorded trace)
207pub struct DynamicAnalysis {
208    /// Maximal edge counter value
209    pub edge_counter_max: usize,
210    /// src_node, dst_node, edge_counter
211    pub edges: BTreeMap<usize, BTreeMap<usize, usize>>,
212}
213
214impl DynamicAnalysis {
215    /// Accumulates a trace
216    pub fn new(register_trace: &[[u64; 12]], analysis: &Analysis) -> Self {
217        let mut result = Self {
218            edge_counter_max: 0,
219            edges: BTreeMap::new(),
220        };
221        let mut last_basic_block = usize::MAX;
222        for traced_instruction in register_trace.iter() {
223            let pc = traced_instruction[11] as usize;
224            if analysis.cfg_nodes.contains_key(&pc) {
225                let counter = result
226                    .edges
227                    .entry(last_basic_block)
228                    .or_default()
229                    .entry(pc)
230                    .or_insert(0);
231                *counter += 1;
232                result.edge_counter_max = result.edge_counter_max.max(*counter);
233                last_basic_block = pc;
234            }
235        }
236        result
237    }
238}
239
240/// A call frame used for function calls inside the Interpreter
241#[derive(Clone, Default)]
242pub struct CallFrame {
243    /// The caller saved registers
244    pub caller_saved_registers: [u64; ebpf::SCRATCH_REGS],
245    /// The callers frame pointer
246    pub frame_pointer: u64,
247    /// The target_pc of the exit instruction which returns back to the caller
248    pub target_pc: u64,
249}
250
251/// Indices of slots inside [EbpfVm]
252pub enum RuntimeEnvironmentSlot {
253    /// [EbpfVm::host_stack_pointer]
254    HostStackPointer = offset_of!(EbpfVm<DummyContextObject>, host_stack_pointer) as isize,
255    /// [EbpfVm::call_depth]
256    CallDepth = offset_of!(EbpfVm<DummyContextObject>, call_depth) as isize,
257    /// [EbpfVm::context_object_pointer]
258    ContextObjectPointer = offset_of!(EbpfVm<DummyContextObject>, context_object_pointer) as isize,
259    /// [EbpfVm::previous_instruction_meter]
260    PreviousInstructionMeter =
261        offset_of!(EbpfVm<DummyContextObject>, previous_instruction_meter) as isize,
262    /// [EbpfVm::due_insn_count]
263    DueInsnCount = offset_of!(EbpfVm<DummyContextObject>, due_insn_count) as isize,
264    /// [EbpfVm::stopwatch_numerator]
265    StopwatchNumerator = offset_of!(EbpfVm<DummyContextObject>, stopwatch_numerator) as isize,
266    /// [EbpfVm::stopwatch_denominator]
267    StopwatchDenominator = offset_of!(EbpfVm<DummyContextObject>, stopwatch_denominator) as isize,
268    /// [EbpfVm::registers]
269    Registers = offset_of!(EbpfVm<DummyContextObject>, registers) as isize,
270    /// [EbpfVm::program_result]
271    ProgramResult = offset_of!(EbpfVm<DummyContextObject>, program_result) as isize,
272    /// [EbpfVm::memory_mapping]
273    MemoryMapping = offset_of!(EbpfVm<DummyContextObject>, memory_mapping) as isize,
274    /// [EbpfVm::register_trace]
275    RegisterTrace = offset_of!(EbpfVm<DummyContextObject>, register_trace) as isize,
276}
277
278/// A virtual machine to run eBPF programs.
279///
280/// # Examples
281///
282/// ```
283/// use solana_sbpf::{
284///     aligned_memory::AlignedMemory,
285///     ebpf,
286///     elf::Executable,
287///     memory_region::{MemoryMapping, MemoryRegion},
288///     program::{BuiltinProgram, FunctionRegistry, SBPFVersion},
289///     verifier::RequisiteVerifier,
290///     vm::{CallFrame, Config, EbpfVm, ExecutionMode},
291/// };
292/// use test_utils::TestContextObject;
293///
294/// let prog = &[
295///     0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // add64 r0, 0
296///     0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // exit
297/// ];
298/// let mut mem: [u8; _] = [0xaa, 0xbb, 0x11, 0x22, 0xcc, 0xdd];
299///
300/// let loader = std::sync::Arc::new(BuiltinProgram::new_mock());
301/// let function_registry = FunctionRegistry::default();
302/// let mut executable = Executable::<TestContextObject>::from_text_bytes(prog, loader.clone(), SBPFVersion::V4, function_registry).unwrap();
303/// executable.verify::<RequisiteVerifier>().unwrap();
304/// let mut context_object = TestContextObject::new(2);
305/// let sbpf_version = executable.get_sbpf_version();
306///
307/// let mut stack = AlignedMemory::<{ebpf::HOST_ALIGN}>::zero_filled(executable.get_config().stack_size());
308/// let stack_len = stack.len();
309/// let mut heap = AlignedMemory::<{ebpf::HOST_ALIGN}>::with_capacity(0);
310///
311/// let regions: Vec<MemoryRegion> = vec![
312///     executable.get_ro_region(),
313///     MemoryRegion::new(&mut stack, ebpf::MM_STACK_START),
314///     MemoryRegion::new(&mut heap, ebpf::MM_HEAP_START),
315///     MemoryRegion::new(&raw mut mem, ebpf::MM_INPUT_START),
316/// ];
317///;
318/// context_object.memory_mapping = unsafe {
319///     MemoryMapping::new(regions, executable.get_config(), sbpf_version).unwrap()
320/// };
321///
322/// let mut vm = EbpfVm::new(loader, sbpf_version, &mut context_object, stack_len);
323///
324/// let mut call_frames = vec![CallFrame::default(); executable.get_config().max_call_depth];
325/// let (instruction_count, result) = vm.execute_program(
326///     &executable,
327///     &mut ExecutionMode::Interpreted,
328///     &mut call_frames,
329/// );
330/// assert_eq!(instruction_count, 2);
331/// assert_eq!(result.unwrap(), 0);
332/// ```
333#[repr(C)]
334pub struct EbpfVm<'a, C: ContextObject> {
335    /// Needed to exit from the guest back into the host
336    pub host_stack_pointer: *mut u64,
337    /// The current call depth.
338    ///
339    /// Incremented on calls and decremented on exits. It's used to enforce
340    /// config.max_call_depth and to know when to terminate execution.
341    pub call_depth: u64,
342    /// Pointer to ContextObject
343    pub(crate) context_object_pointer: ptr::NonNull<C>,
344    /// The lifetime for the context object pointer
345    context_object_lifetime: PhantomData<&'a mut C>,
346    /// Last return value of instruction_meter.get_remaining()
347    pub previous_instruction_meter: u64,
348    /// Outstanding value to instruction_meter.consume()
349    pub due_insn_count: u64,
350    /// CPU cycles accumulated by the stop watch
351    pub stopwatch_numerator: u64,
352    /// Number of times the stop watch was used
353    pub stopwatch_denominator: u64,
354    /// Registers inlined
355    pub registers: [u64; 12],
356    /// ProgramResult inlined
357    pub program_result: ProgramResult,
358    /// MemoryMapping inlined
359    pub(crate) memory_mapping: ptr::NonNull<MemoryMapping>,
360    /// Loader built-in program
361    pub loader: Arc<BuiltinProgram<C>>,
362    /// Collector for the instruction trace
363    pub register_trace: Vec<RegisterTraceEntry>,
364    /// TCP port for the debugger interface
365    #[cfg(feature = "debugger")]
366    pub debug_port: Option<u16>,
367    /// Debug metadata passed
368    #[cfg(feature = "debugger")]
369    pub debug_metadata: Option<String>,
370}
371
372impl<'a, C: ContextObject> EbpfVm<'a, C> {
373    /// Creates a new virtual machine instance.
374    pub fn new(
375        loader: Arc<BuiltinProgram<C>>,
376        sbpf_version: SBPFVersion,
377        context_object: &'a mut C,
378        stack_len: usize,
379    ) -> Self {
380        let config = loader.get_config();
381        let mut registers = [0u64; 12];
382        registers[ebpf::FRAME_PTR_REG] =
383            ebpf::MM_STACK_START.saturating_add(if !sbpf_version.manual_stack_frame_bump() {
384                config.stack_frame_size
385            } else {
386                stack_len
387            } as u64);
388
389        let memory_mapping = context_object.active_mapping_ptr();
390        EbpfVm {
391            host_stack_pointer: std::ptr::null_mut(),
392            call_depth: 0,
393            context_object_pointer: ptr::NonNull::from_mut(context_object),
394            context_object_lifetime: PhantomData,
395            previous_instruction_meter: 0,
396            due_insn_count: 0,
397            stopwatch_numerator: 0,
398            stopwatch_denominator: 0,
399            registers,
400            program_result: ProgramResult::Ok(0),
401            memory_mapping,
402            loader,
403            #[cfg(feature = "debugger")]
404            debug_port: std::env::var("VM_DEBUG_PORT")
405                .ok()
406                .and_then(|v| v.parse::<u16>().ok()),
407            #[cfg(feature = "debugger")]
408            debug_metadata: None,
409            register_trace: Vec::default(),
410        }
411    }
412
413    /// Execute the program
414    ///
415    /// Use `mode` parameter to request a specific execution type. This function will write back
416    /// the execution mode used back to the reference passed in.
417    ///
418    /// It is required to provide `call_frames` when executing in interpreted mode.
419    /// `call_frames` must be large enough to hold the executable config's `max_call_depth`
420    /// frames.
421    ///
422    /// Returns the instruction meter count (CUs) and the execution result of the program.
423    pub fn execute_program(
424        &mut self,
425        executable: &Executable<C>,
426        mode: &mut ExecutionMode,
427        call_frames: &mut [CallFrame],
428    ) -> (u64, ProgramResult) {
429        debug_assert!(Arc::ptr_eq(&self.loader, executable.get_loader()));
430        self.registers[11] = executable.get_entrypoint_instruction_offset() as u64;
431        let config = executable.get_config();
432        let initial_insn_count = self.context().get_remaining();
433        self.previous_instruction_meter = initial_insn_count;
434        self.due_insn_count = 0;
435        self.program_result = ProgramResult::Ok(0);
436
437        'execute: {
438            match *mode {
439                ExecutionMode::Interpreted => {}
440
441                #[cfg(all(feature = "jit", not(target_os = "windows"), target_arch = "x86_64"))]
442                ExecutionMode::PreferJit => {
443                    if let Some(compiled_program) = executable.get_compiled_program() {
444                        *mode = ExecutionMode::Jit;
445                        break 'execute compiled_program.invoke(config, self, self.registers);
446                    }
447                }
448                #[cfg(not(all(
449                    feature = "jit",
450                    not(target_os = "windows"),
451                    target_arch = "x86_64"
452                )))]
453                ExecutionMode::PreferJit => {}
454
455                #[cfg(all(feature = "jit", not(target_os = "windows"), target_arch = "x86_64"))]
456                ExecutionMode::Jit => {
457                    let Some(compiled_program) = executable.get_compiled_program() else {
458                        return (0, ProgramResult::Err(EbpfError::JitNotCompiled));
459                    };
460                    *mode = ExecutionMode::Jit;
461                    break 'execute compiled_program.invoke(config, self, self.registers);
462                }
463                #[cfg(not(all(
464                    feature = "jit",
465                    not(target_os = "windows"),
466                    target_arch = "x86_64"
467                )))]
468                ExecutionMode::Jit => return (0, ProgramResult::Err(EbpfError::JitNotCompiled)),
469            }
470
471            *mode = ExecutionMode::Interpreted;
472            let interpreter = Interpreter::new(self, executable, self.registers, call_frames);
473            break 'execute run_interpreter(interpreter);
474        }
475
476        let instruction_count = if config.enable_instruction_meter {
477            let due_insn_count = self.due_insn_count;
478            let context = self.context();
479            context.consume(due_insn_count);
480            initial_insn_count.saturating_sub(context.get_remaining())
481        } else {
482            0
483        };
484        let mut result = ProgramResult::Ok(0);
485        std::mem::swap(&mut result, &mut self.program_result);
486        (instruction_count, result)
487    }
488
489    /// Invokes a built-in function
490    pub fn invoke_function(&mut self, function: BuiltinFunction<C>) {
491        function(
492            self.encrypted_host_address(),
493            self.registers[1],
494            self.registers[2],
495            self.registers[3],
496            self.registers[4],
497            self.registers[5],
498        );
499    }
500
501    /// Build a `VmAddress` containing a (potentially) encrypted host pointer to self.
502    ///
503    /// Note that this type is effectively a mutable pointer to `self` and although it valid to
504    /// create multiple of these addresses, using them to violate the Rust mutable references'
505    /// uniqueness rule is not sound.
506    pub(crate) fn encrypted_host_address(&mut self) -> EncryptedHostAddressToEbpfVm<C> {
507        let addr = (&raw mut *self).expose_provenance() as isize;
508        EncryptedHostAddressToEbpfVm(
509            addr.wrapping_add(get_runtime_environment_key() as isize) as usize as u64,
510            PhantomData,
511        )
512    }
513
514    /// Get a reference to the context object referenced by this EbpfVm.
515    pub fn context(&mut self) -> &mut C {
516        // SAFETY: we've the unique reference to self here, so there can't be other live references
517        // to `C` either, whether via the memory_mapping or the context_object_pointer itself.
518        //
519        // The `context_object_pointer` is pointing at a valid-to-dereference `C` at all times
520        // through the EbpfVm lifetime.
521        //
522        // Note: for that reason we are intentionally tying the lifetime of the returned `C` to the
523        // lifetime of `&mut self`, rather than returning `&'a mut C`, which would allow aliasing
524        // the returned reference.
525        unsafe { self.context_object_pointer.as_mut() }
526    }
527
528    // Intentionally not public. Users are expected to store their memory mapping inside – and
529    // access from – C.
530    pub(crate) fn memory(&mut self) -> &mut MemoryMapping {
531        // SAFETY: we've the unique reference to self here, so there can't be other live references
532        // to `C` either, whether via the memory_mapping or the context_object_pointer itself.
533        //
534        // The `context_object_pointer` is pointing at a valid-to-dereference `C` at all times
535        // through the EbpfVm lifetime.
536        unsafe { self.memory_mapping.as_mut() }
537    }
538}
539
540/// Encrypted address to the [`EbpfVm`] object.
541#[repr(transparent)]
542pub struct EncryptedHostAddressToEbpfVm<C>(
543    // This ends up having to be public to the crate because inline assembly wants to deal with
544    // integers, not `VmAddress` (even though VmAddress has the same layout.)
545    pub(crate) u64,
546    PhantomData<C>,
547);
548
549impl<C: ContextObject> EncryptedHostAddressToEbpfVm<C> {
550    /// Work on [`EbpfVm`] pointed to by this address.
551    ///
552    /// ## Safety
553    ///
554    /// Multiple concurrently live addresses can reference the same [`EbpfVm`] but under no
555    /// circumstances may they be used to create multiple concurrent mutable references to the
556    /// `EbpfVm`.
557    pub unsafe fn with_vm<R>(&mut self, cb: impl FnOnce(&mut EbpfVm<'_, C>) -> R) -> R {
558        let addr = (self.0 as usize as isize)
559            .wrapping_sub(crate::vm::get_runtime_environment_key() as isize);
560        // SAFETY: we've recovered the same pointer address as that of the reference used to
561        // produce this offset address in the first place.
562        // SAFETY: The mutable reference is unique due to invariant being passed onto the caller.
563        let vm = unsafe {
564            std::ptr::with_exposed_provenance_mut::<crate::vm::EbpfVm<C>>(addr as usize)
565                .as_mut()
566                .unwrap()
567        };
568        cb(vm)
569    }
570}
571
572#[cold]
573#[inline(never)]
574#[cfg(feature = "debugger")]
575fn run_interpreter<C: ContextObject>(mut interpreter: Interpreter<C>) {
576    let debug_port = interpreter.vm.debug_port.clone();
577    if let Some(debug_port) = debug_port {
578        crate::debugger::execute(&mut interpreter, debug_port);
579    } else {
580        while interpreter.step() {}
581    }
582}
583
584#[cold]
585#[inline(never)]
586#[cfg(not(feature = "debugger"))]
587fn run_interpreter<C: ContextObject>(mut interpreter: Interpreter<C>) {
588    while interpreter.step() {}
589}
590
591#[cfg(test)]
592mod tests {
593    use crate::{
594        memory_region::MemoryMapping,
595        program::{BuiltinProgram, SBPFVersion},
596        vm::{Config, ContextObject, RuntimeEnvironmentSlot},
597    };
598    use std::{ptr::NonNull, sync::Arc};
599
600    #[test]
601    fn test_runtime_environment_slots() {
602        struct DummyContextObject(MemoryMapping);
603        impl ContextObject for DummyContextObject {
604            fn consume(&mut self, _: u64) {
605                todo!()
606            }
607            fn get_remaining(&self) -> u64 {
608                todo!()
609            }
610            fn active_mapping_ptr(&mut self) -> NonNull<MemoryMapping> {
611                NonNull::from_mut(&mut self.0)
612            }
613        }
614        let version = SBPFVersion::V4;
615        let config = Config::default();
616        let mut context_object =
617            unsafe { DummyContextObject(MemoryMapping::new(vec![], &config, version).unwrap()) };
618        let env = super::EbpfVm::new(
619            Arc::new(BuiltinProgram::new_mock()),
620            version,
621            &mut context_object,
622            4096,
623        );
624
625        macro_rules! check_slot {
626            ($env:expr, $entry:ident, $slot:ident) => {
627                assert_eq!(
628                    unsafe {
629                        std::ptr::addr_of!($env.$entry)
630                            .cast::<u8>()
631                            .offset_from(std::ptr::addr_of!($env).cast::<u8>()) as usize
632                    },
633                    RuntimeEnvironmentSlot::$slot as usize,
634                );
635            };
636        }
637
638        check_slot!(env, host_stack_pointer, HostStackPointer);
639        check_slot!(env, call_depth, CallDepth);
640        check_slot!(env, context_object_pointer, ContextObjectPointer);
641        check_slot!(env, previous_instruction_meter, PreviousInstructionMeter);
642        check_slot!(env, due_insn_count, DueInsnCount);
643        check_slot!(env, stopwatch_numerator, StopwatchNumerator);
644        check_slot!(env, stopwatch_denominator, StopwatchDenominator);
645        check_slot!(env, registers, Registers);
646        check_slot!(env, program_result, ProgramResult);
647        check_slot!(env, memory_mapping, MemoryMapping);
648        check_slot!(env, register_trace, RegisterTrace);
649    }
650}