Skip to main content

wasi_virt_layer_cli/generator/
vfs_host.rs

1use crate::util::WalrusUtilModule as _;
2use super::{Generator, GeneratorCtx};
3
4/// Generator that connects imports from `__wasip1_vfs-host` to identical exports if they exist.
5///
6/// This is used when the VFS (or another module) wants to call a function that is expected
7/// to be provided by the host or another merged module, using a specific "host" module name.
8#[derive(Debug, Default)]
9pub struct ConnectVfsHost;
10
11impl Generator for ConnectVfsHost {
12    fn post_combine(
13        &mut self,
14        module: &mut walrus::Module,
15        _ctx: &GeneratorCtx,
16    ) -> eyre::Result<()> {
17        let imports_to_resolve = module
18            .imports
19            .iter()
20            .filter_map(|import| {
21                if import.module == "__wasip1_vfs-host" {
22                    if let walrus::ImportKind::Function(import_fid) = import.kind {
23                        return Some((import.id(), import.name.clone(), import_fid));
24                    }
25                }
26                None
27            })
28            .collect::<Vec<_>>();
29
30        for (_, name, import_fid) in imports_to_resolve {
31            let export_fid = module.exports.iter().find_map(|export| {
32                if export.name == name {
33                    if let walrus::ExportItem::Function(export_fid) = export.item {
34                        return Some(export_fid);
35                    }
36                }
37                None
38            });
39
40            if let Some(export_fid) = export_fid {
41                log::info!("Connecting __wasip1_vfs-host import '{}' to matching export.", name);
42                // Connect the import to the export without removing the export.
43                module.connect_func_without_remove(import_fid, export_fid)?;
44            }
45        }
46        Ok(())
47    }
48}