Path: blob/main/crates/environ/src/hostcall.rs
3068 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)]11#[cfg_attr(test, derive(arbitrary::Arbitrary))]12pub enum HostCall {13/// An "array call" is being done which means that the wasm is calling the14/// host using the array calling convention (e.g. `VMArrayCallNative`).15ArrayCall,1617/// A builtin function, e.g. for `memory.grow`, is being called. Each18/// builtin has its own ABI.19Builtin(BuiltinFunctionIndex),2021/// A lowered component function is being called. This is done by a22/// trampoline generated by Cranelift and is distinct from the array calling23/// convention.24///25/// This correspond to `VMLoweringCallee`.26#[cfg(feature = "component-model")]27ComponentLowerImport,2829/// A builtin function, but specifically for components. For example string30/// transcoders.31#[cfg(feature = "component-model")]32ComponentBuiltin(ComponentBuiltinFunctionIndex),33}3435impl HostCall {36/// Returns a 32-bit index for this hostcall.37pub const fn index(&self) -> u32 {38match self {39HostCall::ArrayCall => 0,40HostCall::Builtin(i) => 1 + i.index(),41#[cfg(feature = "component-model")]42HostCall::ComponentLowerImport => 1 + BuiltinFunctionIndex::len(),43#[cfg(feature = "component-model")]44HostCall::ComponentBuiltin(i) => 2 + BuiltinFunctionIndex::len() + i.index(),45}46}4748/// Create a `HostCall` from the result of an earlier call to49/// `HostCall::index`.50pub fn from_index(index: u32) -> Self {51let host_call = match index {520 => Self::ArrayCall,53_ if index < 1 + BuiltinFunctionIndex::len() => {54Self::Builtin(BuiltinFunctionIndex::from_u32(index - 1))55}56#[cfg(feature = "component-model")]57_ if index == 1 + BuiltinFunctionIndex::len() => Self::ComponentLowerImport,58#[cfg(feature = "component-model")]59_ if index < 2 + BuiltinFunctionIndex::len() + ComponentBuiltinFunctionIndex::len() => {60Self::ComponentBuiltin(ComponentBuiltinFunctionIndex::from_u32(61index - 2 - BuiltinFunctionIndex::len(),62))63}64_ => panic!("bad host call index: {index}"),65};66debug_assert_eq!(index, host_call.index());67host_call68}69}7071impl From<BuiltinFunctionIndex> for HostCall {72fn from(idx: BuiltinFunctionIndex) -> HostCall {73HostCall::Builtin(idx)74}75}7677#[cfg(feature = "component-model")]78impl From<ComponentBuiltinFunctionIndex> for HostCall {79fn from(idx: ComponentBuiltinFunctionIndex) -> HostCall {80HostCall::ComponentBuiltin(idx)81}82}838485