Skip to content

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

`CodeBuilder` APIs for defining compile-time builtins (#11918)

Nick Fitzgeralde069bdd3016f
diff --git a/Cargo.lock b/Cargo.lock
index 2898993ce0..e942f0e3ea 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4588,6 +4588,7 @@ dependencies = [
"target-lexicon",
"tempfile",
"tokio",
+ "wasm-compose",
"wasm-encoder 0.240.0",
"wasm-wave",
"wasmparser 0.240.0",
diff --git a/crates/wasmtime/Cargo.toml b/crates/wasmtime/Cargo.toml
index cf0057cb1c..87636c9343 100644
--- a/crates/wasmtime/Cargo.toml
+++ b/crates/wasmtime/Cargo.toml
@@ -36,6 +36,8 @@ target-lexicon = { workspace = true }
wasmparser = { workspace = true }
wasm-encoder = { workspace = true, optional = true }
wasm-wave = { workspace = true, optional = true }
+wasm-compose = { workspace = true, optional = true }
+tempfile = { workspace = true, optional = true }
anyhow = { workspace = true }
libc = { workspace = true }
cfg-if = { workspace = true }
@@ -152,6 +154,7 @@ default = [
'stack-switching',
'std',
'debug',
+ 'compile-time-builtins',
]
# An on-by-default feature enabling runtime compilation of WebAssembly modules
@@ -420,3 +423,5 @@ debug = [
'async'
]
+# Enables support for defining compile-time builtins.
+compile-time-builtins = ['dep:wasm-compose', 'dep:tempfile']
diff --git a/crates/wasmtime/src/compile/code_builder.rs b/crates/wasmtime/src/compile/code_builder.rs
index c7973bff5a..eb9ba33471 100644
--- a/crates/wasmtime/src/compile/code_builder.rs
+++ b/crates/wasmtime/src/compile/code_builder.rs
@@ -3,6 +3,12 @@ use crate::prelude::*;
use std::borrow::Cow;
use std::path::Path;
+#[cfg(feature = "compile-time-builtins")]
+use crate::hash_map::HashMap;
+
+#[cfg(feature = "compile-time-builtins")]
+mod compile_time_builtins;
+
/// Builder-style structure used to create a [`Module`](crate::module::Module) or
/// pre-compile a module to a serialized list of bytes.
///
@@ -41,6 +47,17 @@ pub struct CodeBuilder<'a> {
dwarf_package: Option<Cow<'a, [u8]>>,
dwarf_package_path: Option<Cow<'a, Path>>,
unsafe_intrinsics_import: Option<String>,
+
+ /// A map from import name to the Wasm bytes of the associated compile-time
+ /// builtin and its file path, if any.
+ //
+ // XXX: we can't use `'a` here without forcing us to change a bunch of
+ // callers because `HashMap` has a `Drop` implementation, so `dropck` thinks
+ // that all `'a` borrows could be used by `CodeBuilder`'s `Drop`, which
+ // means that a bunch of the existing calls to `.wasm_bytes` and such would
+ // need to be reordered with the `CodeBuilder`'s construction.
+ #[cfg(feature = "compile-time-builtins")]
+ compile_time_builtins: HashMap<Cow<'a, str>, Cow<'a, [u8]>>,
}
/// Return value of [`CodeBuilder::hint`]
@@ -54,7 +71,7 @@ pub enum CodeHint {
impl<'a> CodeBuilder<'a> {
/// Creates a new builder which will insert modules into the specified
/// [`Engine`].
- pub fn new(engine: &'a Engine) -> CodeBuilder<'a> {
+ pub fn new(engine: &'a Engine) -> Self {
CodeBuilder {
engine,
wasm: None,
@@ -62,6 +79,8 @@ impl<'a> CodeBuilder<'a> {
dwarf_package: None,
dwarf_package_path: None,
unsafe_intrinsics_import: None,
+ #[cfg(feature = "compile-time-builtins")]
+ compile_time_builtins: HashMap::default(),
}
}
@@ -177,10 +196,26 @@ impl<'a> CodeBuilder<'a> {
}
}
- pub(super) fn get_wasm(&self) -> Result<&[u8]> {
- self.wasm
+ /// Get the Wasm to be compiled.
+ ///
+ /// When using compile-time builtins, compose the builtins and the guest
+ /// Wasm together, before returning the Wasm.
+ pub(super) fn get_wasm(&self) -> Result<Cow<'_, [u8]>> {
+ let wasm = self
+ .wasm
.as_deref()
- .ok_or_else(|| anyhow!("no wasm bytes have been configured"))
+ .ok_or_else(|| anyhow!("no wasm bytes have been configured"))?;
+
+ #[cfg(not(feature = "compile-time-builtins"))]
+ {
+ Ok(wasm.into())
+ }
+
+ #[cfg(feature = "compile-time-builtins")]
+ {
+ self.compose_compile_time_builtins(wasm)
+ .context("failed to compose compile-time builtins with the main Wasm")
+ }
}
/// Expose Wasmtime's unsafe intrinsics under the given import name.
@@ -191,18 +226,22 @@ impl<'a> CodeBuilder<'a> {
/// for details.
///
/// This functionality is intended to be used when implementing
- /// "compile-time builtins"; that is, satisfying a Wasm import via
- /// special-cased, embedder-specific code at compile time. You should never
- /// use these intrinsics to intentionally subvert the Wasm sandbox. You
- /// should strive to implement safe functions that encapsulate your uses of
- /// these intrinsics such that, regardless of any value given as arguments,
- /// your functions *cannot* result in loading from or storing to invalid
- /// pointers, or any other kind of unsafety. See below for an example of the
- /// intended use cases.
+ /// [compile-time builtins][CodeBuilder::compile_time_builtins_binary]; that
+ /// is, satisfying a Wasm import via special-cased, embedder-specific code
+ /// at compile time. You should never use these intrinsics to intentionally
+ /// subvert the Wasm sandbox. You should strive to implement safe functions
+ /// that encapsulate your uses of these intrinsics such that, regardless of
+ /// any value given as arguments, your functions *cannot* result in loading
+ /// from or storing to invalid pointers, or any other kind of unsafety. See
+ /// below for an example of the intended use cases.
///
/// Wasmtime's unsafe intrinsics can only be exposed to Wasm components, not
/// core modules, currently.
///
+ /// Note that when compile-time builtins are defined on a `CodeBuilder`,
+ /// only the compile-time builtins can import the unsafe intrinsics, and the
+ /// main guest program cannot import them.
+ ///
/// # Safety
///
/// Extreme care must be taken when using these intrinsics.
@@ -328,8 +367,9 @@ impl<'a> CodeBuilder<'a> {
///
/// # Example
///
- /// The following example shows how you can use unsafe intrinsics to give
- /// Wasm direct zero-copy access to a host buffer.
+ /// The following example shows how you can use unsafe intrinsics and
+ /// compile-time builtins to give Wasm direct zero-copy access to a host
+ /// buffer.
///
/// ```rust
/// use std::mem;
@@ -391,8 +431,8 @@ impl<'a> CodeBuilder<'a> {
/// }
///
/// impl StoreData {
- /// /// Create a new `StoreData`, allocating an inner buffer of `capacity`
- /// /// bytes.
+ /// /// Create a new `StoreData`, allocating an inner buffer containing
+ /// /// `bytes`.
/// fn new(bytes: impl IntoIterator<Item = u8>) -> Self {
/// let buf: Box<[u8]> = bytes.into_iter().collect();
/// let ptr = Box::into_raw(buf);
@@ -410,15 +450,6 @@ impl<'a> CodeBuilder<'a> {
/// std::slice::from_raw_parts(ptr, len)
/// }
/// }
- ///
- /// /// Get the inner buffer as a mutable slice.
- /// fn buf_mut(&mut self) -> &mut [u8] {
- /// let ptr = self.buf_ptr.get();
- /// let len = usize::try_from(self.buf_len).unwrap();
- /// unsafe {
- /// std::slice::from_raw_parts_mut(ptr, len)
- /// }
- /// }
/// }
///
/// # fn main() -> Result<()> {
@@ -441,113 +472,110 @@ impl<'a> CodeBuilder<'a> {
/// builder.expose_unsafe_intrinsics("unsafe-intrinsics");
/// }
///
- /// // Provide the Wasm that we are compiling.
- /// builder.wasm_binary_or_text(r#"
- /// (component
- /// ;; Import the unsafe intrinsics that we will use.
- /// (import "unsafe-intrinsics"
- /// (instance $intrinsics
- /// (export "store-data-address" (func (result u64)))
- /// (export "u64-native-load" (func (param "pointer" u64) (result u64)))
- /// (export "u8-native-load" (func (param "pointer" u64) (result u8)))
- /// (export "u8-native-store" (func (param "pointer" u64) (param "value" u8)))
- /// )
- /// )
- ///
- /// ;; A component that encapsulates the intrinsics' unsafety, exposing a safe API
- /// ;; built on top of them.
- /// (component $safe-api
- /// (import "unsafe-intrinsics"
- /// (instance $intrinsics
- /// (export "store-data-address" (func (result u64)))
- /// (export "u64-native-load" (func (param "pointer" u64) (result u64)))
- /// (export "u8-native-load" (func (param "pointer" u64) (result u8)))
- /// (export "u8-native-store" (func (param "pointer" u64) (param "value" u8)))
+ /// // Define the compile-time builtin that encapsulates the
+ /// // intrinsics' unsafety and builds a safe API on top of them.
+ /// unsafe {
+ /// builder.compile_time_builtins_binary_or_text(
+ /// "safe-api",
+ /// r#"
+ /// (component
+ /// (import "unsafe-intrinsics"
+ /// (instance $intrinsics
+ /// (export "store-data-address" (func (result u64)))
+ /// (export "u64-native-load" (func (param "pointer" u64) (result u64)))
+ /// (export "u8-native-load" (func (param "pointer" u64) (result u8)))
+ /// (export "u8-native-store" (func (param "pointer" u64) (param "value" u8)))
+ /// )
/// )
- /// )
///
- /// ;; The core Wasm module that implements the safe API.
- /// (core module $safe-api-impl
- /// (import "" "store-data-address" (func $store-data-address (result i64)))
- /// (import "" "u64-native-load" (func $u64-native-load (param i64) (result i64)))
- /// (import "" "u8-native-load" (func $u8-native-load (param i64) (result i32)))
- /// (import "" "u8-native-store" (func $u8-native-store (param i64 i32)))
+ /// ;; The core Wasm module that implements the safe API.
+ /// (core module $safe-api-impl
+ /// (import "" "store-data-address" (func $store-data-address (result i64)))
+ /// (import "" "u64-native-load" (func $u64-native-load (param i64) (result i64)))
+ /// (import "" "u8-native-load" (func $u8-native-load (param i64) (result i32)))
+ /// (import "" "u8-native-store" (func $u8-native-store (param i64 i32)))
///
- /// ;; Load the `StoreData::buf_ptr` field
- /// (func $get-buf-ptr (result i64)
- /// (call $u64-native-load (i64.add (call $store-data-address) (i64.const 0)))
- /// )
+ /// ;; Load the `StoreData::buf_ptr` field
+ /// (func $get-buf-ptr (result i64)
+ /// (call $u64-native-load (i64.add (call $store-data-address) (i64.const 0)))
+ /// )
///
- /// ;; Load the `StoreData::buf_len` field
- /// (func $get-buf-len (result i64)
- /// (call $u64-native-load (i64.add (call $store-data-address) (i64.const 8)))
- /// )
+ /// ;; Load the `StoreData::buf_len` field
+ /// (func $get-buf-len (result i64)
+ /// (call $u64-native-load (i64.add (call $store-data-address) (i64.const 8)))
+ /// )
///
- /// ;; Check that `$i` is within `StoreData` buffer's bounds, raising a trap
- /// ;; otherwise.
- /// (func $bounds-check (param $i i64)
- /// (if (i64.lt_u (local.get $i) (call $get-buf-len))
- /// (then (return))
- /// (else (unreachable))
+ /// ;; Check that `$i` is within `StoreData` buffer's bounds, raising a trap
+ /// ;; otherwise.
+ /// (func $bounds-check (param $i i64)
+ /// (if (i64.lt_u (local.get $i) (call $get-buf-len))
+ /// (then (return))
+ /// (else (unreachable))
+ /// )
/// )
- /// )
///
- /// ;; A safe function to get the `i`th byte from `StoreData`'s buffer, raising
- /// ;; a trap on out-of-bounds accesses.
- /// (func (export "get") (param $i i64) (result i32)
- /// (call $bounds-check (local.get $i))
- /// (call $u8-native-load (i64.add (call $get-buf-ptr) (local.get $i)))
- /// )
+ /// ;; A safe function to get the `i`th byte from `StoreData`'s buffer,
+ /// ;; raising a trap on out-of-bounds accesses.
+ /// (func (export "get") (param $i i64) (result i32)
+ /// (call $bounds-check (local.get $i))
+ /// (call $u8-native-load (i64.add (call $get-buf-ptr) (local.get $i)))
+ /// )
///
- /// ;; A safe function to set the `i`th byte in `StoreData`'s buffer, raising
- /// ;; a trap on out-of-bounds accesses.
- /// (func (export "set") (param $i i64) (param $value i32)
- /// (call $bounds-check (local.get $i))
- /// (call $u8-native-store (i64.add (call $get-buf-ptr) (local.get $i))
- /// (local.get $value))
- /// )
+ /// ;; A safe function to set the `i`th byte in `StoreData`'s buffer,
+ /// ;; raising a trap on out-of-bounds accesses.
+ /// (func (export "set") (param $i i64) (param $value i32)
+ /// (call $bounds-check (local.get $i))
+ /// (call $u8-native-store (i64.add (call $get-buf-ptr) (local.get $i))
+ /// (local.get $value))
+ /// )
///
- /// ;; A safe function to get the length of the `StoreData` buffer.
- /// (func (export "len") (result i64)
- /// (call $get-buf-len)
+ /// ;; A safe function to get the length of the `StoreData` buffer.
+ /// (func (export "len") (result i64)
+ /// (call $get-buf-len)
+ /// )
/// )
- /// )
///
- /// ;; Lower the imported intrinsics from component functions to core functions.
- /// (core func $store-data-address' (canon lower (func $intrinsics "store-data-address")))
- /// (core func $u64-native-load' (canon lower (func $intrinsics "u64-native-load")))
- /// (core func $u8-native-load' (canon lower (func $intrinsics "u8-native-load")))
- /// (core func $u8-native-store' (canon lower (func $intrinsics "u8-native-store")))
- ///
- /// ;; Instantiate our safe API implementation, passing in the lowered unsafe
- /// ;; intrinsics as its imports.
- /// (core instance $instance
- /// (instantiate $safe-api-impl
- /// (with "" (instance
- /// (export "store-data-address" (func $store-data-address'))
- /// (export "u64-native-load" (func $u64-native-load'))
- /// (export "u8-native-load" (func $u8-native-load'))
- /// (export "u8-native-store" (func $u8-native-store'))
- /// ))
+ /// ;; Lower the imported intrinsics from component functions to core functions.
+ /// (core func $store-data-address' (canon lower (func $intrinsics "store-data-address")))
+ /// (core func $u64-native-load' (canon lower (func $intrinsics "u64-native-load")))
+ /// (core func $u8-native-load' (canon lower (func $intrinsics "u8-native-load")))
+ /// (core func $u8-native-store' (canon lower (func $intrinsics "u8-native-store")))
+ ///
+ /// ;; Instantiate our safe API implementation, passing in the lowered unsafe
+ /// ;; intrinsics as its imports.
+ /// (core instance $instance
+ /// (instantiate $safe-api-impl
+ /// (with "" (instance
+ /// (export "store-data-address" (func $store-data-address'))
+ /// (export "u64-native-load" (func $u64-native-load'))
+ /// (export "u8-native-load" (func $u8-native-load'))
+ /// (export "u8-native-store" (func $u8-native-store'))
+ /// ))
+ /// )
/// )
- /// )
///
- /// ;; Lift the safe API's exports from core functions to component functions and
- /// ;; export them.
- /// (func (export "get") (param "i" u64) (result u8)
- /// (canon lift (core func $instance "get"))
- /// )
- /// (func (export "set") (param "i" u64) (param "value" u8)
- /// (canon lift (core func $instance "set"))
- /// )
- /// (func (export "len") (result u64)
- /// (canon lift (core func $instance "len"))
+ /// ;; Lift the safe API's exports from core functions to component functions
+ /// ;; and export them.
+ /// (func (export "get") (param "i" u64) (result u8)
+ /// (canon lift (core func $instance "get"))
+ /// )
+ /// (func (export "set") (param "i" u64) (param "value" u8)
+ /// (canon lift (core func $instance "set"))
+ /// )
+ /// (func (export "len") (result u64)
+ /// (canon lift (core func $instance "len"))
+ /// )
/// )
- /// )
+ /// "#.as_bytes(),
+ /// None,
+ /// )?;
+ /// }
///
- /// ;; A component that uses that safe API to increment each byte in the
- /// ;; `StoreData` buffer.
- /// (component $main
+ /// // Provide the guest Wasm that we are compiling, which uses the safe API we
+ /// // implemented as a compile-time builtin.
+ /// builder.wasm_binary_or_text(
+ /// r#"
+ /// (component
/// ;; Import the safe API.
/// (import "safe-api"
/// (instance $safe-api
@@ -605,25 +633,15 @@ impl<'a> CodeBuilder<'a> {
/// )
/// )
///
- /// ;; Lift implementation's `main` from a core function to a component function
- /// ;; and export it.
+ /// ;; Lift the implementation's `main` from a core function to a component function
+ /// ;; and export it!
/// (func (export "main")
/// (canon lift (core func $instance "main"))
/// )
/// )
- ///
- /// ;; Instantiate our safe API component and our main component that consumes
- /// ;; it, passing the unsafe intrinsics into the safe API, and the safe API
- /// ;; into the main component.
- /// (instance $safe-api-instance
- /// (instantiate $safe-api (with "unsafe-intrinsics" (instance $intrinsics))))
- /// (instance $main-instance
- /// (instantiate $main (with "safe-api" (instance $safe-api-instance))))
- ///
- /// ;; Finally, re-export the `main` function!
- /// (export "main" (func $main-instance "main"))
- /// )
- /// "#.as_bytes(), None)?;
+ /// "#.as_bytes(),
+ /// None,
+ /// )?;
///
/// // Finish the builder and compile the component.
/// let component = builder.compile_component()?;
@@ -740,12 +758,19 @@ impl<'a> CodeBuilder<'a> {
/// This can fail if the input wasm module was not valid or if another
/// compilation-related error is encountered.
pub fn compile_module_serialized(&self) -> Result<Vec<u8>> {
- let wasm = self.get_wasm()?;
- let dwarf_package = self.get_dwarf_package();
ensure!(
self.unsafe_intrinsics_import.is_none(),
"`CodeBuilder::expose_unsafe_intrinsics` can only be used with components"
);
+
+ #[cfg(feature = "compile-time-builtins")]
+ ensure!(
+ self.get_compile_time_builtins().is_empty(),
+ "compile-time builtins can only be used with components"
+ );
+
+ let wasm = self.get_wasm()?;
+ let dwarf_package = self.get_dwarf_package();
let (v, _) =
super::build_module_artifacts(self.engine, &wasm, dwarf_package.as_deref(), &())?;
Ok(v)
@@ -756,10 +781,10 @@ impl<'a> CodeBuilder<'a> {
/// instead of a module.
#[cfg(feature = "component-model")]
pub fn compile_component_serialized(&self) -> Result<Vec<u8>> {
- let bytes = self.get_wasm()?;
+ let wasm = self.get_wasm()?;
let (v, _) = super::build_component_artifacts(
self.engine,
- &bytes,
+ &wasm,
None,
self.get_unsafe_intrinsics_import(),
&(),
diff --git a/crates/wasmtime/src/compile/code_builder/compile_time_builtins.rs b/crates/wasmtime/src/compile/code_builder/compile_time_builtins.rs
new file mode 100644
index 0000000000..dc62fe8a5c
--- /dev/null
+++ b/crates/wasmtime/src/compile/code_builder/compile_time_builtins.rs
@@ -0,0 +1,309 @@
+use super::*;
+
+impl<'a> CodeBuilder<'a> {
+ pub(crate) fn get_compile_time_builtins(&self) -> &HashMap<Cow<'a, str>, Cow<'a, [u8]>> {
+ &self.compile_time_builtins
+ }
+
+ pub(super) fn compose_compile_time_builtins<'b>(
+ &self,
+ main_wasm: &'b [u8],
+ ) -> Result<Cow<'b, [u8]>> {
+ if self.get_compile_time_builtins().is_empty() {
+ return Ok(main_wasm.into());
+ }
+
+ let imports = self.check_imports_for_compile_time_builtins(&main_wasm)?;
+ if imports.is_empty() {
+ drop(imports);
+ return Ok(main_wasm.into());
+ }
+
+ let tempdir = tempfile::TempDir::new().context("failed to create a temporary directory")?;
+ let deps = tempdir.path().join("_deps");
+ std::fs::create_dir(&deps)
+ .with_context(|| format!("failed to create directory: {}", deps.display()))?;
+
+ let main_wasm_path = tempdir.path().join("_main.wasm");
+ std::fs::write(&main_wasm_path, &main_wasm)
+ .with_context(|| format!("failed to write to file: {}", main_wasm_path.display()))?;
+
+ let mut config = wasm_compose::config::Config::default();
+ for (name, bytes) in self.get_compile_time_builtins() {
+ let name: &str = &*name;
+ if !imports.contains(&name) {
+ continue;
+ }
+
+ let mut path = deps.join(Path::new(name));
+ path.set_extension("wasm");
+
+ std::fs::write(&path, &bytes)
+ .with_context(|| format!("failed to write to file: {}", path.display()))?;
+
+ config
+ .dependencies
+ .insert(name.to_string(), wasm_compose::config::Dependency { path });
+ }
+
+ let composer = wasm_compose::composer::ComponentComposer::new(&main_wasm_path, &config);
+ let composed = composer.compose()?;
+ Ok(composed.into())
+ }
+
+ /// Check that the main Wasm doesn't import unsafe intrinsics, keeping the
+ /// TCB to just the compile-time builtins' implementation.
+ ///
+ /// Returns the Wasm's top-level instance imports for `wasm-compose`
+ /// configuration.
+ fn check_imports_for_compile_time_builtins<'b>(
+ &self,
+ main_wasm: &'b [u8],
+ ) -> Result<crate::hash_set::HashSet<&'b str>, Error> {
+ let intrinsics_import = self.unsafe_intrinsics_import.as_deref().ok_or_else(|| {
+ anyhow!("must configure the unsafe-intrinsics import when using compile-time builtins")
+ })?;
+
+ let mut instance_imports = crate::hash_set::HashSet::new();
+ let parser = wasmparser::Parser::new(0);
+ let mut level = 0;
+
+ for payload in parser.parse_all(main_wasm) {
+ match payload? {
+ wasmparser::Payload::Version { .. } => {
+ level += 1;
+ }
+ wasmparser::Payload::End(_) => {
+ level -= 1;
+ }
+ wasmparser::Payload::ComponentImportSection(imports) if level == 1 => {
+ for imp in imports.into_iter() {
+ let imp = imp?;
+ // Ideally we would simply choose a new import name that
+ // doesn't conflict with the main Wasm's imports and
+ // plumb that through to the compile-time builtins
+ // regardless of the import name that they use, but
+ // unfortunately the `wasm-compose` API is not powerful
+ // enough for us to do all that.
+ ensure!(
+ imp.name.0 != intrinsics_import,
+ "main Wasm cannot import the unsafe intrinsics (`{intrinsics_import}`) \
+ when using compile-time builtins"
+ );
+
+ if let wasmparser::ComponentTypeRef::Instance(_) = imp.ty {
+ instance_imports.insert(imp.name.0);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ Ok(instance_imports)
+ }
+
+ /// Define a compile-time builtin component, via its Wasm bytes.
+ ///
+ /// Compile-time builtins enable you to build safe, zero-copy, and (with
+ /// [inlining][crate::Config::compiler_inlining])
+ /// zero-function-call-overhead Wasm APIs for accessing host data, buffers,
+ /// and objects.
+ ///
+ /// A compile-time builtin is a component that is
+ ///
+ /// * authored by the host (Wasmtime embedder),
+ ///
+ /// * whose implementation (though not necessarily its interface!) is
+ /// host-specific,
+ ///
+ /// * has access to unsafe intrinsics (and is therefore part of the host's
+ /// [trusted compute base]), and
+ ///
+ /// * is linked into guest Wasm programs at compile-time.
+ ///
+ /// Any imports satisfied by a compile-time builtin during compilation will
+ /// not show up in the resulting component's
+ /// [imports][crate::component::types::Component::imports], and they can no
+ /// longer be customized by a [`Linker`][crate::component::Linker]
+ /// definition at instantiation time.[^0]
+ ///
+ /// [^0]: If linking compile-time builtins into a component at compile-time
+ /// reminds you of [component composition], that is not a coincidence:
+ /// component composition is used under the covers as part of compile-time
+ /// builtins' implementation.
+ ///
+ /// Comparing compile-time builtins with
+ /// [`Linker`][crate::component::Linker]s is informative:
+ ///
+ /// * Both mechanisms define APIs to satisfy a Wasm program's imports.
+ ///
+ /// * A `Linker` satisfies those imports at instantiation-time, while
+ /// compile-time builtins do it during compilation.
+ ///
+ /// * APIs defined by a `Linker` are implemented in Rust, and hosts can
+ /// build safe, sandboxed Wasm APIs on top of raw, un-sandboxed primitives
+ /// via Rust's `unsafe`. APIs defined by compile-time builtins are
+ /// implemented as Wasm components, and hosts can build safe, sandboxed
+ /// Wasm APIs on top of raw, un-sandboxed primitives via [unsafe
+ /// intrinsics][CodeBuilder::expose_unsafe_intrinsics].
+ ///
+ /// * Imports satisfied via `Linker`-defined APIs are implemented with
+ /// [PLT/GOT]-style function table lookups and indirect calls in the
+ /// Wasm's compiled native code. On the other hand, Wasmtime implements
+ /// calls to imports satisfied via compile-time builtins with direct calls
+ /// in the Wasm's compiled native code. Wasmtime's compiler can also
+ /// [inline][crate::Config::compiler_inlining] these direct calls,
+ /// removing function call overheads and enabling further, cascading
+ /// compiler optimizations.
+ ///
+ /// If you are familiar with Wasm on the Web, you can think of compile-time
+ /// builtins as the rough equivalent of [the `js-string-builtins` proposal]
+ /// but for arbitrary host-defined APIs in a Wasmtime embedding environment
+ /// rather than JS string APIs in a Web browser environment.
+ ///
+ /// [trusted compute base]: https://en.wikipedia.org/wiki/Trusted_computing_base
+ /// [the `js-string-builtins` proposal]: https://github.com/WebAssembly/js-string-builtins/blob/main/proposals/js-string-builtins/Overview.md
+ /// [component composition]: https://component-model.bytecodealliance.org/composing-and-distributing/composing.html
+ /// [PLT/GOT]: https://reverseengineering.stackexchange.com/a/1993
+ ///
+ /// # Safety
+ ///
+ /// Compile-time builtins are part of your [trusted compute base] and should
+ /// be authored by trusted, first-party developers with extreme care. You
+ /// should never use compile-time builtins authored by untrusted,
+ /// third-party developers.
+ ///
+ /// Compile-time builtins are given access to Wasmtime's [unsafe
+ /// intrinsics][CodeBuilder::expose_unsafe_intrinsics], and the same safety
+ /// invariants and portability concerns apply. However, when compile-time
+ /// builtins are defined on a `CodeBuilder`, unsafe intrinsics are *only*
+ /// exposed to the compile-time builtins, and they are *not* exposed to the
+ /// main guest Wasm program. This means that — assuming your compile-time
+ /// builtins only exposing safe APIs, encapsulating the intrinsics'
+ /// unsafety, and modulo bugs in your implementation of those safe APIs —
+ /// that the main guest Wasm program is not part of your trusted compute
+ /// base.
+ ///
+ /// # Example
+ ///
+ /// See the example in [CodeBuilder::expose_unsafe_intrinsics].
+ pub unsafe fn compile_time_builtins_binary(
+ &mut self,
+ name: impl Into<Cow<'a, str>>,
+ wasm_bytes: impl Into<Cow<'a, [u8]>>,
+ ) -> &mut Self {
+ self.compile_time_builtins
+ .insert(name.into(), wasm_bytes.into());
+ self
+ }
+
+ /// Equivalent of [`CodeBuilder::compile_time_builtins_binary`] that also
+ /// accepts the WebAssembly text format.
+ ///
+ /// This method will configure the WebAssembly binary to be compiled and
+ /// used to satisfy the `name` instance import. The input `wasm_bytes` may
+ /// either be the wasm text format or the binary format. If the `wat` crate
+ /// feature is enabled, which is enabled by default, then the text format
+ /// will automatically be converted to the binary format.
+ ///
+ /// # Errors
+ ///
+ /// This method will also return an error if `wasm_bytes` is the wasm text
+ /// format and the text syntax is not valid.
+ ///
+ /// # Safety
+ ///
+ /// See [`CodeBuilder::compile_time_builtins_binary`].
+ ///
+ /// # Example
+ ///
+ /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
+ /// compile-time builtins.
+ pub unsafe fn compile_time_builtins_binary_or_text(
+ &mut self,
+ name: impl Into<Cow<'a, str>>,
+ wasm_bytes: impl Into<Cow<'a, [u8]>>,
+ wasm_path: Option<&Path>,
+ ) -> Result<&mut Self> {
+ let wasm_bytes = wasm_bytes.into();
+
+ #[cfg(feature = "wat")]
+ if let Cow::Owned(wasm_bytes) = wat::parse_bytes(&wasm_bytes).map_err(|mut e| {
+ if let Some(path) = wasm_path {
+ e.set_path(path);
+ }
+ e
+ })? {
+ // SAFETY: Same as our unsafe contract.
+ return Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) });
+ }
+
+ // SAFETY: Same as our unsafe contract.
+ Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) })
+ }
+
+ /// Like [`CodeBuilder::compile_time_builtins_binary`], but reads the `file`
+ /// specified for the bytes that will define the compile-time builtin.
+ ///
+ /// # Safety
+ ///
+ /// See [`CodeBuilder::compile_time_builtins_binary`].
+ ///
+ /// # Example
+ ///
+ /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
+ /// compile-time builtins.
+ pub unsafe fn compile_time_builtins_binary_file(
+ &mut self,
+ name: impl Into<Cow<'a, str>>,
+ file: &Path,
+ ) -> Result<&mut Self> {
+ let wasm_bytes = std::fs::read(file)
+ .with_context(|| format!("failed to read file: {}", file.display()))?;
+ // SAFETY: Same as our unsafe contract.
+ Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) })
+ }
+
+ /// Equivalent of [`CodeBuilder::compile_time_builtins_binary_file`] that
+ /// also accepts the WebAssembly text format.
+ ///
+ /// This method is will read the file at the given path and interpret the
+ /// contents to determine if it's the Wasm text format or binary format. The
+ /// file extension is not consulted. The text format is automatically
+ /// converted to the binary format if the crate feature `wat` is active.
+ ///
+ /// # Errors
+ ///
+ /// In addition to the errors returned by
+ /// [`CodeBuilder::compile_time_builtins_binary_file`] this may also fail if
+ /// the text format is read and the syntax is invalid.
+ ///
+ /// # Safety
+ ///
+ /// See [`CodeBuilder::compile_time_builtins_binary`].
+ ///
+ /// # Example
+ ///
+ /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
+ /// compile-time builtins.
+ pub unsafe fn compile_time_builtins_binary_or_text_file(
+ &mut self,
+ name: impl Into<Cow<'a, str>>,
+ file: &Path,
+ ) -> Result<&mut Self> {
+ #[cfg(feature = "wat")]
+ {
+ let wasm = wat::parse_file(file)
+ .with_context(|| format!("error parsing file: {}", file.display()))?;
+ // SAFETY: Same as our unsafe contract.
+ Ok(unsafe { self.compile_time_builtins_binary(name, wasm) })
+ }
+
+ #[cfg(not(feature = "wat"))]
+ {
+ // SAFETY: Same as our unsafe contract.
+ unsafe { self.compile_time_builtins_binary_file(name, file) }
+ }
+ }
+}
diff --git a/crates/wasmtime/src/compile/runtime.rs b/crates/wasmtime/src/compile/runtime.rs
index 794a5029a4..39328ee588 100644
--- a/crates/wasmtime/src/compile/runtime.rs
+++ b/crates/wasmtime/src/compile/runtime.rs
@@ -113,6 +113,13 @@ impl<'a> CodeBuilder<'a> {
self.get_unsafe_intrinsics_import().is_none(),
"`CodeBuilder::expose_unsafe_intrinsics` can only be used with components"
);
+
+ #[cfg(feature = "compile-time-builtins")]
+ ensure!(
+ self.get_compile_time_builtins().is_empty(),
+ "compile-time builtins can only be used with components"
+ );
+
let custom_alignment = self.custom_alignment();
let (code, info_and_types) = self.compile_cached(
|engine, wasm, dwarf, unsafe_intrinsics_import, state| {
diff --git a/deny.toml b/deny.toml
index 5d096c3ec3..399af4036f 100644
--- a/deny.toml
+++ b/deny.toml
@@ -35,7 +35,9 @@ license-files = [
multiple-versions = "deny"
wildcards = "allow"
deny = []
-
+skip = [
+ { name = "heck", reason = "wasm-compose uses an old version of `heck` and was updated in https://github.com/bytecodealliance/wasm-tools/pull/2359, but that hasn't released yet" },
+]
skip-tree = [
# proptest depends on bitflags 1.x.x while other crates depend on 2.x.x so
# ignore its dependency tree until it updates.
diff --git a/supply-chain/audits.toml b/supply-chain/audits.toml
index 9eb63893ab..41e4d4538b 100644
--- a/supply-chain/audits.toml
+++ b/supply-chain/audits.toml
@@ -1555,6 +1555,15 @@ criteria = "safe-to-deploy"
delta = "2.7.0 -> 2.9.4"
notes = "Tweaks to the macro, nothing out of order."
+[[audits.bitmaps]]
+who = "Nick Fitzgerald <[email protected]>"
+criteria = "safe-to-deploy"
+version = "2.1.0"
+notes = """
+No ambient I/O. Minimal unsafe, purely related to simd ISA extensions and
+obviously correct with only local reasoning.
+"""
+
[[audits.block-buffer]]
who = "Benjamin Bouvier <[email protected]>"
criteria = "safe-to-deploy"
@@ -2255,6 +2264,16 @@ criteria = "safe-to-deploy"
delta = "0.1.0 -> 0.1.4"
notes = "Nothing out of the ordinary for a crate finding MSVC tooling."
+[[audits.fixedbitset]]
+who = "Nick Fitzgerald <[email protected]>"
+criteria = "safe-to-deploy"
+version = "0.4.2"
+notes = """
+No ambient I/O. Uses some `unsafe`, but the uses look good and are guarded by
+relevant assertions, although could use some comments and some slight
+refactoring into helpers to dedupe unsafe blocks in my personal opinion.
+"""
+
[[audits.flate2]]
who = "Andrew Brown <[email protected]>"
criteria = "safe-to-deploy"
@@ -3669,6 +3688,11 @@ who = "Pat Hickey <[email protected]>"
criteria = "safe-to-deploy"
version = "1.4.1"
+[[audits.sized-chunks]]
+who = "Nick Fitzgerald <[email protected]>"
+criteria = "safe-to-deploy"
+delta = "0.6.5 -> 0.7.0"
+
[[audits.slab]]
who = "Pat Hickey <[email protected]>"
criteria = "safe-to-deploy"
@@ -4137,6 +4161,12 @@ criteria = "safe-to-run"
delta = "0.236.0 -> 0.237.0"
notes = "The Bytecode Alliance is the author of this crate"
+[[audits.wasm-compose]]
+who = "Nick Fitzgerald <[email protected]>"
+criteria = "safe-to-deploy"
+delta = "0.236.0 -> 0.238.1"
+notes = "Don't know why I have to do this certification even though we have a wildcard audit for this crate because it is authored by the Bytecode Alliance..."
+
[[audits.wasm-compose]]
who = "Alex Crichton <[email protected]>"
criteria = "safe-to-run"
diff --git a/supply-chain/config.toml b/supply-chain/config.toml
index e43b676f68..f43d276c77 100644
--- a/supply-chain/config.toml
+++ b/supply-chain/config.toml
@@ -239,10 +239,6 @@ criteria = "safe-to-deploy"
version = "1.3.2"
criteria = "safe-to-deploy"
-[[exemptions.bitmaps]]
-version = "2.1.0"
-criteria = "safe-to-run"
-
[[exemptions.capstone]]
version = "0.12.0"
criteria = "safe-to-deploy"
@@ -341,6 +337,10 @@ criteria = "safe-to-deploy"
version = "2.1.0"
criteria = "safe-to-deploy"
+[[exemptions.im-rc]]
+version = "15.1.0"
+criteria = "safe-to-deploy"
+
[[exemptions.indicatif]]
version = "0.13.0"
criteria = "safe-to-deploy"
@@ -442,7 +442,7 @@ criteria = "safe-to-deploy"
[[exemptions.petgraph]]
version = "0.6.5"
-criteria = "safe-to-run"
+criteria = "safe-to-deploy"
[[exemptions.ppv-lite86]]
version = "0.2.16"
@@ -468,6 +468,10 @@ criteria = "safe-to-deploy"
version = "0.3.0"
criteria = "safe-to-deploy"
+[[exemptions.rand_xoshiro]]
+version = "0.6.0"
+criteria = "safe-to-deploy"
+
[[exemptions.rand_xoshiro]]
version = "0.6.0"
criteria = "safe-to-run"
@@ -528,6 +532,10 @@ criteria = "safe-to-deploy"
version = "0.3.7"
criteria = "safe-to-deploy"
+[[exemptions.sized-chunks]]
+version = "0.6.5"
+criteria = "safe-to-deploy"
+
[[exemptions.sized-chunks]]
version = "0.6.5"
criteria = "safe-to-run"
diff --git a/tests/all/compile_time_builtins.rs b/tests/all/compile_time_builtins.rs
new file mode 100644
index 0000000000..3218538d44
--- /dev/null
+++ b/tests/all/compile_time_builtins.rs
@@ -0,0 +1,265 @@
+use super::*;
+use std::path::Path;
+use wasmtime::*;
+
+#[test]
+#[cfg_attr(miri, ignore)]
+fn smoke() -> Result<()> {
+ let engine = Engine::default();
+ let linker = component::Linker::new(&engine);
+
+ let component = unsafe {
+ CodeBuilder::new(&engine)
+ .expose_unsafe_intrinsics("unsafe-intrinsics")
+ .compile_time_builtins_binary_or_text(
+ "host-api",
+ r#"
+ (component
+ (import "unsafe-intrinsics"
+ (instance $intrinsics
+ (export "store-data-address" (func (result u64)))
+ (export "u8-native-load" (func (param "pointer" u64) (result u8)))
+ )
+ )
+
+ (core func $store-data-address' (canon lower (func $intrinsics "store-data-address")))
+ (core func $u8-native-load' (canon lower (func $intrinsics "u8-native-load")))
+
+ (core module $m
+ (import "" "store-data-address" (func $store-data-address (result i64)))
+ (import "" "u8-native-load" (func $u8-native-load (param i64) (result i32)))
+ (func (export "get") (result i32)
+ (call $u8-native-load (call $store-data-address))
+ )
+ )
+
+ (core instance $i
+ (instantiate $m
+ (with "" (instance (export "store-data-address" (func $store-data-address'))
+ (export "u8-native-load" (func $u8-native-load'))))
+ )
+ )
+
+ (func (export "get") (result u8)
+ (canon lift (core func $i "get"))
+ )
+ )
+ "#.as_bytes(),
+ Some(Path::new("host-api.wat")),
+ )?
+ .wasm_binary_or_text(
+ r#"
+ (component
+ (import "host-api"
+ (instance $host-api
+ (export "get" (func (result u8)))
+ )
+ )
+
+ (core func $get' (canon lower (func $host-api "get")))
+
+ (core module $m
+ (import "" "get" (func $get (result i32)))
+ (func (export "double-get") (result i32)
+ (i32.add (call $get) (call $get))
+ )
+ )
+
+ (core instance $i
+ (instantiate $m (with "" (instance (export "get" (func $get')))))
+ )
+
+ (func (export "double-get") (result u8)
+ (canon lift (core func $i "double-get"))
+ )
+ )
+ "#.as_bytes(),
+ Some(Path::new("main.wat")),
+ )?
+ .compile_component()?
+ };
+
+ let mut store = Store::new(&engine, 42_u8);
+ let instance = linker.instantiate(&mut store, &component)?;
+
+ let (result,) = instance
+ .get_typed_func::<(), (u8,)>(&mut store, "double-get")?
+ .call(&mut store, ())?;
+ assert_eq!(result, 84);
+
+ Ok(())
+}
+
+#[test]
+#[cfg_attr(miri, ignore)]
+fn unused_compile_time_builtins() -> Result<()> {
+ let engine = Engine::default();
+ let linker = component::Linker::new(&engine);
+
+ let component = unsafe {
+ CodeBuilder::new(&engine)
+ .expose_unsafe_intrinsics("unsafe-intrinsics")
+ .compile_time_builtins_binary_or_text(
+ "host-api",
+ "(component)".as_bytes(),
+ Some(Path::new("host-api.wat")),
+ )?
+ .wasm_binary_or_text(
+ r#"
+ (component
+ (core module $m
+ (func (export "foo") (result i32)
+ (i32.const 42)
+ )
+ )
+
+ (core instance $i (instantiate $m))
+
+ (func (export "foo") (result u8)
+ (canon lift (core func $i "foo"))
+ )
+ )
+ "#
+ .as_bytes(),
+ Some(Path::new("main.wat")),
+ )?
+ .compile_component()?
+ };
+
+ let mut store = Store::new(&engine, ());
+ let instance = linker.instantiate(&mut store, &component)?;
+
+ let (result,) = instance
+ .get_typed_func::<(), (u8,)>(&mut store, "foo")?
+ .call(&mut store, ())?;
+ assert_eq!(result, 42);
+
+ Ok(())
+}
+
+#[test]
+#[cfg_attr(miri, ignore)]
+fn multiple_compile_time_builtins() -> Result<()> {
+ let engine = Engine::default();
+ let linker = component::Linker::new(&engine);
+
+ let component = unsafe {
+ CodeBuilder::new(&engine)
+ .expose_unsafe_intrinsics("unsafe-intrinsics")
+ .compile_time_builtins_binary_or_text(
+ "host-api1",
+ "(component)".as_bytes(),
+ Some(Path::new("host-api1.wat")),
+ )?
+ .compile_time_builtins_binary_or_text(
+ "host-api2",
+ "(component)".as_bytes(),
+ Some(Path::new("host-api2.wat")),
+ )?
+ .compile_time_builtins_binary_or_text(
+ "host-api3",
+ "(component)".as_bytes(),
+ Some(Path::new("host-api3.wat")),
+ )?
+ .wasm_binary_or_text(
+ r#"
+ (component
+ (import "host-api2" (instance))
+ (import "host-api3" (instance))
+
+ (core module $m
+ (func (export "foo") (result i32)
+ (i32.const 42)
+ )
+ )
+
+ (core instance $i (instantiate $m))
+
+ (func (export "foo") (result u8)
+ (canon lift (core func $i "foo"))
+ )
+ )
+ "#
+ .as_bytes(),
+ Some(Path::new("main.wat")),
+ )?
+ .compile_component()?
+ };
+
+ let mut store = Store::new(&engine, ());
+ let instance = linker.instantiate(&mut store, &component)?;
+
+ let (result,) = instance
+ .get_typed_func::<(), (u8,)>(&mut store, "foo")?
+ .call(&mut store, ())?;
+ assert_eq!(result, 42);
+
+ Ok(())
+}
+
+#[test]
+#[cfg_attr(miri, ignore)]
+fn main_wasm_cannot_use_intrinsics() -> Result<()> {
+ let engine = Engine::default();
+
+ let err = unsafe {
+ CodeBuilder::new(&engine)
+ .expose_unsafe_intrinsics("unsafe-intrinsics")
+ .compile_time_builtins_binary_or_text(
+ "host-api",
+ "(component)".as_bytes(),
+ Some(Path::new("host-api.wat")),
+ )?
+ .wasm_binary_or_text(
+ r#"
+ (component
+ (import "unsafe-intrinsics" (instance $intrinsics))
+ )
+ "#
+ .as_bytes(),
+ Some(Path::new("main.wat")),
+ )?
+ .compile_component()
+ .map(|_| ())
+ .unwrap_err()
+ };
+
+ err.assert_contains("main Wasm cannot import the unsafe intrinsics");
+ Ok(())
+}
+
+#[test]
+#[cfg_attr(miri, ignore)]
+fn import_erased() -> Result<()> {
+ let engine = Engine::default();
+
+ let component = unsafe {
+ CodeBuilder::new(&engine)
+ .expose_unsafe_intrinsics("unsafe-intrinsics")
+ .compile_time_builtins_binary_or_text(
+ "compile-time-api",
+ "(component)".as_bytes(),
+ Some(Path::new("compile-time-api.wat")),
+ )?
+ .wasm_binary_or_text(
+ r#"
+ (component
+ (import "compile-time-api" (instance))
+ (import "link-time-api" (instance))
+ )
+ "#
+ .as_bytes(),
+ Some(Path::new("main.wat")),
+ )?
+ .compile_component()?
+ };
+
+ let component_type = component.component_type();
+ let imports = component_type
+ .imports(&engine)
+ .map(|(name, _ty)| name)
+ .collect::<Vec<_>>();
+ assert_eq!(imports, ["link-time-api"]);
+
+ Ok(())
+}
diff --git a/tests/all/intrinsics.rs b/tests/all/intrinsics.rs
index 0c67749edb..c6a73f6786 100644
--- a/tests/all/intrinsics.rs
+++ b/tests/all/intrinsics.rs
@@ -16,7 +16,6 @@ fn native_loads_and_stores() -> Result<()> {
("u32", "i32"),
("u64", "i64"),
] {
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::native_loads_and_stores::{comp_ty}");
let path = Path::new(&path);
let wat = format!(
@@ -66,6 +65,7 @@ fn native_loads_and_stores() -> Result<()> {
)
"#
);
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -163,8 +163,6 @@ fn ref_func_of_intrinsic() -> Result<()> {
config.wasm_gc(true);
let engine = Engine::new(&config)?;
- let mut code_builder = CodeBuilder::new(&engine);
-
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -200,6 +198,8 @@ fn ref_func_of_intrinsic() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -224,8 +224,6 @@ fn ref_func_of_intrinsic() -> Result<()> {
fn table_element_segment_with_intrinsic() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
-
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -260,6 +258,8 @@ fn table_element_segment_with_intrinsic() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -283,7 +283,6 @@ fn table_element_segment_with_intrinsic() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn intrinsics_not_listed_in_imports() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -297,6 +296,8 @@ fn intrinsics_not_listed_in_imports() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -314,7 +315,6 @@ fn intrinsics_not_listed_in_imports() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn unknown_intrinsic_function() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -328,6 +328,8 @@ fn unknown_intrinsic_function() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -346,7 +348,6 @@ fn unknown_intrinsic_function() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_extra_param() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -360,6 +361,8 @@ fn bad_extra_param() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -381,7 +384,6 @@ fn bad_extra_param() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_missing_param() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -395,6 +397,8 @@ fn bad_missing_param() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -416,7 +420,6 @@ fn bad_missing_param() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_missing_return() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -430,6 +433,8 @@ fn bad_missing_return() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -451,7 +456,6 @@ fn bad_missing_return() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_extra_return() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -465,6 +469,8 @@ fn bad_extra_return() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -486,7 +492,6 @@ fn bad_extra_return() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_param_type() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -500,6 +505,8 @@ fn bad_param_type() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -521,7 +528,6 @@ fn bad_param_type() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn bad_result_type() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let path = format!("intrinsics::ref_func_of_intrinsic");
let path = Path::new(&path);
@@ -535,6 +541,8 @@ fn bad_result_type() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), Some(path))?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -556,7 +564,6 @@ fn bad_result_type() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn store_data_address() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let wat = r#"
(component
@@ -600,6 +607,8 @@ fn store_data_address() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), None)?;
unsafe {
code_builder.expose_unsafe_intrinsics("unsafe-intrinsics");
@@ -622,7 +631,6 @@ fn store_data_address() -> Result<()> {
#[cfg_attr(miri, ignore)]
fn other_import_name() -> Result<()> {
let engine = Engine::default();
- let mut code_builder = CodeBuilder::new(&engine);
let wat = r#"
(component
@@ -633,6 +641,8 @@ fn other_import_name() -> Result<()> {
)
)
"#;
+
+ let mut code_builder = CodeBuilder::new(&engine);
code_builder.wasm_binary_or_text(wat.as_bytes(), None)?;
unsafe {
code_builder.expose_unsafe_intrinsics("other-name");
diff --git a/tests/all/main.rs b/tests/all/main.rs
index 3e2803baa7..820dbc6ba8 100644
--- a/tests/all/main.rs
+++ b/tests/all/main.rs
@@ -7,6 +7,7 @@ mod async_functions;
mod call_hook;
mod cli_tests;
mod code_too_large;
+mod compile_time_builtins;
mod component_model;
mod coredump;
mod custom_code_memory;