wasi_virt_layer_cli/generator/
abi_connect.rs

1use crate::{
2    abi::Wasip1ABIFunc,
3    generator::Generator,
4    util::{WalrusFID, WalrusUtilExport, WalrusUtilModule},
5};
6
7/// Connect Wasip1 ABI
8/// If an import exists, add the corresponding export.
9/// If it does not exist, remove that export if it exists.
10/// Require before PatchComponent
11#[derive(Debug, Default)]
12pub struct ConnectWasip1ABI;
13
14impl Generator for ConnectWasip1ABI {
15    /// todo!();
16    /// It must be placed before the patch_component.
17    fn pre_vfs(
18        &mut self,
19        module: &mut walrus::Module,
20        ctx: &super::GeneratorCtx,
21    ) -> eyre::Result<()> {
22        for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
23            let export_name = format!("__wasip1_vfs___self_{import}");
24            let export = export_name.get_fid(&module.exports).ok();
25
26            if let Some(import_id) = (
27                // CORE_MODULE_ROOT,
28                // &format!("[static]wasip1.{}-import", import.replace("_", "-")),
29                "wasi_snapshot_preview1",
30                import,
31            )
32                .get_fid(&module.imports)
33                .ok()
34            {
35                if let Some(_) = export {
36                    module.connect_func_alt_with_remove_export(
37                        import_id,
38                        export_name,
39                        ctx.unstable_print_debug,
40                    )?;
41                } else {
42                    log::warn!("No export found for Wasip1 ABI import self: {import}");
43                }
44            } else {
45                if let Some(_) = export {
46                    module.exports.remove(export_name).unwrap();
47                }
48            }
49        }
50
51        Ok(())
52    }
53
54    fn pre_target(
55        &mut self,
56        module: &mut walrus::Module,
57        _: &crate::generator::GeneratorCtx,
58        external: &crate::generator::ModuleExternal,
59    ) -> eyre::Result<()> {
60        module
61            .imports
62            .iter_mut()
63            .filter(|import| {
64                <Wasip1ABIFunc as strum::VariantNames>::VARIANTS.contains(&import.name.as_str())
65                    && import.module == "wasi_snapshot_preview1"
66            })
67            .for_each(|import| {
68                import.name = format!("__wasip1_vfs_{}_{}", external.name, import.name);
69            });
70
71        Ok(())
72    }
73
74    fn post_combine(
75        &mut self,
76        module: &mut walrus::Module,
77        ctx: &crate::generator::GeneratorCtx,
78    ) -> eyre::Result<()> {
79        for wasm in &ctx.target_names {
80            for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
81                let export_name = format!("__wasip1_vfs_{wasm}_{import}");
82                if let Some(import_id) = ("wasi_snapshot_preview1", import)
83                    .get_fid(&module.imports)
84                    .ok()
85                {
86                    unreachable!();
87                    // module.connect_func_alt(import_id, &export_name, ctx.unstable_print_debug)?;
88                } else {
89                    module
90                        .exports
91                        .erase_with(&export_name, ctx.unstable_print_debug)
92                        .ok();
93                }
94            }
95        }
96        Ok(())
97    }
98}
99
100#[derive(Debug, Default)]
101pub struct ConnectWasip1ThreadsABI;
102
103impl Generator for ConnectWasip1ThreadsABI {
104    fn post_combine(
105        &mut self,
106        module: &mut walrus::Module,
107        ctx: &crate::generator::GeneratorCtx,
108    ) -> eyre::Result<()> {
109        if ctx.threads {
110            for wasm in &ctx.target_names {
111                if format!("__wasip1_vfs_wasi_thread_start_{wasm}")
112                    .get_fid(&module.exports)
113                    .ok()
114                    .is_some()
115                {
116                    module.connect_func_alt_with_remove_export(
117                        (
118                            "wasip1-vfs",
119                            &format!("__wasip1_vfs_{wasm}_wasi_thread_start"),
120                        ),
121                        &format!("__wasip1_vfs_wasi_thread_start_{wasm}"),
122                        ctx.unstable_print_debug,
123                    )?;
124
125                    module.exports.erase_with(
126                        &format!("__wasip1_vfs_{wasm}_wasi_thread_start_anchor"),
127                        ctx.unstable_print_debug,
128                    )?;
129
130                    module.connect_func_alt_with_remove_export(
131                        ("wasi", &format!("__wasip1_vfs_wasi_thread_spawn_{wasm}")),
132                        &format!("__wasip1_vfs_wasi_thread_spawn_{wasm}"),
133                        ctx.unstable_print_debug,
134                    )?;
135                }
136            }
137        }
138        Ok(())
139    }
140}
141
142/// Require before PatchComponent
143/// Require after ConnectWasip1ABI
144#[derive(Debug, Default)]
145pub struct NonRecursiveWasiABI;
146
147impl Generator for NonRecursiveWasiABI {
148    fn pre_vfs(
149        &mut self,
150        module: &mut walrus::Module,
151        _: &super::GeneratorCtx,
152    ) -> eyre::Result<()> {
153        for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
154            if let Some(fid) = ("non_recursive_wasi_snapshot_preview1", import)
155                .get_fid(&module.imports)
156                .ok()
157            {
158                // If it already exists, make it possible to call it.
159                if let Some(import_id) = ("wasi_snapshot_preview1", import)
160                    .get_fid(&module.imports)
161                    .ok()
162                {
163                    module.renew_call_fn(fid, import_id)?;
164                } else {
165                    let import_id = module.imports.get_imported_func(fid).unwrap().id();
166                    let import = module.imports.get_mut(import_id);
167                    import.module = "wasi_snapshot_preview1".to_string();
168                }
169            }
170        }
171
172        module
173            .imports
174            .iter()
175            .filter(|import| import.module == "non_recursive_wasi_snapshot_preview1")
176            .map(|import| &import.name)
177            .for_each(|name| {
178                log::warn!(
179                    "Non-recursive Wasip1 ABI import exists: {name}, but this is not verified."
180                );
181            });
182
183        Ok(())
184    }
185}