Skip to content

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

explore: Support components (#14426)

Adam Bratschi-Kaye1eab66350732
diff --git a/Cargo.lock b/Cargo.lock
index 5b9cb2ae52..e8a81c6e25 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4942,9 +4942,11 @@ dependencies = [
"serde_derive",
"serde_json",
"target-lexicon 0.13.5",
+ "tempfile",
"wasmprinter",
"wasmtime",
"wasmtime-environ",
+ "wat",
]
[[package]]
diff --git a/crates/explorer/Cargo.toml b/crates/explorer/Cargo.toml
index d199bf7679..9cd7785f28 100644
--- a/crates/explorer/Cargo.toml
+++ b/crates/explorer/Cargo.toml
@@ -19,5 +19,9 @@ serde_derive = { workspace = true }
serde_json = { workspace = true }
target-lexicon = { workspace = true, features = ['std'] }
wasmprinter = { workspace = true }
-wasmtime = { workspace = true, features = ["anyhow", "cranelift", "runtime"] }
+wasmtime = { workspace = true, features = ["anyhow", "component-model", "cranelift", "runtime"] }
wasmtime-environ = { workspace = true, features = ["anyhow"] }
+
+[dev-dependencies]
+tempfile = { workspace = true }
+wat = { workspace = true }
diff --git a/crates/explorer/src/index.js b/crates/explorer/src/index.js
index 827e362a9e..6732fcb343 100644
--- a/crates/explorer/src/index.js
+++ b/crates/explorer/src/index.js
@@ -226,11 +226,13 @@ if (clifElem) {
const funcHeader = document.createElement("h3");
let func_name =
- func.name === null ? `function[${func.func_index}]` : func.name;
+ func.name === null
+ ? `wasm[${func.module_index}]::function[${func.func_index}]`
+ : func.name;
let demangled_name =
func.demangled_name !== null ? func.demangled_name : func_name;
funcHeader.textContent = `Intermediate Representation of function <${demangled_name}>:`;
- funcHeader.title = `Function ${func.func_index}: ${func_name}`;
+ funcHeader.title = `Module ${func.module_index}, function ${func.func_index}: ${func_name}`;
funcElem.appendChild(funcHeader);
for (const inst of func.instructions) {
@@ -255,11 +257,13 @@ for (const func of state.asm.functions) {
const funcHeader = document.createElement("h3");
let functionName =
- func.name === null ? `function[${func.func_index}]` : func.name;
+ func.name === null
+ ? `wasm[${func.module_index}]::function[${func.func_index}]`
+ : func.name;
let demangledName =
func.demangled_name !== null ? func.demangled_name : functionName;
funcHeader.textContent = `Disassembly of function <${demangledName}>:`;
- funcHeader.title = `Function ${func.func_index}: ${functionName}`;
+ funcHeader.title = `Module ${func.module_index}, function ${func.func_index}: ${functionName}`;
funcElem.appendChild(funcHeader);
let currentBlock = createDivForCode();
diff --git a/crates/explorer/src/lib.rs b/crates/explorer/src/lib.rs
index 7cf03c49b5..c2ddeae892 100644
--- a/crates/explorer/src/lib.rs
+++ b/crates/explorer/src/lib.rs
@@ -8,13 +8,14 @@
use capstone::arch::BuildsCapstone;
use serde_derive::Serialize;
use std::{
+ collections::HashMap,
fs::File,
io::{Write, read_to_string},
- path::Path,
+ path::{Path, PathBuf},
str::FromStr,
};
-use wasmtime::{Result, ToWasmtimeResult as _};
-use wasmtime_environ::demangle_function_name;
+use wasmtime::{ModuleFunction, Result, ToWasmtimeResult as _};
+use wasmtime_environ::{demangle_function_name, wasmparser};
pub fn generate(
config: &wasmtime::Config,
@@ -126,6 +127,7 @@ struct AnnotatedAsm {
#[derive(Serialize, Debug)]
struct AnnotatedFunction {
+ module_index: u32,
func_index: u32,
name: Option<String>,
demangled_name: Option<String>,
@@ -141,16 +143,49 @@ struct AnnotatedInstruction {
operands: Option<String>,
}
+enum CompilationArtifact {
+ Module(wasmtime::Module),
+ Component(wasmtime::component::Component),
+}
+
+impl CompilationArtifact {
+ fn text(&self) -> &[u8] {
+ match self {
+ CompilationArtifact::Module(module) => module.text(),
+ CompilationArtifact::Component(component) => component.text(),
+ }
+ }
+ fn address_map(&self) -> Option<Box<dyn Iterator<Item = (usize, Option<u32>)> + '_>> {
+ match self {
+ CompilationArtifact::Module(module) => module
+ .address_map()
+ .map(|i| Box::new(i) as Box<dyn Iterator<Item = _>>),
+ CompilationArtifact::Component(component) => component
+ .address_map()
+ .map(|i| Box::new(i) as Box<dyn Iterator<Item = _>>),
+ }
+ }
+ fn functions(&self) -> Box<dyn Iterator<Item = ModuleFunction> + '_> {
+ match self {
+ CompilationArtifact::Module(module) => Box::new(module.functions()),
+ CompilationArtifact::Component(component) => Box::new(component.functions()),
+ }
+ }
+}
fn annotate_asm(
config: &wasmtime::Config,
target: &target_lexicon::Triple,
wasm: &[u8],
) -> Result<AnnotatedAsm> {
let engine = wasmtime::Engine::new(config)?;
- let module = wasmtime::Module::new(&engine, wasm)?;
+ let artifact = if wasmparser::Parser::is_component(wasm) {
+ CompilationArtifact::Component(wasmtime::component::Component::new(&engine, wasm)?)
+ } else {
+ CompilationArtifact::Module(wasmtime::Module::new(&engine, wasm)?)
+ };
- let text = module.text();
- let address_map: Vec<_> = module
+ let text = artifact.text();
+ let address_map: Vec<_> = artifact
.address_map()
.ok_or_else(|| wasmtime::format_err!("address maps must be enabled in the config"))?
.collect();
@@ -174,7 +209,7 @@ fn annotate_asm(
current_entry.and_then(|entry| entry.1.map(WasmOffset))
};
- let functions = module
+ let functions = artifact
.functions()
.map(|function| {
let body = &text[function.offset..][..function.len];
@@ -239,6 +274,7 @@ fn annotate_asm(
};
Ok(AnnotatedFunction {
+ module_index: function.module.as_u32(),
func_index: function.index.as_u32(),
name: function.name,
demangled_name,
@@ -257,6 +293,7 @@ struct AnnotatedClif {
#[derive(Serialize, Debug)]
struct AnnotatedClifFunction {
+ module_index: u32,
func_index: u32,
name: Option<String>,
demangled_name: Option<String>,
@@ -270,15 +307,16 @@ struct AnnotatedClifInstruction {
}
fn annotate_clif(clif_dir: &Path, asm: &AnnotatedAsm) -> Result<AnnotatedClif> {
+ let clif_files = ClifFiles::new(clif_dir)?;
let mut clif = AnnotatedClif {
functions: Vec::new(),
};
for function in &asm.functions {
- let function_path = clif_dir.join(format!("wasm_func_{}.clif", function.func_index));
- if !function_path.exists() {
+ let Some(function_path) = clif_files.get(function.module_index, function.func_index) else {
continue;
- }
+ };
let mut clif_function = AnnotatedClifFunction {
+ module_index: function.module_index,
func_index: function.func_index,
name: function.name.clone(),
demangled_name: function.demangled_name.clone(),
@@ -305,3 +343,109 @@ fn annotate_clif(clif_dir: &Path, asm: &AnnotatedAsm) -> Result<AnnotatedClif> {
}
Ok(clif)
}
+
+/// Cache the mapping from module + function indices to clif file path.
+struct ClifFiles {
+ paths: HashMap<(u32, u32), PathBuf>,
+}
+
+impl ClifFiles {
+ fn new(clif_dir: &Path) -> Result<Self> {
+ let mut paths = HashMap::new();
+ for entry in clif_dir.read_dir()? {
+ let path = entry?.path();
+ let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
+ continue;
+ };
+ let Some(key) = parse_clif_filename(file_name) else {
+ continue;
+ };
+ if let Some(previous) = paths.insert(key, path.clone()) {
+ panic!(
+ "multiple CLIF files for wasm[{}]::function[{}]: {:?} and {:?}",
+ key.0, key.1, previous, path,
+ );
+ }
+ }
+ Ok(Self { paths })
+ }
+
+ fn get(&self, module_index: u32, func_index: u32) -> Option<&Path> {
+ self.paths
+ .get(&(module_index, func_index))
+ .map(PathBuf::as_path)
+ }
+}
+
+/// Parse the expected filename `wasm[<mod>]--function[<fn>]--<name>.clif` to
+/// extract the indices <mod> and <fn>.
+fn parse_clif_filename(file_name: &str) -> Option<(u32, u32)> {
+ let file_name = file_name.strip_suffix(".clif")?;
+ let file_name = file_name.strip_prefix("wasm[")?;
+ let (module_index, file_name) = file_name.split_once("]--function[")?;
+ let (func_index, name) = file_name.split_once(']')?;
+ if !name.is_empty() && !name.starts_with("--") {
+ return None;
+ }
+ Some((module_index.parse().ok()?, func_index.parse().ok()?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{ClifFiles, parse_clif_filename};
+ use tempfile::tempdir;
+
+ #[test]
+ fn parses_clif_filenames_for_modules_and_components() {
+ assert_eq!(
+ parse_clif_filename("wasm[0]--function[3].clif"),
+ Some((0, 3))
+ );
+ assert_eq!(
+ parse_clif_filename("wasm[4]--function[27]--some-name.clif"),
+ Some((4, 27))
+ );
+ assert_eq!(
+ parse_clif_filename("array_to_wasm_trampoline[0].clif"),
+ None
+ );
+ }
+
+ #[test]
+ fn finds_emitted_module_clif() {
+ let clif_dir = tempdir().unwrap();
+ let mut config = wasmtime::Config::new();
+ config.emit_clif(clif_dir.path());
+ let engine = wasmtime::Engine::new(&config).unwrap();
+ let wasm = wat::parse_str("(module (func $f) (func $g))").unwrap();
+ wasmtime::Module::new(&engine, wasm).unwrap();
+
+ let files = ClifFiles::new(clif_dir.path()).unwrap();
+ assert!(files.get(0, 0).is_some());
+ assert!(files.get(0, 1).is_some());
+ assert!(files.get(1, 0).is_none());
+ assert!(files.get(0, 2).is_none());
+ }
+
+ #[test]
+ fn finds_emitted_component_clif() {
+ let clif_dir = tempdir().unwrap();
+ let mut config = wasmtime::Config::new();
+ config.emit_clif(clif_dir.path());
+ let engine = wasmtime::Engine::new(&config).unwrap();
+ let wasm = wat::parse_str(
+ "(component
+ (core module (func $first))
+ (core module (func $second) (func $third))
+ )",
+ )
+ .unwrap();
+ wasmtime::component::Component::new(&engine, wasm).unwrap();
+
+ let files = ClifFiles::new(clif_dir.path()).unwrap();
+ assert!(files.get(0, 0).is_some());
+ assert!(files.get(1, 0).is_some());
+ assert!(files.get(1, 1).is_some());
+ assert!(files.get(0, 1).is_none());
+ }
+}