Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Consume hostcall fuel in FACT adapters & streams (#15030)

Alex Crichtonb1b352b41637
diff --git a/crates/c-api/include/wasmtime/trap.h b/crates/c-api/include/wasmtime/trap.h
index 3d6c29db5f..d82cec9d8f 100644
--- a/crates/c-api/include/wasmtime/trap.h
+++ b/crates/c-api/include/wasmtime/trap.h
@@ -159,6 +159,9 @@ enum wasmtime_trap_code_enum {
/// `task.return` or `task.cancel` was called by a task which was not
/// created by an `async`-lifted export.
WASMTIME_TRAP_CODE_TASK_RETURN_OR_CANCEL_SYNC_LIFTED = 54,
+ /// More data was copied between the host and the guest, or between two
+ /// guests, than the store's hostcall fuel allows.
+ WASMTIME_TRAP_CODE_HOSTCALL_FUEL_EXHAUSTED = 55,
};
/**
diff --git a/crates/c-api/src/trap.rs b/crates/c-api/src/trap.rs
index 9dd577506b..4907490db9 100644
--- a/crates/c-api/src/trap.rs
+++ b/crates/c-api/src/trap.rs
@@ -61,6 +61,7 @@ const _: () = {
assert!(Trap::WriteToDroppedFuture as u8 == 52);
assert!(Trap::LiftDroppedStream as u8 == 53);
assert!(Trap::TaskReturnOrCancelSyncLifted as u8 == 54);
+ assert!(Trap::HostcallFuelExhausted as u8 == 55);
};
#[repr(C)]
diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rs
index 7a40c012a0..f4145749df 100644
--- a/crates/cranelift/src/compiler/component.rs
+++ b/crates/cranelift/src/compiler/component.rs
@@ -57,6 +57,9 @@ impl From<GetLibcallFn> for HostCallee {
/// How to interpret the results of a host function.
enum HostResult {
+ /// Normal result, can't trap, just returned to wasm.
+ Normal,
+
/// The host function returns the sentinel specified which is interpreted
/// and translated to the real return value.
Sentinel(TrapSentinel),
@@ -689,6 +692,14 @@ impl<'a> TrampolineCompiler<'a> {
let (mut traps, builder) = self.traps();
traps.trap(builder, code);
}
+ Trampoline::HostcallFuel => {
+ self.translate_libcall(
+ host::hostcall_fuel,
+ HostResult::Normal,
+ WasmArgs::InRegisters,
+ |_, _| {},
+ );
+ }
Trampoline::EnterSyncCall => {
self.translate_libcall(
host::enter_sync_call,
@@ -970,6 +981,10 @@ impl<'a> TrampolineCompiler<'a> {
let result_ty = result.map(|v| self.builder.func.dfg.value_type(v));
let expected = self.signature.results();
match host_result.into() {
+ HostResult::Normal => {
+ assert_eq!(expected.len(), 1);
+ self.abi_store_results(&[result.unwrap()]);
+ }
HostResult::Sentinel(TrapSentinel::NegativeOne) => {
assert_eq!(expected.len(), 1);
let (result, result_ty) = (result.unwrap(), result_ty.unwrap());
@@ -1426,6 +1441,7 @@ impl<'a> TrampolineCompiler<'a> {
| Trampoline::StreamTransfer
| Trampoline::ErrorContextTransfer
| Trampoline::Trap(_)
+ | Trampoline::HostcallFuel
| Trampoline::EnterSyncCall
| Trampoline::ExitSyncCall
| Trampoline::Transcoder { .. } => return,
diff --git a/crates/environ/src/component.rs b/crates/environ/src/component.rs
index 6744977589..ce4d320b83 100644
--- a/crates/environ/src/component.rs
+++ b/crates/environ/src/component.rs
@@ -118,6 +118,9 @@ macro_rules! foreach_builtin_component_function {
enter_sync_call(vmctx: vmctx, callee_async: u32, callee_instance: u32) -> bool;
exit_sync_call(vmctx: vmctx) -> bool;
+ // Returns the store's hostcall fuel.
+ hostcall_fuel(vmctx: vmctx) -> u64;
+
#[cfg(feature = "component-model-async")]
backpressure_modify(vmctx: vmctx, caller_instance: u32, increment: u8) -> bool;
#[cfg(feature = "component-model-async")]
diff --git a/crates/environ/src/component/dfg.rs b/crates/environ/src/component/dfg.rs
index e35aa98806..a5f2d1360d 100644
--- a/crates/environ/src/component/dfg.rs
+++ b/crates/environ/src/component/dfg.rs
@@ -482,6 +482,7 @@ pub enum Trampoline {
StreamTransfer,
ErrorContextTransfer,
Trap(Trap),
+ HostcallFuel,
EnterSyncCall,
ExitSyncCall,
ThreadIndex {
@@ -1204,6 +1205,7 @@ impl LinearizeDfg<'_> {
Trampoline::StreamTransfer => info::Trampoline::StreamTransfer,
Trampoline::ErrorContextTransfer => info::Trampoline::ErrorContextTransfer,
Trampoline::Trap(trap) => info::Trampoline::Trap(*trap),
+ Trampoline::HostcallFuel => info::Trampoline::HostcallFuel,
Trampoline::EnterSyncCall => info::Trampoline::EnterSyncCall,
Trampoline::ExitSyncCall => info::Trampoline::ExitSyncCall,
Trampoline::ThreadIndex { instance } => info::Trampoline::ThreadIndex {
diff --git a/crates/environ/src/component/info.rs b/crates/environ/src/component/info.rs
index 7b6df1da7a..d64f869cda 100644
--- a/crates/environ/src/component/info.rs
+++ b/crates/environ/src/component/info.rs
@@ -1133,6 +1133,10 @@ pub enum Trampoline {
/// code.
Trap(Trap),
+ /// An intrinsic used by FACT-generated modules to get the store's hostcall
+ /// fuel, which limits how many bytes of strings the host copies.
+ HostcallFuel,
+
/// An intrinsic used by FACT-generated modules to push a task onto the
/// stack for a sync-to-sync, guest-to-guest call.
EnterSyncCall,
@@ -1265,6 +1269,7 @@ impl Trampoline {
StreamTransfer => format!("stream-transfer"),
ErrorContextTransfer => format!("error-context-transfer"),
Trap(trap) => format!("trap-{}", *trap as u8),
+ HostcallFuel => format!("hostcall-fuel"),
EnterSyncCall => format!("enter-sync-call"),
ExitSyncCall => format!("exit-sync-call"),
ThreadIndex { .. } => format!("thread-index"),
diff --git a/crates/environ/src/component/thread_transparency.rs b/crates/environ/src/component/thread_transparency.rs
index bcb31a460d..47656ed26d 100644
--- a/crates/environ/src/component/thread_transparency.rs
+++ b/crates/environ/src/component/thread_transparency.rs
@@ -311,6 +311,7 @@ fn trampoline_callable(
| StreamTransfer
| ErrorContextTransfer
| Trap(_)
+ | HostcallFuel
| EnterSyncCall
| ExitSyncCall => {
unreachable!("these trampolines do not exist yet")
diff --git a/crates/environ/src/component/translate/adapt.rs b/crates/environ/src/component/translate/adapt.rs
index b2a0cfbfcb..aa60b885cc 100644
--- a/crates/environ/src/component/translate/adapt.rs
+++ b/crates/environ/src/component/translate/adapt.rs
@@ -344,6 +344,7 @@ fn fact_import_to_core_def(
simple_intrinsic(dfg::Trampoline::ErrorContextTransfer)
}
fact::Import::Trap(trap) => simple_intrinsic(dfg::Trampoline::Trap(*trap)),
+ fact::Import::HostcallFuel => simple_intrinsic(dfg::Trampoline::HostcallFuel),
fact::Import::EnterSyncCall => simple_intrinsic(dfg::Trampoline::EnterSyncCall),
fact::Import::ExitSyncCall => simple_intrinsic(dfg::Trampoline::ExitSyncCall),
fact::Import::UnsafeIntrinsic(intrinsic) => {
diff --git a/crates/environ/src/component/types_builder.rs b/crates/environ/src/component/types_builder.rs
index edd64cef9b..4833d38aee 100644
--- a/crates/environ/src/component/types_builder.rs
+++ b/crates/environ/src/component/types_builder.rs
@@ -888,6 +888,11 @@ impl ComponentTypesBuilder {
self.type_information(ty).handles.has_any()
}
+ /// Returns whether the type specified contains a `string` within it.
+ pub fn ty_contains_string(&self, ty: &InterfaceType) -> bool {
+ self.type_information(ty).has_string
+ }
+
/// Returns whether the signature of `ty` mentions any handle, in either its
/// parameters or its results.
pub fn func_contains_any_handle(&self, ty: TypeFuncIndex) -> bool {
@@ -945,7 +950,11 @@ impl ComponentTypesBuilder {
&INFO
}
InterfaceType::String => {
- static INFO: TypeInformation = TypeInformation::string();
+ static INFO: TypeInformation = {
+ let mut info = TypeInformation::string();
+ info.has_string = true;
+ info
+ };
&INFO
}
@@ -1125,6 +1134,9 @@ struct TypeInformation {
/// Which handles this type transitively contains, if any.
handles: Handles,
+
+ /// Whether this type transitively contains a `string`.
+ has_string: bool,
}
impl TypeInformation {
@@ -1132,6 +1144,7 @@ impl TypeInformation {
TypeInformation {
flat: FlatTypesStorage::new(),
handles: Handles::None,
+ has_string: false,
}
}
@@ -1158,6 +1171,7 @@ impl TypeInformation {
fn build_record<'a>(&mut self, types: impl Iterator<Item = &'a TypeInformation>) {
for info in types {
self.handles = Handles::join(self.handles, info.handles);
+ self.has_string |= info.has_string;
match info.flat.as_flat_types() {
Some(types) => {
for (t32, t64) in types.memory32.iter().zip(types.memory64) {
@@ -1199,6 +1213,7 @@ impl TypeInformation {
None => continue,
};
self.handles = Handles::join(self.handles, info.handles);
+ self.has_string |= info.has_string;
// If this variant is already unrepresentable in a flat
// representation then this can be skipped.
@@ -1264,6 +1279,7 @@ impl TypeInformation {
fn fixed_length_lists(&mut self, types: &ComponentTypesBuilder, ty: &TypeFixedLengthList) {
let element_info = types.type_information(&ty.element);
self.handles = element_info.handles;
+ self.has_string = element_info.has_string;
match element_info.flat.as_flat_types() {
Some(types) => {
'outer: for _ in 0..ty.size {
@@ -1319,6 +1335,7 @@ impl TypeInformation {
*self = TypeInformation::string();
let info = types.type_information(&ty.element);
self.handles = info.handles;
+ self.has_string = info.has_string;
}
fn maps(&mut self, types: &ComponentTypesBuilder, ty: &TypeMap) {
@@ -1328,5 +1345,6 @@ impl TypeInformation {
let key_info = types.type_information(&ty.key);
let value_info = types.type_information(&ty.value);
self.handles = Handles::join(key_info.handles, value_info.handles);
+ self.has_string = key_info.has_string || value_info.has_string;
}
}
diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rs
index 0878fa428b..751ce079be 100644
--- a/crates/environ/src/fact.rs
+++ b/crates/environ/src/fact.rs
@@ -100,6 +100,11 @@ pub struct Module<'a> {
imported_enter_sync_call: Option<FuncIndex>,
imported_exit_sync_call: Option<FuncIndex>,
+ imported_hostcall_fuel: Option<FuncIndex>,
+
+ /// Whether any adapter uses the defined global holding the hostcall fuel
+ /// that's remaining for strings copied by the host.
+ hostcall_fuel_global: bool,
/// Cached versions of unsafe intrinsics and where they were imported.
imported_unsafe_intrinsics: HashMap<UnsafeIntrinsic, FuncIndex>,
@@ -303,6 +308,8 @@ impl<'a> Module<'a> {
imported_error_context_transfer: None,
imported_enter_sync_call: None,
imported_exit_sync_call: None,
+ imported_hostcall_fuel: None,
+ hostcall_fuel_global: false,
imported_unsafe_intrinsics: HashMap::new(),
imported_traps: HashMap::new(),
exports: Vec::new(),
@@ -736,6 +743,17 @@ impl<'a> Module<'a> {
)
}
+ fn import_hostcall_fuel(&mut self) -> FuncIndex {
+ self.import_simple(
+ "runtime",
+ "hostcall-fuel",
+ &[],
+ &[ValType::I64],
+ Import::HostcallFuel,
+ |me| &mut me.imported_hostcall_fuel,
+ )
+ }
+
/// Imports the `context.get` intrinsic for the `slot`th context slot.
fn import_context_get(&mut self, slot: usize) -> FuncIndex {
let intrinsic = match slot {
@@ -859,6 +877,14 @@ impl<'a> Module<'a> {
Body::RefFunc(id) => {
Instruction::RefFunc(id_to_index[*id].as_u32()).encode(&mut body);
}
+ Body::HostcallFuelGlobalGet => {
+ let idx = u32::try_from(self.imported_globals.len()).unwrap();
+ Instruction::GlobalGet(idx).encode(&mut body);
+ }
+ Body::HostcallFuelGlobalSet => {
+ let idx = u32::try_from(self.imported_globals.len()).unwrap();
+ Instruction::GlobalSet(idx).encode(&mut body);
+ }
}
}
code.raw(&body);
@@ -868,6 +894,18 @@ impl<'a> Module<'a> {
result.section(&self.core_types.section);
result.section(&self.core_imports);
result.section(&funcs);
+ if self.hostcall_fuel_global {
+ let mut globals = GlobalSection::new();
+ globals.global(
+ GlobalType {
+ val_type: ValType::I64,
+ mutable: true,
+ shared: false,
+ },
+ &ConstExpr::i64_const(0),
+ );
+ result.section(&globals);
+ }
result.section(&exports);
result.section(&code);
result.finish()
@@ -933,6 +971,8 @@ pub enum Import {
ErrorContextTransfer,
/// An intrinsic for trapping the instance with a specific trap code.
Trap(Trap),
+ /// An intrinsic returning the store's hostcall fuel.
+ HostcallFuel,
/// An intrinsic used by FACT-generated modules to check whether an instance
/// may be entered for a sync-to-sync call and push a task onto the stack if
/// so.
@@ -1004,28 +1044,26 @@ struct Function {
/// Representation of a fragment of the body of a core wasm function generated
/// for adapters.
///
-/// This variant comes in one of two flavors:
-///
-/// 1. First a `Raw` variant is used to contain general instructions for the
-/// wasm function. This is populated by `Compiler::instruction` primarily.
-///
-/// 2. A `Call` instruction variant for a `FunctionId` where the final
-/// `FuncIndex` isn't known until emission time.
-///
-/// The purpose of this representation is the `Body::Call` variant. This can't
-/// be encoded as an instruction when it's generated due to not knowing the
-/// final index of the function being called. During `Module::encode`, however,
-/// all indices are known and `Body::Call` is turned into a final
-/// `Instruction::Call`.
+/// The purpose of this representation is to handle relocations sort of. For
+/// example `Body::Call` doesn't actually know the function index being called
+/// until all adapters are generated because generating an adapter may generate
+/// imports which would shift the index space.
///
-/// One other possible representation in the future would be to encode a `Call`
-/// instruction with a 5-byte leb to fill in later, but for now this felt
-/// easier to represent. A 5-byte leb may be more efficient at compile-time if
-/// necessary, however.
+/// One other possible representation in the future would be to encode indexes
+/// with a 5-byte leb to fill in later, but for now this felt easier to
+/// represent. A 5-byte leb may be more efficient at compile-time if necessary,
+/// however.
enum Body {
+ /// Raw wasm opcodes which aren't affected by imports.
Raw(Vec<u8>),
+ /// A wasm `call` instruction to the specified function.
Call(FunctionId),
+ /// A wasm `ref.func` instruction to the specified function.
RefFunc(FunctionId),
+ /// A `global.get` of the hostcall fuel global.
+ HostcallFuelGlobalGet,
+ /// A `global.set` of the hostcall fuel global.
+ HostcallFuelGlobalSet,
}
impl Function {
diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rs
index 06e39b78ba..02051b6938 100644
--- a/crates/environ/src/fact/trampoline.rs
+++ b/crates/environ/src/fact/trampoline.rs
@@ -501,13 +501,8 @@ impl<'a, 'b> Compiler<'a, 'b> {
},
);
- self.flush_code();
- self.module.funcs[self.result]
- .body
- .push(Body::RefFunc(start));
- self.module.funcs[self.result]
- .body
- .push(Body::RefFunc(return_));
+ self.push_body(Body::RefFunc(start));
+ self.push_body(Body::RefFunc(return_));
self.instruction(I32Const(
i32::try_from(adapter.lower.instance.as_u32()).unwrap(),
));
@@ -820,6 +815,7 @@ impl<'a, 'b> Compiler<'a, 'b> {
.iter()
.copied()
.collect::<Vec<_>>();
+ self.init_hostcall_fuel(&src_tys);
let dst_tys = self.types[adapter.lift.ty].params;
let dst_tys = self.types[dst_tys]
.types
@@ -908,6 +904,7 @@ impl<'a, 'b> Compiler<'a, 'b> {
.iter()
.copied()
.collect::<Vec<_>>();
+ self.init_hostcall_fuel(&src_tys);
let dst_tys = self.types[adapter.lower.ty].results;
let dst_tys = self.types[dst_tys]
.types
@@ -1196,8 +1193,7 @@ impl<'a, 'b> Compiler<'a, 'b> {
});
// Emit a `call` instruction which will get "relocated" to a
// function index once translation has completely finished.
- self.flush_code();
- self.module.funcs[self.result].body.push(Body::Call(helper));
+ self.push_body(Body::Call(helper));
// If the destination of the translation was on the stack then
// the types on the stack need to be optionally converted to
@@ -1698,6 +1694,51 @@ impl<'a, 'b> Compiler<'a, 'b> {
self.free_temp_local(dst_str.len);
}
+ /// Resets the hostcall fuel remaining for the strings in `tys` to the
+ /// store's hostcall fuel, if there are any strings.
+ ///
+ /// Strings are the only values the host copies on behalf of an adapter;
+ /// everything else is copied by the adapter's own wasm and charged as
+ /// such.
+ fn init_hostcall_fuel(&mut self, tys: &[InterfaceType]) {
+ if !tys.iter().any(|ty| self.types.ty_contains_string(ty)) {
+ return;
+ }
+ self.module.hostcall_fuel_global = true;
+ let hostcall_fuel = self.module.import_hostcall_fuel();
+ self.instruction(Call(hostcall_fuel.as_u32()));
+ self.push_body(Body::HostcallFuelGlobalSet);
+ }
+
+ /// Charges `src`'s code units at `enc`'s width against the remaining
+ /// hostcall fuel before the host copies it, trapping if there isn't
+ /// enough.
+ fn consume_hostcall_fuel(&mut self, src: &WasmString<'_>, enc: FE) {
+ self.instruction(LocalGet(src.len.idx));
+ if src.len.ty == ValType::I32 {
+ self.instruction(I64ExtendI32U);
+ }
+ if enc.width() > 1 {
+ self.instruction(I64Const(i64::from(enc.width())));
+ self.instruction(I64Mul);
+ }
+ let bytes = self.local_set_new_tmp(ValType::I64);
+
+ self.instruction(LocalGet(bytes.idx));
+ self.push_body(Body::HostcallFuelGlobalGet);
+ self.instruction(I64GtU);
+ self.instruction(If(BlockType::Empty));
+ self.trap(Trap::HostcallFuelExhausted);
+ self.instruction(End);
+
+ self.push_body(Body::HostcallFuelGlobalGet);
+ self.instruction(LocalGet(bytes.idx));
+ self.instruction(I64Sub);
+ self.push_body(Body::HostcallFuelGlobalSet);
+
+ self.free_temp_local(bytes);
+ }
+
// Corresponding function for `store_string_copy` in the spec.
//
// This performs a transcoding of the string with a one-pass copy from
@@ -2325,7 +2366,8 @@ impl<'a, 'b> Compiler<'a, 'b> {
}
fn validate_string_length(&mut self, src: &WasmString<'_>, dst: FE) {
- self.validate_string_length_u8(src, dst.width())
+ self.validate_string_length_u8(src, dst.width());
+ self.consume_hostcall_fuel(src, dst);
}
fn validate_string_length_u8(&mut self, s: &WasmString<'_>, dst: u8) {
@@ -3942,6 +3984,12 @@ impl<'a, 'b> Compiler<'a, 'b> {
self.instruction(End);
}
+ /// Pushes a `Body` fragment directly to the function being created.
+ fn push_body(&mut self, body: Body) {
+ self.flush_code();
+ self.module.funcs[self.result].body.push(body);
+ }
+
/// Flushes out the current `code` instructions into the destination
/// function.
///
diff --git a/crates/environ/src/trap_encoding.rs b/crates/environ/src/trap_encoding.rs
index 2346cfef04..8c2dee567f 100644
--- a/crates/environ/src/trap_encoding.rs
+++ b/crates/environ/src/trap_encoding.rs
@@ -299,6 +299,10 @@ generate_trap_type! {
/// created by an `async`-lifted export.
TaskReturnOrCancelSyncLifted = "`task.return` or `task.cancel` called by a task which was not lifted with `async`",
+ /// More data was copied between the host and the guest, or between
+ /// two guests, than the store's hostcall fuel allows.
+ HostcallFuelExhausted = "too much data is being copied between the host and the guest: fuel allocated for hostcalls has been exhausted",
+
// if adding a variant here be sure to update `trap.rs` and `trap.h` as
// mentioned above
}
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index baa7967768..dae06a4602 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -3474,7 +3474,13 @@ impl Instance {
Some(ty) => ty,
None => bail_bug!("expected read payload type to be present"),
};
- if flat_abi.is_some() {
+ let lift =
+ &mut LiftContext::new(store.store_opaque_mut(), write_options, write_instance)?;
+ if let Some(abi) = flat_abi {
+ // The host copies these bytes itself rather than wasm, so
+ // charge them against hostcall fuel.
+ lift.consume_fuel_array(count, usize::try_from(abi.size)?)?;
+
// Fast path memcpy for "flat" (i.e. no pointers or handles) payloads:
let store_opaque = store.store_opaque_mut();
@@ -3514,8 +3520,6 @@ impl Instance {
}
}
} else {
- let store_opaque = store.store_opaque_mut();
- let lift = &mut LiftContext::new(store_opaque, write_options, write_instance)?;
let bytes = &lift.memory()[write_address..][..write_length_in_bytes];
lift.consume_fuel_array(count, size_of::<Val>())?;
diff --git a/crates/wasmtime/src/runtime/component/func/options.rs b/crates/wasmtime/src/runtime/component/func/options.rs
index 57163105cc..e4d706685f 100644
--- a/crates/wasmtime/src/runtime/component/func/options.rs
+++ b/crates/wasmtime/src/runtime/component/func/options.rs
@@ -12,7 +12,6 @@ use crate::runtime::vm::component::{
use crate::runtime::vm::{UncaughtException, VMFuncRef};
use crate::store::{StoreId, StoreOpaque};
use alloc::sync::Arc;
-use core::fmt;
use core::pin::Pin;
use core::ptr::NonNull;
use wasmtime_environ::component::{
@@ -533,7 +532,7 @@ impl<'a> LiftContext<'a> {
pub fn consume_fuel(&mut self, amt: usize) -> Result<()> {
match self.hostcall_fuel.checked_sub(amt) {
Some(new) => self.hostcall_fuel = new,
- None => bail!(HostcallFuelExhausted),
+ None => bail!(crate::Trap::HostcallFuelExhausted),
}
Ok(())
}
@@ -543,22 +542,7 @@ impl<'a> LiftContext<'a> {
pub fn consume_fuel_array(&mut self, len: usize, size: usize) -> Result<()> {
match len.checked_mul(size) {
Some(bytes) => self.consume_fuel(bytes),
- None => bail!(HostcallFuelExhausted),
+ None => bail!(crate::Trap::HostcallFuelExhausted),
}
}
}
-
-#[derive(Debug)]
-struct HostcallFuelExhausted;
-
-impl fmt::Display for HostcallFuelExhausted {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "too much data is being copied between the host and the guest: \
- fuel allocated for hostcalls has been exhausted"
- )
- }
-}
-
-impl core::error::Error for HostcallFuelExhausted {}
diff --git a/crates/wasmtime/src/runtime/vm/component/libcalls.rs b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
index 3319476598..59e596db05 100644
--- a/crates/wasmtime/src/runtime/vm/component/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
@@ -690,6 +690,10 @@ fn enter_sync_call(
)
}
+fn hostcall_fuel(store: &mut dyn VMStore, _: Instance) -> u64 {
+ u64::try_from(store.hostcall_fuel()).unwrap_or(u64::MAX)
+}
+
fn exit_sync_call(store: &mut dyn VMStore, instance: Instance) -> Result<()> {
store
.component_resource_tables(Some(instance))?
diff --git a/crates/wast/src/wast.rs b/crates/wast/src/wast.rs
index 7462a36cc5..b242539722 100644
--- a/crates/wast/src/wast.rs
+++ b/crates/wast/src/wast.rs
@@ -271,6 +271,12 @@ impl WastContext {
store.as_context_mut().gc(None)?;
Ok(())
})?;
+ i.func_wrap("set-hostcall-fuel", |mut store, (fuel,): (u64,)| {
+ store
+ .as_context_mut()
+ .set_hostcall_fuel(usize::try_from(fuel).unwrap_or(usize::MAX));
+ Ok(())
+ })?;
}
Ok(())
}
diff --git a/tests/misc_testsuite/component-model/async/hostcall-fuel-stream.wast b/tests/misc_testsuite/component-model/async/hostcall-fuel-stream.wast
new file mode 100644
index 0000000000..7a308d5581
--- /dev/null
+++ b/tests/misc_testsuite/component-model/async/hostcall-fuel-stream.wast
@@ -0,0 +1,66 @@
+;;! component_model_async = true
+
+;; A `stream<u8>` write that completes a pending read is copied by the host, so
+;; it's limited by the store's hostcall fuel. This runs with exactly the fuel a
+;; 64 KiB copy needs and then traps with one byte less.
+
+(component definition $stream
+ (import "wasmtime" (instance $wasmtime
+ (export "set-hostcall-fuel" (func (param "fuel" u64)))
+ ))
+ (core module $libc (memory (export "mem") 2))
+ (core instance $libc (instantiate $libc))
+ (type $s (stream u8))
+ (core func $stream.new (canon stream.new $s))
+ (core func $stream.read
+ (canon stream.read $s async (memory (core memory $libc "mem"))))
+ (core func $stream.write
+ (canon stream.write $s async (memory (core memory $libc "mem"))))
+ (core func $stream.cancel-read (canon stream.cancel-read $s))
+ (core module $m
+ (import "" "stream.new" (func $stream.new (result i64)))
+ (import "" "stream.read"
+ (func $stream.read (param i32 i32 i32) (result i32)))
+ (import "" "stream.write"
+ (func $stream.write (param i32 i32 i32) (result i32)))
+ (import "" "stream.cancel-read"
+ (func $stream.cancel-read (param i32) (result i32)))
+ (func (export "run")
+ (local $pair i64)
+ (local $r i32)
+ (local $w i32)
+ (local.set $pair (call $stream.new))
+ (local.set $r (i32.wrap_i64 (local.get $pair)))
+ (local.set $w (i32.wrap_i64 (i64.shr_u (local.get $pair) (i64.const 32))))
+ ;; BLOCKED
+ (if (i32.ne (call $stream.read (local.get $r) (i32.const 0) (i32.const 65536))
+ (i32.const -1))
+ (then unreachable))
+ ;; (65536 << 4) | COMPLETED
+ (if (i32.ne (call $stream.write (local.get $w) (i32.const 65536) (i32.const 65536))
+ (i32.const 0x100000))
+ (then unreachable))
+ ;; collect the read's completion so the task can exit
+ (drop (call $stream.cancel-read (local.get $r)))))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "stream.new" (func $stream.new))
+ (export "stream.read" (func $stream.read))
+ (export "stream.write" (func $stream.write))
+ (export "stream.cancel-read" (func $stream.cancel-read))))))
+ (core func $set-hostcall-fuel (canon lower (func $wasmtime "set-hostcall-fuel")))
+ (core module $fuel
+ (import "" "set" (func $set (param i64)))
+ (func (export "set") (param i64) (call $set (local.get 0))))
+ (core instance $fuel (instantiate $fuel
+ (with "" (instance (export "set" (func $set-hostcall-fuel))))))
+ (func (export "set-hostcall-fuel") (param "fuel" u64)
+ (canon lift (core func $fuel "set")))
+ (func (export "run") (canon lift (core func $i "run"))))
+
+(component instance $i $stream)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65536)))
+(assert_return (invoke "run"))
+(component instance $i $stream)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65535)))
+(assert_trap (invoke "run") "fuel allocated for hostcalls has been exhausted")
diff --git a/tests/misc_testsuite/component-model/big-strings.wast b/tests/misc_testsuite/component-model/big-strings.wast
index b31a47c7a5..53d29bc58d 100644
--- a/tests/misc_testsuite/component-model/big-strings.wast
+++ b/tests/misc_testsuite/component-model/big-strings.wast
@@ -12,6 +12,21 @@
;; should happen but eventually `realloc` will fail-fast before any real
;; transcoding. Memory growth is assumed to be VM-based and thus quite fast.
(component definition $A
+ ;; These strings are far larger than the default hostcall fuel allows, so
+ ;; raise it to the maximum while instantiating.
+ (import "wasmtime" (instance $wasmtime
+ (export "set-hostcall-fuel" (func (param "fuel" u64)))
+ ))
+ (core func $set-hostcall-fuel (canon lower (func $wasmtime "set-hostcall-fuel")))
+ (core module $max-hostcall-fuel
+ (import "" "set-hostcall-fuel" (func $set-hostcall-fuel (param i64)))
+ (func $start (call $set-hostcall-fuel (i64.const -1)))
+ (start $start)
+ )
+ (core instance (instantiate $max-hostcall-fuel
+ (with "" (instance (export "set-hostcall-fuel" (func $set-hostcall-fuel))))
+ ))
+
(component $A
(core module $m
(memory (export "m") 1)
diff --git a/tests/misc_testsuite/component-model/hostcall-fuel-strings.wast b/tests/misc_testsuite/component-model/hostcall-fuel-strings.wast
new file mode 100644
index 0000000000..ef192dbb5f
--- /dev/null
+++ b/tests/misc_testsuite/component-model/hostcall-fuel-strings.wast
@@ -0,0 +1,142 @@
+;;! multi_memory = true
+
+;; Strings passed between components are copied by the host, so they're
+;; limited by the store's hostcall fuel. Each test below runs with exactly the
+;; fuel it needs and then traps with one byte less.
+
+;; `$b` passes a 64 KiB string to `$a`.
+(component definition $one-string
+ (import "wasmtime" (instance $wasmtime
+ (export "set-hostcall-fuel" (func (param "fuel" u64)))
+ ))
+ (component $a
+ (core module $m
+ (memory (export "mem") 1)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)
+ (func (export "f") (param i32 i32)))
+ (core instance $i (instantiate $m))
+ (func (export "f") (param "s" string)
+ (canon lift (core func $i "f") (memory (core memory $i "mem"))
+ (realloc (core func $i "realloc")))))
+ (component $b
+ (import "f" (func $f (param "s" string)))
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core func $f (canon lower (func $f) (memory (core memory $libc "mem"))))
+ (core module $m
+ (import "" "f" (func $f (param i32 i32)))
+ (func (export "run") (call $f (i32.const 0) (i32.const 65536))))
+ (core instance $i (instantiate $m (with "" (instance (export "f" (func $f))))))
+ (func (export "run") (canon lift (core func $i "run"))))
+ (instance $a (instantiate $a))
+ (instance $b (instantiate $b (with "f" (func $a "f"))))
+ (core func $set-hostcall-fuel (canon lower (func $wasmtime "set-hostcall-fuel")))
+ (core module $fuel
+ (import "" "set" (func $set (param i64)))
+ (func (export "set") (param i64) (call $set (local.get 0))))
+ (core instance $fuel (instantiate $fuel
+ (with "" (instance (export "set" (func $set-hostcall-fuel))))))
+ (func (export "set-hostcall-fuel") (param "fuel" u64)
+ (canon lift (core func $fuel "set")))
+ (export "run" (func $b "run")))
+
+(component instance $i $one-string)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65536)))
+(assert_return (invoke "run"))
+(component instance $i $one-string)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65535)))
+(assert_trap (invoke "run") "fuel allocated for hostcalls has been exhausted")
+
+;; `$b` passes two 64 KiB strings to `$a` in one call, which share one budget.
+(component definition $two-strings
+ (import "wasmtime" (instance $wasmtime
+ (export "set-hostcall-fuel" (func (param "fuel" u64)))
+ ))
+ (component $a
+ (core module $m
+ (memory (export "mem") 1)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)
+ (func (export "f") (param i32 i32 i32 i32)))
+ (core instance $i (instantiate $m))
+ (func (export "f") (param "s1" string) (param "s2" string)
+ (canon lift (core func $i "f") (memory (core memory $i "mem"))
+ (realloc (core func $i "realloc")))))
+ (component $b
+ (import "f" (func $f (param "s1" string) (param "s2" string)))
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core func $f (canon lower (func $f) (memory (core memory $libc "mem"))))
+ (core module $m
+ (import "" "f" (func $f (param i32 i32 i32 i32)))
+ (func (export "run")
+ (call $f (i32.const 0) (i32.const 65536) (i32.const 0) (i32.const 65536))))
+ (core instance $i (instantiate $m (with "" (instance (export "f" (func $f))))))
+ (func (export "run") (canon lift (core func $i "run"))))
+ (instance $a (instantiate $a))
+ (instance $b (instantiate $b (with "f" (func $a "f"))))
+ (core func $set-hostcall-fuel (canon lower (func $wasmtime "set-hostcall-fuel")))
+ (core module $fuel
+ (import "" "set" (func $set (param i64)))
+ (func (export "set") (param i64) (call $set (local.get 0))))
+ (core instance $fuel (instantiate $fuel
+ (with "" (instance (export "set" (func $set-hostcall-fuel))))))
+ (func (export "set-hostcall-fuel") (param "fuel" u64)
+ (canon lift (core func $fuel "set")))
+ (export "run" (func $b "run")))
+
+(component instance $i $two-strings)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 131072)))
+(assert_return (invoke "run"))
+(component instance $i $two-strings)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 131071)))
+(assert_trap (invoke "run") "fuel allocated for hostcalls has been exhausted")
+
+;; `$b` passes a 64 KiB string to `$a`, which returns a 64 KiB string. Params and
+;; results each get their own budget.
+(component definition $roundtrip
+ (import "wasmtime" (instance $wasmtime
+ (export "set-hostcall-fuel" (func (param "fuel" u64)))
+ ))
+ (component $a
+ (core module $m
+ (memory (export "mem") 2)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)
+ (func (export "f") (param i32 i32) (result i32)
+ (i32.store (i32.const 65536) (i32.const 0))
+ (i32.store (i32.const 65540) (i32.const 65536))
+ i32.const 65536))
+ (core instance $i (instantiate $m))
+ (func (export "f") (param "s" string) (result string)
+ (canon lift (core func $i "f") (memory (core memory $i "mem"))
+ (realloc (core func $i "realloc")))))
+ (component $b
+ (import "f" (func $f (param "s" string) (result string)))
+ (core module $libc
+ (memory (export "mem") 2)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0))
+ (core instance $libc (instantiate $libc))
+ (core func $f (canon lower (func $f) (memory (core memory $libc "mem"))
+ (realloc (core func $libc "realloc"))))
+ (core module $m
+ (import "" "f" (func $f (param i32 i32 i32)))
+ (func (export "run") (call $f (i32.const 0) (i32.const 65536) (i32.const 65536))))
+ (core instance $i (instantiate $m (with "" (instance (export "f" (func $f))))))
+ (func (export "run") (canon lift (core func $i "run"))))
+ (instance $a (instantiate $a))
+ (instance $b (instantiate $b (with "f" (func $a "f"))))
+ (core func $set-hostcall-fuel (canon lower (func $wasmtime "set-hostcall-fuel")))
+ (core module $fuel
+ (import "" "set" (func $set (param i64)))
+ (func (export "set") (param i64) (call $set (local.get 0))))
+ (core instance $fuel (instantiate $fuel
+ (with "" (instance (export "set" (func $set-hostcall-fuel))))))
+ (func (export "set-hostcall-fuel") (param "fuel" u64)
+ (canon lift (core func $fuel "set")))
+ (export "run" (func $b "run")))
+
+(component instance $i $roundtrip)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65536)))
+(assert_return (invoke "run"))
+(component instance $i $roundtrip)
+(assert_return (invoke "set-hostcall-fuel" (u64.const 65535)))
+(assert_trap (invoke "run") "fuel allocated for hostcalls has been exhausted")