Skip to main content

solana_program_runtime/
vm.rs

1//! SBF virtual machine provisioning and execution.
2
3#[cfg(feature = "svm-internal")]
4use qualifier_attr::qualifiers;
5use {
6    crate::{
7        abi::ABI,
8        execution_budget::MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268,
9        invoke_context::{BpfAllocator, InvokeContext},
10        mem_pool::VmMemoryPool,
11        memory_context::{MemoryContext, SerializedAccountMetadata},
12        program_cache::entry::ProgramCacheEntry,
13        serialization::{self, SerializationResult},
14        stable_log,
15    },
16    solana_instruction_error::InstructionError,
17    solana_program_entrypoint::SUCCESS,
18    solana_sbpf::{
19        ebpf::{self, MM_HEAP_START, MM_RODATA_START, MM_STACK_START},
20        elf::Executable,
21        error::{EbpfError, ProgramResult},
22        memory_region::{AccessType, MemoryMapping, MemoryRegion},
23        vm::{ContextObject, EbpfVm, ExecutionMode},
24    },
25    solana_svm_log_collector::ic_logger_msg,
26    solana_svm_measure::measure::Measure,
27    solana_transaction_context::IndexOfAccount,
28    std::{cell::RefCell, mem, time::Duration},
29};
30
31thread_local! {
32    pub static MEMORY_POOL: RefCell<VmMemoryPool> = RefCell::new(VmMemoryPool::new());
33}
34
35/// Only used in macro, do not use directly!
36pub fn calculate_heap_cost(heap_size: u32, heap_cost: u64) -> u64 {
37    const KIBIBYTE: u64 = 1024;
38    const PAGE_SIZE_KB: u64 = 32;
39    let mut rounded_heap_size = u64::from(heap_size);
40    rounded_heap_size =
41        rounded_heap_size.saturating_add(PAGE_SIZE_KB.saturating_mul(KIBIBYTE).saturating_sub(1));
42    rounded_heap_size
43        .checked_div(PAGE_SIZE_KB.saturating_mul(KIBIBYTE))
44        .expect("PAGE_SIZE_KB * KIBIBYTE > 0")
45        .saturating_sub(1)
46        .saturating_mul(heap_cost)
47}
48
49/// Only used in macro, do not use directly!
50///
51/// # Safety
52///
53/// Refer to [`configure_program_regions`].
54#[cfg_attr(feature = "svm-internal", qualifiers(pub))]
55pub unsafe fn create_vm<'a, 'b>(
56    program: &'a Executable<InvokeContext<'b, 'b>>,
57    invoke_context: &'a mut InvokeContext<'b, 'b>,
58    stack: *mut [u8],
59    heap: *mut [u8],
60) -> Result<EbpfVm<'a, InvokeContext<'b, 'b>>, Box<dyn std::error::Error>> {
61    let stack_size = stack.len();
62    unsafe {
63        // SAFETY: invariants delegated to the caller.
64        configure_program_regions(invoke_context, program, stack, heap)?;
65    }
66    Ok(EbpfVm::new(
67        program.get_loader().clone(),
68        program.get_sbpf_version(),
69        invoke_context,
70        stack_size,
71    ))
72}
73
74/// # Safety
75///
76/// The `executable`, `stack` and `heap` arguments must remain allocated for at least the lifetime
77/// of [`MemoryMapping`] (or until after the `MemoryMapping` is reconfigured with different
78/// `executable`, `stack` and `heap`).
79unsafe fn configure_program_regions<C: ContextObject>(
80    invoke_context: &mut InvokeContext,
81    executable: &Executable<C>,
82    stack: *mut [u8],
83    heap: *mut [u8],
84) -> Result<(), Box<dyn std::error::Error>> {
85    let mapping = invoke_context.memory_contexts.memory_mapping_mut()?;
86    let regions = mapping.get_regions_mut();
87    let [ro_area, stack_area, heap_area, ..] = regions else {
88        panic!("the regions vector must have at least three entries")
89    };
90    *ro_area = executable.get_ro_region();
91    let sbpf_version = executable.get_sbpf_version();
92    let config = executable.get_config();
93    *stack_area = MemoryRegion::new_gapped(
94        stack,
95        MM_STACK_START,
96        if sbpf_version.stack_frame_gaps() && config.enable_stack_frame_gaps {
97            config.stack_frame_size as u64
98        } else {
99            0
100        },
101    );
102    *heap_area = MemoryRegion::new(heap, MM_HEAP_START);
103    mapping
104        .initialize()
105        .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
106}
107
108/// Create the SBF virtual machine
109#[macro_export]
110macro_rules! create_vm {
111    ($vm:ident, $program:expr, $invoke_context:expr $(,)?) => {
112        let invoke_context = &*$invoke_context;
113        let stack_size = $program.get_config().stack_size();
114        let heap_size = invoke_context.get_compute_budget().heap_size;
115        let heap_cost_result =
116            invoke_context.consume_checked($crate::__private::calculate_heap_cost(
117                heap_size,
118                invoke_context.get_execution_cost().heap_cost,
119            ));
120        let $vm = heap_cost_result.and_then(|_| {
121            let (mut stack, mut heap) = $crate::__private::MEMORY_POOL
122                .with_borrow_mut(|pool| (pool.get_stack(stack_size), pool.get_heap(heap_size)));
123            let vm = $crate::__private::create_vm(
124                $program,
125                $invoke_context,
126                stack
127                    .as_slice_mut()
128                    .get_mut(..stack_size)
129                    .expect("invalid stack size"),
130                heap.as_slice_mut()
131                    .get_mut(..heap_size as usize)
132                    .expect("invalid heap size"),
133            );
134            vm.map(|vm| (vm, stack, heap))
135        });
136    };
137}
138
139/// # Safety
140///
141/// The [`MemoryRegion`]s must satisfy the safety preconditions for
142/// [`MemoryMapping::new_uninitialized`].
143unsafe fn set_memory_context<'b>(
144    additional_initialized_regions: Vec<MemoryRegion>,
145    accounts_metadata: Vec<SerializedAccountMetadata>,
146    invoke_context: &mut InvokeContext<'b, 'b>,
147    executable: &Executable<InvokeContext<'b, 'b>>,
148    virtual_address_space_adjustments: bool,
149    account_data_direct_mapping: bool,
150) -> Result<(), Box<dyn std::error::Error>> {
151    let heap_size = invoke_context.get_compute_budget().heap_size;
152    let regions = [
153        MemoryRegion::new_empty(MM_RODATA_START),
154        MemoryRegion::new_empty(MM_STACK_START),
155        MemoryRegion::new_empty(MM_HEAP_START),
156    ]
157    .into_iter()
158    .chain(additional_initialized_regions)
159    .collect();
160    let memory_mapping = unsafe {
161        // SAFETY: all memory regions are `default` (and thus implicitly valid) or valid by
162        // delegating the safety invariant upon the caller.
163        MemoryMapping::new_uninitialized(
164            regions,
165            executable.get_config(),
166            executable.get_sbpf_version(),
167            invoke_context.transaction_context.access_violation_handler(
168                virtual_address_space_adjustments,
169                account_data_direct_mapping,
170            ),
171        )
172    };
173
174    invoke_context
175        .memory_contexts
176        .set_memory_context_abi_v1(MemoryContext::new(
177            BpfAllocator::new(heap_size as u64),
178            accounts_metadata,
179            memory_mapping,
180        ))
181        .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
182}
183
184#[cfg_attr(feature = "svm-internal", qualifiers(pub))]
185pub fn execute<'a, 'b: 'a>(
186    executable: &'a Executable<InvokeContext<'static, 'static>>,
187    invoke_context: &'a mut InvokeContext<'b, 'b>,
188    cache_entry: &ProgramCacheEntry,
189) -> Result<(), Box<dyn std::error::Error>> {
190    // We dropped the lifetime tracking in the Executor by setting it to 'static,
191    // thus we need to reintroduce the correct lifetime of InvokeContext here again.
192    let executable = unsafe {
193        mem::transmute::<
194            &'a Executable<InvokeContext<'static, 'static>>,
195            &'a Executable<InvokeContext<'b, 'b>>,
196        >(executable)
197    };
198    let log_collector = invoke_context.get_log_collector();
199    let abi = invoke_context.abi();
200    let transaction_context = &invoke_context.transaction_context;
201    let instruction_context = transaction_context.get_current_instruction_context()?;
202    let program_id = *instruction_context.get_program_key()?;
203    let virtual_address_space_adjustments = invoke_context
204        .get_feature_set()
205        .virtual_address_space_adjustments;
206    let account_data_direct_mapping = invoke_context.get_feature_set().account_data_direct_mapping;
207    let direct_account_pointers_in_program_input = invoke_context
208        .get_feature_set()
209        .direct_account_pointers_in_program_input;
210    let pass_input_metadata_in_vm_r3_r5 = invoke_context
211        .get_feature_set()
212        .pass_input_metadata_in_vm_r3_r5;
213
214    let mut serialize_time = Measure::start("serialize");
215    let SerializationResult {
216        parameter_bytes,
217        regions,
218        accounts_metadata,
219        instruction_data_offset,
220        account_pointers_offset,
221    } = serialization::serialize_parameters(
222        &instruction_context,
223        abi,
224        virtual_address_space_adjustments,
225        account_data_direct_mapping,
226        direct_account_pointers_in_program_input,
227    )?;
228    serialize_time.stop();
229
230    let instruction_data_len = instruction_context.get_instruction_data().len();
231    let number_of_instruction_accounts = instruction_context.get_number_of_instruction_accounts();
232
233    // save the account addresses so in case we hit an AccessViolation error we
234    // can map to a more specific error
235    let account_region_addrs = accounts_metadata
236        .iter()
237        .map(|m| {
238            let vm_end = m
239                .vm_data_addr
240                .saturating_add(m.original_data_len as u64)
241                .saturating_add(abi.account_realloc_padding() as u64);
242            m.vm_data_addr..vm_end
243        })
244        .collect::<Vec<_>>();
245
246    #[cfg(feature = "sbpf-debugger")]
247    let (debug_port, debug_metadata) = if invoke_context.debug_port.is_some() {
248        (
249            invoke_context.debug_port,
250            Some(format!(
251                "program_id={};cpi_level={};caller={}",
252                program_id,
253                instruction_context.get_stack_height().saturating_sub(1),
254                invoke_context
255                    .get_stack_height()
256                    .checked_sub(2)
257                    .and_then(|nesting_level| {
258                        transaction_context
259                            .get_instruction_context_at_nesting_level(nesting_level)
260                            .ok()
261                    })
262                    .and_then(|ctx| ctx.get_program_key().ok())
263                    .map(|key| key.to_string())
264                    .unwrap_or_else(|| "none".into())
265            )),
266        )
267    } else {
268        (None, None)
269    };
270
271    let mut create_vm_time = Measure::start("create_vm");
272    unsafe {
273        // SAFETY: The memory pointed to by regions is valid for the useful lifetime of
274        // `invoke_context`, which in turn contains the `MemoryMapping` that allows access to this
275        // memory.
276        set_memory_context(
277            regions,
278            accounts_metadata,
279            invoke_context,
280            executable,
281            virtual_address_space_adjustments,
282            account_data_direct_mapping,
283        )?
284    };
285
286    let execution_result = {
287        let mut execution_mode = ExecutionMode::PreferJit;
288
289        #[cfg(feature = "sbpf-debugger")]
290        if invoke_context.debug_port.is_some() {
291            execution_mode = ExecutionMode::Interpreted;
292        }
293
294        let compute_meter_prev = invoke_context.get_remaining();
295        let mapped_heap_len = invoke_context.get_compute_budget().heap_size as usize;
296        let (mut vm, stack, heap) = unsafe {
297            // SAFETY: The `stack`, `heap` and `executable` live past the lifetime of
298            // `invoke_context`.
299            create_vm!(vm, executable, invoke_context);
300            match vm {
301                Ok(info) => info,
302                Err(e) => {
303                    ic_logger_msg!(log_collector, "Failed to create SBF VM: {}", e);
304                    return Err(Box::new(InstructionError::ProgramEnvironmentSetupFailure));
305                }
306            }
307        };
308
309        create_vm_time.stop();
310        #[cfg(feature = "sbpf-debugger")]
311        {
312            vm.debug_port = debug_port;
313            vm.debug_metadata = debug_metadata;
314        }
315
316        let execute_time = Measure::start("execute");
317        let prev_nested_exec_time = vm.context().total_nested_exec_time;
318
319        vm.registers[1] = ebpf::MM_INPUT_START;
320        vm.registers[2] = instruction_data_offset as u64;
321
322        // SIMD-0683: Pass ABIv1 input metadata via registers r3–r5.
323        if abi == ABI::V1 && pass_input_metadata_in_vm_r3_r5 {
324            vm.registers[3] = instruction_data_len as u64;
325            vm.registers[4] = if let Some(account_pointers_offset) = account_pointers_offset {
326                account_pointers_offset as u64
327            } else {
328                // SIMD-0683 depends on SIMD-0449, which provides the account
329                // pointers array. Since this path only handles ABIv1, the offset
330                // should always be present when SIMD-0683 is enabled so this error
331                // should never happen.
332                ic_logger_msg!(
333                    log_collector,
334                    "Failed to create SBF VM: cannot determine account pointers offset"
335                );
336                return Err(Box::new(InstructionError::ProgramEnvironmentSetupFailure));
337            };
338            vm.registers[5] = number_of_instruction_accounts as u64;
339        }
340
341        let mut call_frames =
342            MEMORY_POOL.with_borrow_mut(|memory_pool| memory_pool.get_call_frames());
343        let (compute_units_consumed, result) =
344            vm.execute_program(executable, &mut execution_mode, &mut call_frames);
345        let register_trace = std::mem::take(&mut vm.register_trace);
346        MEMORY_POOL.with_borrow_mut(|memory_pool| {
347            memory_pool.put_stack(stack);
348            memory_pool.put_heap(heap, mapped_heap_len);
349            memory_pool.put_call_frames(call_frames);
350            debug_assert!(memory_pool.stack_len() <= MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268);
351            debug_assert!(memory_pool.heap_len() <= MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268);
352        });
353        drop(vm);
354        invoke_context.insert_register_trace(register_trace);
355
356        // This section is a little convoluted due to the nested and sibling (CPI) invocations.
357        let total_execute_ns = execute_time.end_as_ns();
358        let nested_execution_time_delta = invoke_context
359            .total_nested_exec_time
360            .saturating_sub(prev_nested_exec_time);
361        let this_call_ns =
362            total_execute_ns.saturating_sub(nested_execution_time_delta.as_nanos() as u64);
363        invoke_context.total_nested_exec_time = invoke_context
364            .total_nested_exec_time
365            .saturating_add(Duration::from_nanos(this_call_ns));
366        let this_call_us = this_call_ns / 1000;
367        invoke_context.timings.execute_us += this_call_us;
368        match execution_mode {
369            ExecutionMode::Interpreted => cache_entry.stats.interpreter_executed(this_call_us),
370            ExecutionMode::Jit => cache_entry.stats.jit_executed(this_call_us),
371            ExecutionMode::PreferJit => { /* not actually executed? */ }
372        }
373
374        ic_logger_msg!(
375            log_collector,
376            "Program {} consumed {} of {} compute units",
377            &program_id,
378            compute_units_consumed,
379            compute_meter_prev
380        );
381        let (_returned_from_program_id, return_data) =
382            invoke_context.transaction_context.get_return_data();
383        if !return_data.is_empty() {
384            stable_log::program_return(&log_collector, &program_id, return_data);
385        }
386        match result {
387            ProgramResult::Ok(status) if status != SUCCESS => {
388                let error: InstructionError = status.into();
389                Err(Box::new(error) as Box<dyn std::error::Error>)
390            }
391            ProgramResult::Err(mut error) => {
392                // Don't clean me up!!
393                // This feature is active on all networks, but we still toggle
394                // it off during fuzzing.
395                if invoke_context
396                    .get_feature_set()
397                    .deplete_cu_meter_on_vm_failure
398                    && !matches!(error, EbpfError::SyscallError(_))
399                {
400                    // when an exception is thrown during the execution of a
401                    // Basic Block (e.g., a null memory dereference or other
402                    // faults), determining the exact number of CUs consumed
403                    // up to the point of failure requires additional effort
404                    // and is unnecessary since these cases are rare.
405                    //
406                    // In order to simplify CU tracking, simply consume all
407                    // remaining compute units so that the block cost
408                    // tracker uses the full requested compute unit cost for
409                    // this failed transaction.
410                    invoke_context.consume(invoke_context.get_remaining());
411                }
412
413                if virtual_address_space_adjustments {
414                    if let EbpfError::SyscallError(err) = error {
415                        error = err
416                            .downcast::<EbpfError>()
417                            .map(|err| *err)
418                            .unwrap_or_else(EbpfError::SyscallError);
419                    }
420                    if let EbpfError::AccessViolation(access_type, vm_addr, len, _section_name) =
421                        error
422                    {
423                        // If virtual_address_space_adjustments is enabled and a program tries to write to a readonly
424                        // region we'll get a memory access violation. Map it to a more specific
425                        // error so it's easier for developers to see what happened.
426                        if let Some((instruction_account_index, vm_addr_range)) =
427                            account_region_addrs
428                                .iter()
429                                .enumerate()
430                                .find(|(_, vm_addr_range)| vm_addr_range.contains(&vm_addr))
431                        {
432                            let transaction_context = &invoke_context.transaction_context;
433                            let instruction_context =
434                                transaction_context.get_current_instruction_context()?;
435                            let account = instruction_context.try_borrow_instruction_account(
436                                instruction_account_index as IndexOfAccount,
437                            )?;
438                            if vm_addr.saturating_add(len) <= vm_addr_range.end {
439                                // The access was within the range of the accounts address space,
440                                // but it might not be within the range of the actual data.
441                                let is_access_outside_of_data = vm_addr
442                                    .saturating_add(len)
443                                    .saturating_sub(vm_addr_range.start)
444                                    as usize
445                                    > account.get_data().len();
446                                error = EbpfError::SyscallError(Box::new(match access_type {
447                                    AccessType::Store => {
448                                        if let Err(err) = account.can_data_be_changed() {
449                                            err
450                                        } else {
451                                            // The store was allowed but failed,
452                                            // thus it must have been an attempt to grow the account.
453                                            debug_assert!(is_access_outside_of_data);
454                                            InstructionError::InvalidRealloc
455                                        }
456                                    }
457                                    AccessType::Load => {
458                                        // Loads should only fail when they are outside of the account data.
459                                        debug_assert!(is_access_outside_of_data);
460                                        if account.can_data_be_changed().is_err() {
461                                            // Load beyond readonly account data happened because the program
462                                            // expected more data than there actually is.
463                                            InstructionError::AccountDataTooSmall
464                                        } else {
465                                            // Load beyond writable account data also attempted to grow.
466                                            InstructionError::InvalidRealloc
467                                        }
468                                    }
469                                }));
470                            }
471                        }
472                    }
473                }
474                Err(if let EbpfError::SyscallError(err) = error {
475                    err
476                } else {
477                    error.into()
478                })
479            }
480            _ => Ok(()),
481        }
482    };
483
484    fn deserialize_parameters(
485        invoke_context: &mut InvokeContext,
486        abi: ABI,
487        parameter_bytes: &[u8],
488        virtual_address_space_adjustments: bool,
489        account_data_direct_mapping: bool,
490    ) -> Result<(), InstructionError> {
491        serialization::deserialize_parameters(
492            &invoke_context
493                .transaction_context
494                .get_current_instruction_context()?,
495            abi,
496            virtual_address_space_adjustments,
497            account_data_direct_mapping,
498            parameter_bytes,
499            &invoke_context
500                .memory_contexts
501                .memory_context_abi_v1()?
502                .accounts_metadata,
503        )
504    }
505
506    let mut deserialize_time = Measure::start("deserialize");
507    let execute_or_deserialize_result = execution_result.and_then(|_| {
508        deserialize_parameters(
509            invoke_context,
510            abi,
511            parameter_bytes.as_slice(),
512            virtual_address_space_adjustments,
513            account_data_direct_mapping,
514        )
515        .map_err(|error| Box::new(error) as Box<dyn std::error::Error>)
516    });
517    deserialize_time.stop();
518
519    // Update the timings
520    invoke_context.timings.serialize_us += serialize_time.as_us();
521    invoke_context.timings.create_vm_us += create_vm_time.as_us();
522    invoke_context.timings.deserialize_us += deserialize_time.as_us();
523
524    execute_or_deserialize_result
525}