Path: blob/main/crates/environ/src/hostcall.rs
1691 views
use crate::BuiltinFunctionIndex;1#[cfg(feature = "component-model")]2use crate::component::ComponentBuiltinFunctionIndex;34/// Enumeration of all possible ways that wasm may execute code in the5/// host.6///7/// This type is intended to be serialized into a 32-bit index (or smaller) and8/// is used by Pulley for example to identify how transitions from the guest to9/// the host are performed.10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]11pub enum HostCall {12/// An "array call" is being done which means that the wasm is calling the13/// host using the array calling convention (e.g. `VMArrayCallNative`).14ArrayCall,1516/// A builtin function, e.g. for `memory.grow`, is being called. Each17/// builtin has its own ABI.18Builtin(BuiltinFunctionIndex),1920/// A lowered component function is being called. This is done by a21/// trampoline generated by Cranelift and is distinct from the array calling22/// convention.23///24/// This correspond to `VMLoweringCallee`.25#[cfg(feature = "component-model")]26ComponentLowerImport,2728/// A builtin function, but specifically for components. For example string29/// transcoders.30#[cfg(feature = "component-model")]31ComponentBuiltin(ComponentBuiltinFunctionIndex),32}3334impl HostCall {35/// Returns a 32-bit index for this hostcall.36pub const fn index(&self) -> u32 {37match self {38HostCall::ArrayCall => 0,39HostCall::Builtin(i) => 1 + i.index(),40#[cfg(feature = "component-model")]41HostCall::ComponentLowerImport => 1 + BuiltinFunctionIndex::len(),42#[cfg(feature = "component-model")]43HostCall::ComponentBuiltin(i) => 2 + BuiltinFunctionIndex::len() + i.index(),44}45}4647/// Create a `HostCall` from the result of an earlier call to48/// `HostCall::index`.49pub fn from_index(index: u32) -> Self {50let host_call = match index {510 => Self::ArrayCall,52_ if index < 1 + BuiltinFunctionIndex::len() => {53Self::Builtin(BuiltinFunctionIndex::from_u32(index - 1))54}55#[cfg(feature = "component-model")]56_ if index == 1 + BuiltinFunctionIndex::len() => Self::ComponentLowerImport,57#[cfg(feature = "component-model")]58_ if index < 2 + BuiltinFunctionIndex::len() + ComponentBuiltinFunctionIndex::len() => {59Self::ComponentBuiltin(ComponentBuiltinFunctionIndex::from_u32(60index - 2 - BuiltinFunctionIndex::len(),61))62}63_ => panic!("bad host call index: {index}"),64};65debug_assert_eq!(index, host_call.index());66host_call67}68}6970impl From<BuiltinFunctionIndex> for HostCall {71fn from(idx: BuiltinFunctionIndex) -> HostCall {72HostCall::Builtin(idx)73}74}7576#[cfg(feature = "component-model")]77impl From<ComponentBuiltinFunctionIndex> for HostCall {78fn from(idx: ComponentBuiltinFunctionIndex) -> HostCall {79HostCall::ComponentBuiltin(idx)80}81}828384