1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//! What a built component imports and exports.
use std::collections::{BTreeMap, BTreeSet};
use wasmparser::{Parser, Payload};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ComponentShape {
/// Top-level instance and function import names
/// (`standard:plugin/values@2.0.0`, `wasi:...`).
pub imports: Vec<String>,
/// Top-level type imports (`event`, `json`): bound to a type the
/// component defines, they need nothing from the host.
pub type_imports: Vec<String>,
/// Top-level export names (`activate`, ...).
pub exports: Vec<String>,
/// The instance imports the component takes at least one function
/// from; an interface imported only for its types (`account` for the
/// daemon world's `pane`) is not among them.
pub function_imports: Vec<String>,
/// The functions the component takes from each instance import. The
/// component model imports only what a component calls, so a function
/// missing here is one the plugin never calls. Empty when the validator
/// refuses the component.
pub functions: BTreeMap<String, BTreeSet<String>>,
}
impl ComponentShape {
/// The functions taken from the plugin interface `interface`
/// (`surface`), when the component imports it and could be read.
pub fn plugin_functions(&self, interface: &str) -> Option<&BTreeSet<String>> {
let prefix = format!("standard:plugin/{interface}@");
self.functions
.iter()
.find(|(import, _)| import.starts_with(&prefix))
.map(|(_, functions)| functions)
}
}
/// The functions each instance import carries, by validating the component
/// and reading each import's instance type; `None` for a component the
/// validator refuses.
fn import_functions(
bytes: &[u8],
imports: &[String],
) -> Option<BTreeMap<String, BTreeSet<String>>> {
use wasmparser::component_types::ComponentEntityType;
let mut validator = wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all());
let types = validator.validate_all(bytes).ok()?;
Some(
imports
.iter()
.filter_map(|name| {
let item = types.component_item_for_import(name)?;
let ComponentEntityType::Instance(id) = item.ty else {
return None;
};
let functions = types[id]
.exports
.iter()
.filter(|(_, item)| matches!(item.ty, ComponentEntityType::Func(_)))
.map(|(function, _)| function.to_string())
.collect();
Some((name.clone(), functions))
})
.collect(),
)
}
/// Reads a component's top-level imports and exports. An error names why
/// the bytes are not a component.
pub fn inspect(bytes: &[u8]) -> Result<ComponentShape, String> {
let mut shape = ComponentShape::default();
let mut depth = 0usize;
for payload in Parser::new(0).parse_all(bytes) {
let payload = payload.map_err(|error| format!("not a valid wasm binary: {error}"))?;
match payload {
Payload::Version { encoding, .. } if depth == 0 => {
if encoding != wasmparser::Encoding::Component {
return Err(
"a core wasm module, not a component: build for wasm32-wasip2".into(),
);
}
}
Payload::ModuleSection { .. } | Payload::ComponentSection { .. } => depth += 1,
Payload::End(_) => depth = depth.saturating_sub(1),
Payload::ComponentImportSection(reader) if depth == 0 => {
for import in reader {
let import = import.map_err(|error| error.to_string())?;
let name = import.name.name.to_string();
if matches!(import.ty, wasmparser::ComponentTypeRef::Type(_)) {
shape.type_imports.push(name);
} else {
shape.imports.push(name);
}
}
}
Payload::ComponentExportSection(reader) if depth == 0 => {
for export in reader {
let export = export.map_err(|error| error.to_string())?;
shape.exports.push(export.name.name.to_string());
}
}
_ => {}
}
}
// A component the validator refuses counts every instance import, so
// `check` still reports the grants they need.
match import_functions(bytes, &shape.imports) {
Some(functions) => {
shape.function_imports = shape
.imports
.iter()
.filter(|name| {
functions
.get(*name)
.is_none_or(|functions| !functions.is_empty())
})
.cloned()
.collect();
shape.functions = functions;
}
None => shape.function_imports = shape.imports.clone(),
}
Ok(shape)
}