Skip to content

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

Add component support for unknown imports returning default values (#14746)

Nick Fitzgerald3c4c9651687c
diff --git a/crates/c-api/include/wasmtime/component/linker.h b/crates/c-api/include/wasmtime/component/linker.h
index aa6f76aa98..305a939995 100644
--- a/crates/c-api/include/wasmtime/component/linker.h
+++ b/crates/c-api/include/wasmtime/component/linker.h
@@ -84,6 +84,18 @@ WASM_API_EXTERN wasmtime_error_t *
wasmtime_component_linker_define_unknown_imports_as_traps(
wasmtime_component_linker_t *linker, const wasmtime_component_t *component);
+/**
+ * \brief Defines all unknown imports of `component` as functions which return
+ * default values.
+ *
+ * An import whose results have no default, such as a `future`, is defined as a
+ * trapping function instead.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_component_linker_define_unknown_imports_as_default_values(
+ wasmtime_component_linker_t *linker, wasmtime_context_t *store,
+ const wasmtime_component_t *component);
+
/**
* \brief Deletes a #wasmtime_component_linker_t created by
* #wasmtime_component_linker_new
diff --git a/crates/c-api/include/wasmtime/component/linker.hh b/crates/c-api/include/wasmtime/component/linker.hh
index b65ff8639b..6307703471 100644
--- a/crates/c-api/include/wasmtime/component/linker.hh
+++ b/crates/c-api/include/wasmtime/component/linker.hh
@@ -181,6 +181,24 @@ class Linker {
return std::monostate();
}
+ /**
+ * \brief Defines all unknown imports of `component` as functions which
+ * return default values.
+ *
+ * An import whose results have no default, such as a `future`, is defined
+ * as a trapping function instead.
+ */
+ Result<std::monostate>
+ define_unknown_imports_as_default_values(Store::Context cx,
+ const Component &component) {
+ auto err =
+ wasmtime_component_linker_define_unknown_imports_as_default_values(
+ ptr.get(), cx.capi(), component.capi());
+ if (err)
+ return Error(err);
+ return std::monostate();
+ }
+
/// Configures whether shadowing previous names is allowed or not.
///
/// By default shadowing is not allowed.
diff --git a/crates/c-api/src/component/linker.rs b/crates/c-api/src/component/linker.rs
index e4714f769c..18c3ea37a0 100644
--- a/crates/c-api/src/component/linker.rs
+++ b/crates/c-api/src/component/linker.rs
@@ -309,6 +309,18 @@ pub unsafe extern "C" fn wasmtime_component_linker_define_unknown_imports_as_tra
crate::handle_result(result, |_| ())
}
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_component_linker_define_unknown_imports_as_default_values(
+ linker: &mut wasmtime_component_linker_t,
+ store: WasmtimeStoreContextMut<'_>,
+ component: &wasmtime_component_t,
+) -> Option<Box<wasmtime_error_t>> {
+ let result = linker
+ .linker
+ .define_unknown_imports_as_default_values(store, &component.component);
+ crate::handle_result(result, |_| ())
+}
+
pub type wasmtime_component_resource_destructor_t =
extern "C" fn(*mut c_void, WasmtimeStoreContextMut<'_>, u32) -> Option<Box<wasmtime_error_t>>;
diff --git a/crates/c-api/tests/component/linker.cc b/crates/c-api/tests/component/linker.cc
index c928aa7999..012c6905dd 100644
--- a/crates/c-api/tests/component/linker.cc
+++ b/crates/c-api/tests/component/linker.cc
@@ -88,3 +88,21 @@ TEST(Linker, unknown_imports_trap) {
EXPECT_TRUE(linker.define_unknown_imports_as_traps(c));
EXPECT_TRUE(linker.instantiate(store, c));
}
+
+TEST(Linker, unknown_imports_default_values) {
+ wasmtime::Engine engine;
+ Linker linker(engine);
+ wasmtime::Store store(engine);
+
+ auto c = Component::compile(engine, R"(
+ (component
+ (import "a" (func (result u32)))
+ )
+ )")
+ .unwrap();
+
+ EXPECT_FALSE(linker.instantiate(store, c));
+ EXPECT_TRUE(
+ linker.define_unknown_imports_as_default_values(store.context(), c));
+ EXPECT_TRUE(linker.instantiate(store, c));
+}
diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rs
index bdfdd21ed3..38de9cb5d5 100644
--- a/crates/wasmtime/src/runtime/component/linker.rs
+++ b/crates/wasmtime/src/runtime/component/linker.rs
@@ -355,7 +355,42 @@ impl<T: 'static> Linker<T> {
/// memory allocation fails. See the `OutOfMemory` type's documentation for
/// details on Wasmtime's out-of-memory handling.
pub fn define_unknown_imports_as_traps(&mut self, component: &Component) -> Result<()> {
- // Recursively stub out all imports of the component with a function that traps.
+ self.define_unknown_imports(component, StubKind::Trap)
+ }
+
+ /// Implement any imports of the given [`Component`] with functions which
+ /// ignore their arguments and return default values.
+ ///
+ /// By default a [`Linker`] will error when unknown imports are encountered
+ /// when instantiating a [`Component`]. This changes that behavior from an
+ /// instant error to returning defaults when the import is called. See
+ /// [`Type::default_value`](crate::component::types::Type::default_value)
+ /// for what each type defaults to.
+ ///
+ /// Values are built when the import is called, not here, as a handle's
+ /// type depends on the instance it is flowing into.
+ ///
+ /// Not every result has a default: a `future`, `stream`, or
+ /// `error-context`, or a guest-defined resource, has none. Such an import
+ /// is still defined, but traps when called rather than preventing
+ /// instantiation, so a component which never calls it can still be run.
+ ///
+ /// # Errors
+ ///
+ /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
+ /// memory allocation fails. See the `OutOfMemory` type's documentation for
+ /// details on Wasmtime's out-of-memory handling.
+ pub fn define_unknown_imports_as_default_values(
+ &mut self,
+ _store: impl AsContextMut<Data = T>,
+ component: &Component,
+ ) -> Result<()> {
+ self.define_unknown_imports(component, StubKind::DefaultValue)
+ }
+
+ /// Stub out all of `component`'s undefined imports.
+ fn define_unknown_imports(&mut self, component: &Component, kind: StubKind) -> Result<()> {
+ // Recursively stub out all imports of the component.
use wasmtime_environ::component::{ComponentTypes, ResourceIndex, TypeDef};
fn stub_item<T>(
@@ -364,7 +399,8 @@ impl<T: 'static> Linker<T> {
item_name: &str,
item_def: &TypeDef,
parent_instance: Option<&str>,
- types: &ComponentTypes,
+ types: &Arc<ComponentTypes>,
+ kind: StubKind,
) -> Result<()> {
// The first definition of a resource needs to be present, but all other future
// references to the same resource are aliases of the original resource definition.
@@ -405,27 +441,45 @@ impl<T: 'static> Linker<T> {
// `func_new` (only a sync-typed import can) — see
// `typecheck_async`'s doc comment. Stub it with
// `func_new_concurrent` instead so unsatisfied async
- // imports can be stubbed-as-traps too, not just sync
+ // imports can be stubbed too, not just sync
// ones; if concurrency support isn't enabled there's no
// way to stub it here, so fall through to `func_new` and
// let instantiation fail with that same explanatory
// error.
#[cfg(feature = "component-model-async")]
if types[*_func_idx].async_ && linker.engine.tunables().concurrency_support {
- linker.func_new_concurrent(&item_name, move |_, _, _, _| {
+ linker.func_new_concurrent(&item_name, move |accessor, ty, params, results| {
let fully_qualified_name = fully_qualified_name.try_clone();
Box::pin(async move {
let fully_qualified_name = fully_qualified_name?;
- bail!(
- "unknown import: `{fully_qualified_name}` has not been defined"
- )
+ match kind {
+ StubKind::Trap => bail!(
+ "unknown import: `{fully_qualified_name}` has not been defined"
+ ),
+ StubKind::DefaultValue => accessor
+ .with(|store| fill_defaults(store, &ty, params, results))
+ .with_context(|| {
+ format_err!(
+ "unknown import: `{fully_qualified_name}` has no \
+ default value"
+ )
+ }),
+ }
})
})?;
return Ok(());
}
- linker.func_new(&item_name, move |_, _, _, _| {
- bail!("unknown import: `{fully_qualified_name}` has not been defined")
+ linker.func_new(&item_name, move |store, ty, params, results| match kind {
+ StubKind::Trap => {
+ bail!("unknown import: `{fully_qualified_name}` has not been defined")
+ }
+ StubKind::DefaultValue => fill_defaults(store, &ty, params, results)
+ .with_context(|| {
+ format_err!(
+ "unknown import: `{fully_qualified_name}` has no default value"
+ )
+ }),
})?;
}
TypeDef::ComponentInstance(i) => {
@@ -439,6 +493,7 @@ impl<T: 'static> Linker<T> {
&export.ty,
Some(item_name),
types,
+ kind,
)?;
}
}
@@ -447,7 +502,11 @@ impl<T: 'static> Linker<T> {
linker.resource(item_name, ty, |_, _| Ok(()))?;
}
TypeDef::Component(_) | TypeDef::Module(_) => {
- bail!("unable to define {} imports as traps", item_def.desc())
+ bail!(
+ "unable to define {} imports as {}",
+ item_def.desc(),
+ kind.desc()
+ )
}
_ => {}
}
@@ -464,12 +523,126 @@ impl<T: 'static> Linker<T> {
&import_type.ty,
None,
component.types(),
+ kind,
)?;
}
Ok(())
}
}
+/// Which flavor of stub `Linker::define_unknown_imports` installs.
+#[derive(Copy, Clone)]
+enum StubKind {
+ /// Stubs trap when called.
+ Trap,
+ /// Stubs return default values; see
+ /// `Linker::define_unknown_imports_as_default_values`.
+ DefaultValue,
+}
+
+impl StubKind {
+ /// A human readable description, for error messages.
+ fn desc(&self) -> &'static str {
+ match self {
+ StubKind::Trap => "traps",
+ StubKind::DefaultValue => "default values",
+ }
+ }
+}
+
+/// Drop every handle within `params`.
+fn drop_params(mut store: impl AsContextMut, params: &[Val]) -> Result<()> {
+ let mut store = store.as_context_mut();
+ for param in params {
+ drop_val(store.as_context_mut(), param)?;
+ }
+ Ok(())
+}
+
+/// Drop every handle within `val`.
+fn drop_val<T>(mut store: StoreContextMut<'_, T>, val: &Val) -> Result<()> {
+ match val {
+ // Drop through the internal entry point rather than the public
+ // `resource_drop`: this runs while servicing a guest call on a fiber,
+ // where `resource_drop`'s `validate_sync_call` check would reject the
+ // drop with "cannot do blocking `call` from an async context".
+ Val::Resource(resource) => resource.resource_drop_in_guest_call(&mut store)?,
+
+ // Without `component-model-async` these are uninhabited, so there is
+ // nothing to close.
+ #[cfg(feature = "component-model-async")]
+ Val::Future(future) => future.clone().close(&mut store)?,
+ #[cfg(feature = "component-model-async")]
+ Val::Stream(stream) => stream.clone().close(&mut store)?,
+ #[cfg(not(feature = "component-model-async"))]
+ Val::Future(_) | Val::Stream(_) => {}
+
+ Val::List(vals) | Val::Tuple(vals) | Val::FixedLengthList(vals) => {
+ for val in vals {
+ drop_val(store.as_context_mut(), val)?;
+ }
+ }
+ Val::Record(fields) => {
+ for (_, val) in fields {
+ drop_val(store.as_context_mut(), val)?;
+ }
+ }
+ Val::Map(entries) => {
+ for (key, val) in entries {
+ drop_val(store.as_context_mut(), key)?;
+ drop_val(store.as_context_mut(), val)?;
+ }
+ }
+ Val::Variant(_, Some(val)) | Val::Option(Some(val)) => {
+ drop_val(store.as_context_mut(), val)?
+ }
+ Val::Result(Ok(Some(val)) | Err(Some(val))) => drop_val(store.as_context_mut(), val)?,
+
+ // Lifting an `error-context` reads its representation without taking
+ // ownership of a handle, so there is nothing to drop.
+ Val::ErrorContext(_) => {}
+
+ Val::Bool(_)
+ | Val::S8(_)
+ | Val::U8(_)
+ | Val::S16(_)
+ | Val::U16(_)
+ | Val::S32(_)
+ | Val::U32(_)
+ | Val::S64(_)
+ | Val::U64(_)
+ | Val::Float32(_)
+ | Val::Float64(_)
+ | Val::Char(_)
+ | Val::String(_)
+ | Val::Enum(_)
+ | Val::Flags(_)
+ | Val::Variant(_, None)
+ | Val::Option(None)
+ | Val::Result(Ok(None) | Err(None)) => {}
+ }
+ Ok(())
+}
+
+/// Write a default value for each of `ty`'s results into `results`, after
+/// disposing of `params`.
+///
+/// `ty` comes from the call itself rather than from the linker, so its `own`
+/// and `borrow` types are those of the instance being called, which is what
+/// makes the handles this produces pass the guest's type check.
+fn fill_defaults(
+ mut store: impl AsContextMut,
+ ty: &types::ComponentFunc,
+ params: &[Val],
+ results: &mut [Val],
+) -> Result<()> {
+ drop_params(&mut store, params)?;
+ for (slot, ty) in results.iter_mut().zip(ty.results()) {
+ *slot = ty.default_value(&mut store)?;
+ }
+ Ok(())
+}
+
impl<T: 'static> LinkerInstance<'_, T> {
fn as_mut(&mut self) -> LinkerInstance<'_, T> {
LinkerInstance {
diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rs
index 7a2f3c696a..c320aee10a 100644
--- a/crates/wasmtime/src/runtime/component/resources/any.rs
+++ b/crates/wasmtime/src/runtime/component/resources/any.rs
@@ -130,6 +130,35 @@ impl ResourceAny {
resource.try_into_resource_any(store)
}
+ /// Creates a new owned resource of type `ty` with the `rep` specified.
+ ///
+ /// Unlike `try_from_resource`, which derives the resource type from a Rust
+ /// type parameter, this takes the type dynamically. It is used to
+ /// synthesize a handle whose type is only known at runtime, such as a
+ /// default value for an `own` result; see
+ /// `Linker::define_unknown_imports_as_default_values`.
+ ///
+ /// No destructor is attached.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if `ty` is not host-defined. A guest resource's
+ /// representation belongs to the guest that defines it, so the host
+ /// cannot conjure an instance of one.
+ pub(crate) fn new_own_dynamic(
+ ty: ResourceType,
+ rep: u32,
+ mut store: impl AsContextMut,
+ ) -> Result<Self> {
+ if !ty.is_host_defined() {
+ bail!("cannot synthesize a resource of a non-host-defined type");
+ }
+ let store = store.as_context_mut();
+ let idx =
+ HostResourceTables::new_host(store.0)?.host_resource_lower_own(rep, None, None)?;
+ Ok(ResourceAny::new(idx, ty, true))
+ }
+
/// Attempts to convert this value into a statically typed, host-defined
/// [`Resource`].
///
@@ -247,6 +276,23 @@ impl ResourceAny {
self.resource_drop_impl(&mut store)
}
+ /// Drops this resource without the `validate_sync_call` check that the
+ /// public [`ResourceAny::resource_drop`] performs.
+ ///
+ /// This is for dropping handles that are already owned by the host while it
+ /// is servicing a guest call, such as the parameters handed to an unknown
+ /// import stubbed by
+ /// [`Linker::define_unknown_imports_as_default_values`](crate::component::Linker::define_unknown_imports_as_default_values).
+ /// Such a stub always runs on a fiber, where `validate_sync_call` would
+ /// reject the public entry point even though the drop itself is the same
+ /// bookkeeping the runtime does whenever a guest drops a handle mid-call.
+ pub(crate) fn resource_drop_in_guest_call<T: 'static>(
+ self,
+ store: &mut StoreContextMut<'_, T>,
+ ) -> Result<()> {
+ self.resource_drop_impl(store)
+ }
+
/// Same as [`ResourceAny::resource_drop`] except for use with async stores
/// to execute the destructor [asynchronously](crate#async).
///
diff --git a/crates/wasmtime/src/runtime/component/resources/ty.rs b/crates/wasmtime/src/runtime/component/resources/ty.rs
index 44246503c8..01bfdfcf48 100644
--- a/crates/wasmtime/src/runtime/component/resources/ty.rs
+++ b/crates/wasmtime/src/runtime/component/resources/ty.rs
@@ -104,6 +104,17 @@ impl ResourceType {
}
}
+ /// Returns whether this type was defined by the host, as opposed to by a
+ /// guest or by an uninstantiated or abstract component type.
+ pub(crate) fn is_host_defined(&self) -> bool {
+ match self.kind {
+ ResourceTypeKind::Host(_) | ResourceTypeKind::HostDynamic(_) => true,
+ ResourceTypeKind::Guest { .. }
+ | ResourceTypeKind::Uninstantiated { .. }
+ | ResourceTypeKind::Abstract { .. } => false,
+ }
+ }
+
pub(crate) fn as_host_dynamic(&self) -> Option<u32> {
match self.kind {
ResourceTypeKind::HostDynamic(payload) => Some(payload),
diff --git a/crates/wasmtime/src/runtime/component/types.rs b/crates/wasmtime/src/runtime/component/types.rs
index e299f48319..9fe84a9015 100644
--- a/crates/wasmtime/src/runtime/component/types.rs
+++ b/crates/wasmtime/src/runtime/component/types.rs
@@ -3,7 +3,8 @@
#[cfg(feature = "component-model-async")]
use crate::component::ComponentType;
use crate::component::matching::InstanceType;
-use crate::{Engine, ExternType, FuncType, prelude::*};
+use crate::component::{ResourceAny, Val};
+use crate::{AsContextMut, Engine, ExternType, FuncType, StoreContextMut, prelude::*};
use alloc::sync::Arc;
use core::fmt;
use core::ops::Deref;
@@ -951,6 +952,124 @@ impl Type {
}
}
+ /// Construct a default value of this type, if one exists.
+ ///
+ /// Defaults are the "empty" or "zero" value of each type: zero for the
+ /// numerics, the empty `string`/`list`, `none` for `option`, `ok` for
+ /// `result`, no flags set, and the first case of a `variant` or `enum`.
+ ///
+ /// An `own` or `borrow` of a host-defined resource defaults to a fresh
+ /// handle in `store`, with an arbitrary representation and no destructor.
+ /// Nothing can be done with such a handle beyond passing it back to the
+ /// component that the resource was defined for.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error for an `own` or `borrow` of a guest-defined resource,
+ /// whose representation belongs to the guest and so cannot be conjured by
+ /// the host.
+ ///
+ /// Returns an error for `future`, `stream`, and `error-context`, as there
+ /// is currently no way to synthesize these without statically knowing
+ /// their payload type.
+ ///
+ /// An aggregate containing any of the above is an error for the same
+ /// reason.
+ ///
+ /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error
+ /// when memory allocation fails. See the `OutOfMemory` type's
+ /// documentation for details on Wasmtime's out-of-memory handling.
+ pub fn default_value(&self, mut store: impl AsContextMut) -> Result<Val> {
+ self.default_value_impl(store.as_context_mut())
+ }
+
+ /// Recursive implementation of `default_value`.
+ fn default_value_impl<T>(&self, mut store: StoreContextMut<'_, T>) -> Result<Val> {
+ Ok(match self {
+ Type::Bool => Val::Bool(false),
+ Type::S8 => Val::S8(0),
+ Type::U8 => Val::U8(0),
+ Type::S16 => Val::S16(0),
+ Type::U16 => Val::U16(0),
+ Type::S32 => Val::S32(0),
+ Type::U32 => Val::U32(0),
+ Type::S64 => Val::S64(0),
+ Type::U64 => Val::U64(0),
+ Type::Float32 => Val::Float32(0.0),
+ Type::Float64 => Val::Float64(0.0),
+ Type::Char => Val::Char('\0'),
+ Type::String => Val::String(String::new()),
+
+ // These never visit their payload types.
+ Type::List(_) => Val::List(Vec::new()),
+ Type::Map(_) => Val::Map(Vec::new()),
+ Type::Option(_) => Val::Option(None),
+ Type::Flags(_) => Val::Flags(Vec::new()),
+
+ Type::Enum(e) => {
+ let name = e.names().next().ok_or_else(|| {
+ format_err!("no default value exists for an `enum` with no cases")
+ })?;
+ Val::Enum(name.to_string())
+ }
+
+ Type::Record(record) => {
+ let mut fields = TryVec::with_capacity(record.fields().len())?;
+ for field in record.fields() {
+ let val = field.ty.default_value_impl(store.as_context_mut())?;
+ fields.push((field.name.to_string(), val))?;
+ }
+ Val::Record(fields.into())
+ }
+
+ Type::Tuple(tuple) => {
+ let mut vals = TryVec::with_capacity(tuple.types().len())?;
+ for ty in tuple.types() {
+ vals.push(ty.default_value_impl(store.as_context_mut())?)?;
+ }
+ Val::Tuple(vals.into())
+ }
+
+ Type::Variant(variant) => {
+ let case = variant.cases().next().ok_or_else(|| {
+ format_err!("no default value exists for a `variant` with no cases")
+ })?;
+ let payload = match &case.ty {
+ Some(ty) => Some(Box::new(ty.default_value_impl(store.as_context_mut())?)),
+ None => None,
+ };
+ Val::Variant(case.name.to_string(), payload)
+ }
+
+ Type::Result(result) => Val::Result(Ok(match result.ok() {
+ Some(ty) => Some(Box::new(ty.default_value_impl(store.as_context_mut())?)),
+ None => None,
+ })),
+
+ Type::FixedLengthList(list) => {
+ // Every element has the same type, so one value is cloned.
+ let element = list.ty().default_value_impl(store.as_context_mut())?;
+ let len = usize::try_from(list.len())?;
+ let mut vals = TryVec::with_capacity(len)?;
+ for _ in 0..len {
+ vals.push(element.clone())?;
+ }
+ Val::FixedLengthList(vals.into())
+ }
+
+ // The `rep` is arbitrary and never dereferenced: there is no
+ // destructor, and the handle is opaque to everything but the
+ // component that defines the resource.
+ Type::Own(ty) | Type::Borrow(ty) => {
+ Val::Resource(ResourceAny::new_own_dynamic(*ty, 0, &mut store)?)
+ }
+
+ Type::Future(_) | Type::Stream(_) | Type::ErrorContext => {
+ bail!("no default value exists for type `{}`", self.desc())
+ }
+ })
+ }
+
fn desc(&self) -> &'static str {
match self {
Type::Bool => "bool",
diff --git a/src/commands/run.rs b/src/commands/run.rs
index 8dfb6c93b3..5f04e76c8b 100644
--- a/src/commands/run.rs
+++ b/src/commands/run.rs
@@ -703,7 +703,13 @@ impl RunCommand {
main_target.unwrap_core(),
)?;
}
- _ => bail!("cannot use `--default-values-unknown-imports` with components"),
+ #[cfg(feature = "component-model")]
+ CliLinker::Component(linker) => {
+ linker.define_unknown_imports_as_default_values(
+ &mut *store,
+ main_target.unwrap_component(),
+ )?;
+ }
}
}
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index 368ead3431..bf301742c9 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -686,6 +686,79 @@ fn component_invoke_multiple_run_exports() -> Result<()> {
Ok(())
}
+#[test]
+#[cfg_attr(not(feature = "component-model"), ignore)]
+fn component_unknown_imports_default() -> Result<()> {
+ let path = "tests/all/cli_tests/component-unknown-imports.wat";
+
+ // Every type that has a default comes back with it.
+ let stdout = run_wasmtime(&[
+ "run",
+ "-Wunknown-imports-default",
+ "--invoke",
+ "defaults()",
+ path,
+ ])?;
+ assert_eq!(
+ stdout,
+ "(0, 0, \"\", false, '\\u{0}', [], none, ok(0), {a: 0, b: \"\"}, x(0), {}, e1)\n"
+ );
+
+ // Resources need handling that a return value does not show: a `borrow`
+ // argument must be dropped by the stub, and an `own` argument consumed.
+ run_wasmtime(&["run", "-Wunknown-imports-default", path])?;
+
+ // Without the flag the component cannot even be instantiated.
+ let output = get_wasmtime_command()?.arg("run").arg(path).output()?;
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("a matching implementation was not found in the linker"),
+ "bad stderr: {stderr}"
+ );
+
+ // `unknown-imports-trap` still traps rather than returning defaults.
+ let output = get_wasmtime_command()?
+ .arg("run")
+ .arg("-Wunknown-imports-trap")
+ .arg(path)
+ .output()?;
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("unknown import: `unknown:pkg/iface#make` has not been defined"),
+ "bad stderr: {stderr}"
+ );
+
+ Ok(())
+}
+
+#[test]
+#[cfg_attr(not(feature = "component-model-async"), ignore)]
+fn component_unknown_imports_default_async() -> Result<()> {
+ let path = "tests/all/cli_tests/component-unknown-imports-async.wat";
+
+ // Async imports are stubbed out, so the component instantiates, but `f`
+ // returns a `future`, which has no default value.
+ let output = get_wasmtime_command()?
+ .args([
+ "run",
+ "-Wcomponent-model-async",
+ "-Wunknown-imports-default",
+ ])
+ .arg(path)
+ .output()?;
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("unknown import: `f` has no default value")
+ && stderr.contains("no default value exists for type `future`"),
+ "bad stderr: {stderr}"
+ );
+
+ Ok(())
+}
+
// If the text format is invalid then the filename should be mentioned in the
// error message.
#[test]
diff --git a/tests/all/cli_tests/component-unknown-imports-async.wat b/tests/all/cli_tests/component-unknown-imports-async.wat
new file mode 100644
index 0000000000..14127b3e74
--- /dev/null
+++ b/tests/all/cli_tests/component-unknown-imports-async.wat
@@ -0,0 +1,32 @@
+;; A component with undefined async imports, to exercise
+;; `-W unknown-imports-default` on the concurrent stub path.
+;;
+;; An `async func`-typed import can only be satisfied by `func_new_concurrent`,
+;; so stubbing these at all exercises a separate path from the sync case.
+;;
+;; `f` returns a `future`, which has no default. Defining it still succeeds, so
+;; the component instantiates; calling it is what fails.
+(component
+ (import "foo" (func async (result u32)))
+ (import "bar" (instance (export "baz" (func async))))
+ (import "qux" (type (sub resource)))
+
+ (type $f (func (result (future u32))))
+ (import "f" (func $fn (type $f)))
+
+ (core func $lowered (canon lower (func $fn)))
+ (core module $m
+ (import "" "f" (func $f (result i32)))
+ (func (export "run") (result i32)
+ (drop (call $f))
+ i32.const 0)
+ )
+ (core instance $i (instantiate $m
+ (with "" (instance (export "f" (func $lowered))))))
+
+ (func $run (result (result))
+ (canon lift (core func $i "run")))
+
+ (instance (export (interface "wasi:cli/[email protected]"))
+ (export "run" (func $run)))
+)
diff --git a/tests/all/cli_tests/component-unknown-imports.wat b/tests/all/cli_tests/component-unknown-imports.wat
new file mode 100644
index 0000000000..24822782b9
--- /dev/null
+++ b/tests/all/cli_tests/component-unknown-imports.wat
@@ -0,0 +1,101 @@
+;; A component whose imports are all undefined, to exercise
+;; `-W unknown-imports-default`. Without that flag it cannot be instantiated.
+;;
+;; Two entry points:
+;;
+;; * `defaults`, invoked with `--invoke`, returns the defaults for every
+;; interface type that has one, so they can be checked against the printed
+;; output.
+;;
+;; * `wasi:cli/run`, which exercises the resource handling that is not visible
+;; in a return value: a `borrow` argument must be dropped by the stub, or the
+;; guest traps with "borrow handles still remain at the end of the call".
+(component
+ (type (;0;) (record (field "a" u32) (field "b" string)))
+ (import "rec" (type $rec (eq 0)))
+ (type (;2;) (variant (case "x" s64) (case "y")))
+ (import "var" (type $var (eq 2)))
+ (type (;4;) (flags "p" "q"))
+ (import "fl" (type $fl (eq 4)))
+ (type (;6;) (enum "e1" "e2"))
+ (import "en" (type $en (eq 6)))
+
+ (type $all (tuple u32 float64 string bool char (list u8)
+ (option u64) (result u32 (error string))
+ $rec $var $fl $en))
+
+ (import "unknown:pkg/iface" (instance $iface
+ (export "r" (type $r (sub resource)))
+ (export "defaults" (func (result $all)))
+ (export "make" (func (result (own $r))))
+ (export "borrow-it" (func (param "self" (borrow $r)) (result u32)))
+ (export "consume" (func (param "a" (own $r)) (result u32)))
+ ;; Stubbed out as well, though nothing here calls them.
+ (export "nested" (instance (export "baz" (func))))
+ ))
+ (alias export $iface "r" (type $r))
+ (alias export $iface "defaults" (func $defaults))
+ (alias export $iface "make" (func $make))
+ (alias export $iface "borrow-it" (func $borrow-it))
+ (alias export $iface "consume" (func $consume))
+
+ (core module $libc
+ (memory (export "mem") 1)
+ (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 8)
+ )
+ (core instance $libc (instantiate $libc))
+ (alias core export $libc "mem" (core memory $mem))
+ (alias core export $libc "realloc" (core func $realloc))
+
+ (core func $defaults-l
+ (canon lower (func $defaults) (memory $mem) (realloc (core func $realloc))))
+ (core func $make-l (canon lower (func $make)))
+ (core func $borrow-l (canon lower (func $borrow-it)))
+ (core func $consume-l (canon lower (func $consume)))
+ (core func $drop-r (canon resource.drop $r))
+
+ (core module $m
+ (import "" "defaults" (func $defaults (param i32)))
+ (import "" "make" (func $make (result i32)))
+ (import "" "borrow" (func $borrow (param i32) (result i32)))
+ (import "" "consume" (func $consume (param i32) (result i32)))
+ (import "" "drop" (func $drop (param i32)))
+
+ (func (export "defaults") (result i32)
+ (call $defaults (i32.const 256))
+ i32.const 256)
+
+ (func (export "run") (result i32)
+ (local $handle i32)
+
+ ;; A resource-returning import yields a usable handle, and passing it
+ ;; back as a `borrow` must not leave the borrow dangling on return.
+ (local.set $handle (call $make))
+ (if (i32.ne (call $borrow (local.get $handle)) (i32.const 0))
+ (then unreachable))
+ (call $drop (local.get $handle))
+
+ ;; An `own` argument is consumed by the stub; do it twice to be sure the
+ ;; handle was really released.
+ (if (i32.ne (call $consume (call $make)) (i32.const 0)) (then unreachable))
+ (if (i32.ne (call $consume (call $make)) (i32.const 0)) (then unreachable))
+
+ i32.const 0)
+ )
+
+ (core instance $i (instantiate $m (with "" (instance
+ (export "defaults" (func $defaults-l))
+ (export "make" (func $make-l))
+ (export "borrow" (func $borrow-l))
+ (export "consume" (func $consume-l))
+ (export "drop" (func $drop-r))))))
+
+ (func (export "defaults") (result $all)
+ (canon lift (core func $i "defaults") (memory $mem) (realloc (core func $realloc))))
+
+ (func $run (result (result))
+ (canon lift (core func $i "run")))
+
+ (instance (export (interface "wasi:cli/[email protected]"))
+ (export "run" (func $run)))
+)
diff --git a/tests/all/component_model/linker.rs b/tests/all/component_model/linker.rs
index 66c82358ec..bec6e67840 100644
--- a/tests/all/component_model/linker.rs
+++ b/tests/all/component_model/linker.rs
@@ -1,6 +1,6 @@
use wasmtime::Result;
use wasmtime::component::types::ComponentItem;
-use wasmtime::component::{Component, Linker, ResourceType};
+use wasmtime::component::{Component, Linker, ResourceType, Val};
use wasmtime::{Config, Engine, Module, Store};
#[test]
@@ -253,6 +253,82 @@ fn linker_fails_to_define_unknown_core_module_imports_as_traps() -> Result<()> {
Ok(())
}
+/// A default `own` handle takes the resource type of the instance it flows
+/// into, which is only possible for a host-defined type: a guest owns the
+/// representation of its own resources, so one cannot be synthesized.
+#[test]
+#[cfg_attr(miri, ignore)]
+fn linker_default_value_resource_types() -> Result<()> {
+ const COMPONENT: &str = r#"(component
+ (import "types" (instance $t (export "r" (type (sub resource)))))
+ (alias export $t "r" (type $r))
+ (import "f" (func $fn (result (own $r))))
+
+ (core func $lowered (canon lower (func $fn)))
+ (core module $m
+ (import "" "f" (func $f (result i32)))
+ (func (export "run") (result i32) call $f)
+ )
+ (core instance $i (instantiate $m
+ (with "" (instance (export "f" (func $lowered))))))
+ (func (export "run") (result (own $r))
+ (canon lift (core func $i "run")))
+ )"#;
+
+ let engine = Engine::default();
+ let component = Component::new(&engine, COMPONENT)?;
+ let mut store = Store::new(&engine, ());
+
+ // A host-defined resource: the handle comes back with the linker's type,
+ // not one of the stub's choosing.
+ let host_ty = ResourceType::host::<u32>();
+ let mut linker = Linker::<()>::new(&engine);
+ linker
+ .instance("types")?
+ .resource("r", host_ty, |_, _| Ok(()))?;
+ linker.define_unknown_imports_as_default_values(&mut store, &component)?;
+
+ let instance = linker.instantiate(&mut store, &component)?;
+ let run = instance.get_func(&mut store, "run").unwrap();
+ let mut results = [Val::Bool(false)];
+ run.call(&mut store, &[], &mut results)?;
+ let Val::Resource(resource) = results[0] else {
+ panic!("expected a resource");
+ };
+ assert_eq!(resource.ty(), host_ty);
+
+ // A guest-defined resource, taken from a live instance of a component
+ // which defines one. Instantiating still works; only the call fails.
+ let producer = Component::new(
+ &engine,
+ r#"(component
+ (core module $m (func (export "dtor") (param i32)))
+ (core instance $mi (instantiate $m))
+ (type $r (resource (rep i32) (dtor (core func $mi "dtor"))))
+ (export "r" (type $r))
+ )"#,
+ )?;
+ let producer = Linker::<()>::new(&engine).instantiate(&mut store, &producer)?;
+ let guest_ty = producer.get_resource(&mut store, "r").unwrap();
+
+ let mut linker = Linker::<()>::new(&engine);
+ linker
+ .instance("types")?
+ .resource("r", guest_ty, |_, _| Ok(()))?;
+ linker.define_unknown_imports_as_default_values(&mut store, &component)?;
+
+ let instance = linker.instantiate(&mut store, &component)?;
+ let run = instance.get_func(&mut store, "run").unwrap();
+ let err = run.call(&mut store, &[], &mut results).unwrap_err();
+ let err = format!("{err:?}");
+ assert!(
+ err.contains("cannot synthesize a resource of a non-host-defined type"),
+ "unexpected error: {err}"
+ );
+
+ Ok(())
+}
+
#[test]
fn open_instance_twice() -> Result<()> {
let engine = Engine::default();