Skip to main content

wasi_virt_layer_cli/generator/
abi_connect.rs

1use itertools::Itertools;
2use strum::VariantNames;
3
4use crate::{
5    abi::{Wasip1ABIFunc, Wasip1ThreadsABIExportFunc, Wasip1ThreadsABIFunc},
6    generator::{Generator, threads::ThreadsSpawnName},
7    unique_name::UniqueName,
8    util::{
9        ResultUtil as _, WalrusFID, WalrusFIDAssister as _, WalrusUtilExport, WalrusUtilImport,
10        WalrusUtilModule, WasmName, gen_component_name,
11    },
12};
13use eyre::WrapErr as _;
14
15/// Abstraction over internal representation name generations for hooking WASI implementations.
16#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
17#[strum(serialize_all = "snake_case")]
18pub enum Wasip1ABIName<'a> {
19    #[strum(serialize = "__self")]
20    /// Reference to a self-contained import.
21    SelfDefault {
22        /// Identifier string representation of the import.
23        import: &'a str,
24    },
25    #[strum(serialize = "")]
26    /// Temporarily constructed linking to a specified module during intermediate compilation.
27    TargetTemporal {
28        /// Specific wasm module binding origin.
29        wasm: &'a WasmName,
30        /// Specific imported signature target.
31        import: &'a str,
32    },
33}
34
35/// Connect Wasip1 ABI
36/// If an import exists, add the corresponding export.
37/// If it does not exist, remove that export if it exists.
38/// Require before PatchComponent
39///
40/// **Why this is needed:**
41/// WASI functions (like `fd_read`, `environ_get`) imported by the target module must be
42/// fulfilled by the VFS (Virtual File System) layer. This generator automatically scans
43/// for all potential `wasi_snapshot_preview1` imports and maps them to the corresponding
44/// exports (`__wasip1_vfs_...`) exposed by the virtualization core. Missing imports or
45/// unused exports are pruned to keep the ABI clean.
46#[derive(Debug, Default)]
47pub struct ConnectWasip1ABI;
48
49impl Generator for ConnectWasip1ABI {
50    /// todo!();
51    /// It must be placed before the patch_component.
52    fn pre_vfs(
53        &mut self,
54        module: &mut walrus::Module,
55        ctx: &super::GeneratorCtx,
56    ) -> eyre::Result<()> {
57        for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
58            let export = UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import })
59                .get_fid(&module.exports)
60                .ok();
61
62            if let Some(import_id) = (
63                // CORE_MODULE_ROOT,
64                // &format!("[static]wasip1.{}-import", import.replace("_", "-")),
65                UniqueName::WASIP1_ABI_MODULE,
66                import,
67            )
68                .get_fid(&module.imports)
69                .ok()
70            {
71                if let Some(_) = export {
72                    module.connect_func_alt_with_remove_export(
73                        import_id,
74                        &UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import }).to_string(),
75                        ctx.unstable_print_debug,
76                    )?;
77                } else {
78                    log::warn!("No plug found for Wasip1 ABI import self: {import}");
79                }
80            } else {
81                if let Some(_) = export {
82                    module
83                        .exports
84                        .remove(
85                            &UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import })
86                                .to_string(),
87                        )
88                        .unwrap();
89                }
90            }
91        }
92
93        Ok(())
94    }
95
96    fn pre_target(
97        &mut self,
98        module: &mut walrus::Module,
99        _: &crate::generator::GeneratorCtx,
100        external: &crate::generator::ModuleExternal,
101    ) -> eyre::Result<()> {
102        module
103            .imports
104            .iter_mut()
105            .filter(|import| {
106                <Wasip1ABIFunc as strum::VariantNames>::VARIANTS.contains(&import.name.as_str())
107                    && import.module == UniqueName::WASIP1_ABI_MODULE
108            })
109            .for_each(|import| {
110                import.name =
111                    crate::unique_name::UniqueName::Wasip1ABI(&Wasip1ABIName::TargetTemporal {
112                        wasm: &external.name,
113                        import: import.name.as_str(),
114                    })
115                    .to_string();
116            });
117
118        Ok(())
119    }
120
121    fn post_combine(
122        &mut self,
123        module: &mut walrus::Module,
124        ctx: &crate::generator::GeneratorCtx,
125    ) -> eyre::Result<()> {
126        for wasm in &ctx.target_names {
127            for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
128                if let Some(_import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
129                    .get_fid(&module.imports)
130                    .ok()
131                {
132                    unreachable!();
133                    // module.connect_func_alt(import_id, &export_name, ctx.unstable_print_debug)?;
134                } else {
135                    module
136                        .exports
137                        .erase_with(
138                            &UniqueName::Wasip1ABI(&Wasip1ABIName::TargetTemporal { wasm, import }),
139                            ctx.unstable_print_debug,
140                        )
141                        .ok();
142                }
143            }
144        }
145        Ok(())
146    }
147}
148
149/// ABI Generator: Connects WASI-threads ABI imports across modules.
150///
151/// **Why this is needed:**
152/// Similar to `ConnectWasip1ABI`, thread-specific WASI functions (e.g., `wasi_thread_spawn`)
153/// and the Thread ID assignment logic need to be properly intercepted. This generator aligns
154/// the standard thread imports with our instrumented logic, allowing the host context to
155/// initialize and direct threads properly according to our virtualized shared memory architecture.
156#[derive(Debug, Default)]
157pub struct ConnectWasip1ThreadsABI;
158
159impl Generator for ConnectWasip1ThreadsABI {
160    fn post_combine(
161        &mut self,
162        module: &mut walrus::Module,
163        ctx: &crate::generator::GeneratorCtx,
164    ) -> eyre::Result<()> {
165        if ctx.threads {
166            for wasm in &ctx.target_names {
167                let start_import = (
168                    UniqueName::NAMESPACE,
169                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStart(wasm)),
170                );
171
172                let dest_name =
173                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
174                        .to_string();
175                let dest_fid = module.exports.get_fid_by_name(&dest_name).ok();
176
177                if let Some(_) = dest_fid {
178                    module.connect_func_alt_with_remove_export(
179                        start_import,
180                        &dest_name,
181                        ctx.unstable_print_debug,
182                    )?;
183                } else {
184                    // Destination not found. We should still resolve the import to avoid component encoding failure.
185                    if let Ok(import_id) = start_import.get_fid(&module.imports) {
186                        log::warn!(
187                            "Thread start destination not found for {}, connecting to trap.",
188                            wasm
189                        );
190                        // Connect to trap
191                        module
192                            .replace_imported_func(import_id, |(body, _)| {
193                                body.unreachable();
194                            })
195                            .to_eyre()
196                            .wrap_err_with(|| {
197                                eyre::eyre!("Failed to replace missing thread start import")
198                            })?;
199                    }
200                }
201
202                module
203                    .exports
204                    .erase_with(
205                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartAnchor(wasm)),
206                        ctx.unstable_print_debug,
207                    )
208                    .ok();
209
210                let spawn_import = (
211                    UniqueName::WASIP1_THREADS_ABI_MODULE,
212                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)),
213                );
214                let spawn_dest_name =
215                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
216
217                if let Ok(import_id) = spawn_import.get_fid(&module.imports) {
218                    if let Ok(_) = module.exports.get_fid_by_name(&spawn_dest_name) {
219                        module.connect_func_alt_with_remove_export(
220                            spawn_import,
221                            &spawn_dest_name,
222                            ctx.unstable_print_debug,
223                        )?;
224                    } else {
225                        module
226                            .replace_imported_func(import_id, |(body, _)| {
227                                body.unreachable();
228                            })
229                            .to_eyre()
230                            .wrap_err_with(|| {
231                                eyre::eyre!("Failed to replace missing thread spawn import")
232                            })?;
233                    }
234                }
235            }
236        }
237        Ok(())
238    }
239}
240
241/// Require before PatchComponent
242/// Require after ConnectWasip1ABI
243///
244/// **Why this is needed:**
245/// Sometimes the VFS implementation itself needs to call the host's real WASI functions
246/// (e.g., falling back to the real filesystem). If it just called the normal WASI imports,
247/// it could cause an infinite recursion because they are patched to point back to the VFS.
248/// This generator rewires special `non_recursive_...` invocations directly to the original
249/// host environment imports.
250#[derive(Debug, Default)]
251pub struct NonRecursiveWasiABI;
252
253impl Generator for NonRecursiveWasiABI {
254    fn pre_vfs(
255        &mut self,
256        module: &mut walrus::Module,
257        _: &super::GeneratorCtx,
258    ) -> eyre::Result<()> {
259        for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
260            if let Some(fid) = (UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT, import)
261                .get_fid(&module.imports)
262                .ok()
263            {
264                // If it already exists, make it possible to call it.
265                if let Some(import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
266                    .get_fid(&module.imports)
267                    .ok()
268                {
269                    module.renew_call_fn(fid, import_id)?;
270                } else {
271                    let import_id = module.imports.get_imported_func(fid).unwrap().id();
272                    let import = module.imports.get_mut(import_id);
273                    import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
274                }
275            }
276        }
277
278        module
279            .imports
280            .iter()
281            .filter(|import| import.module == UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT)
282            .map(|import| &import.name)
283            .for_each(|name| {
284                log::warn!(
285                    "Non-recursive Wasip1 ABI import exists: {name}, but this is not verified."
286                );
287            });
288
289        Ok(())
290    }
291}
292
293/// Adjust ABI to match wasip1-threads
294///
295/// **Why this is needed:**
296/// Target runners (like standard environments or `wasmtime`) expect exactly
297/// `wasi_snapshot_preview1` and standard threads module names. After all our
298/// patching using intermediate component names, this pass rename the finalized
299/// module imports back to standard names so that the result is syntactically a
300/// correct standard WASM matching the underlying runtime requirements.
301#[derive(Debug, Clone, Default)]
302pub struct AdjustABI;
303
304impl Generator for AdjustABI {
305    fn post_components(
306        &mut self,
307        module: &mut walrus::Module,
308        ctx: &super::ComponentCtx,
309    ) -> eyre::Result<()> {
310        if !ctx.adjust_abi {
311            return Ok(());
312        }
313
314        for import_name in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
315            if let Ok(import_id) = (
316                UniqueName::CORE_MODULE_ROOT,
317                &gen_component_name(UniqueName::WASIP1_ABI_MODULE_ALT, import_name),
318            )
319                .get_fid(&module.imports)
320            {
321                if let Ok(import_id) =
322                    (UniqueName::WASIP1_ABI_MODULE, import_name).get_fid(&module.imports)
323                {
324                    module.imports.erase(import_id).unwrap();
325                }
326
327                let import_id = module.imports.get_imported_func(import_id).unwrap().id();
328                let import = module.imports.get_mut(import_id);
329                import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
330                import.name = import_name.to_string();
331            }
332        }
333
334        let import_name = <Wasip1ThreadsABIFunc as strum::VariantNames>::VARIANTS
335            .iter()
336            .exactly_one()
337            .unwrap();
338
339        if let Ok(import_id) = (
340            UniqueName::THREADS_MODULE_ROOT,
341            &gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, import_name),
342        )
343            .get_fid(&module.imports)
344        {
345            if let Ok(import_id) =
346                (UniqueName::WASIP1_THREADS_ABI_MODULE, import_name).get_fid(&module.imports)
347            {
348                module.imports.erase(import_id).unwrap();
349            }
350
351            let import_id = module.imports.get_imported_func(import_id).unwrap().id();
352            let import = module.imports.get_mut(import_id);
353            import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
354            import.name = import_name.to_string();
355
356            let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
357                .iter()
358                .exactly_one()
359                .unwrap();
360
361            if let Ok(export_id) = export_name.get_fid(&module.exports) {
362                module.exports.erase(export_id)?;
363            }
364
365            // adjust export
366            let id = UniqueName::THREADS_EXPORT_MODULE_ROOT.get_fid(&module.exports)?;
367            let eid = module.exports.get_exported_func(id).unwrap().id();
368            let export = module.exports.get_mut(eid);
369            export.name = UniqueName::THREADS_EXPORT_MODULE_ROOT.to_string();
370        }
371
372        Ok(())
373    }
374}