Skip to main content

standard_plugin_cli/
component.rs

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