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 pre_target(
161        &mut self,
162        module: &mut walrus::Module,
163        _: &crate::generator::GeneratorCtx,
164        external: &crate::generator::ModuleExternal,
165    ) -> eyre::Result<()> {
166        module
167            .imports
168            .iter_mut()
169            .filter(|import| {
170                import.name == "wasi_thread_spawn"
171                    && (import.module == "wasi" || import.module == "env")
172            })
173            .for_each(|import| {
174                import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
175                import.name = UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(
176                    &external.name,
177                ))
178                .to_string();
179            });
180
181        Ok(())
182    }
183
184    fn post_combine(
185        &mut self,
186        module: &mut walrus::Module,
187        ctx: &crate::generator::GeneratorCtx,
188    ) -> eyre::Result<()> {
189        if ctx.threads {
190            for wasm in &ctx.target_names {
191                let start_import = (
192                    UniqueName::NAMESPACE,
193                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStart(wasm)),
194                );
195
196                let dest_name =
197                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
198                        .to_string();
199                let dest_fid = module.exports.get_fid_by_name(&dest_name).ok();
200
201                if let Some(_) = dest_fid {
202                    module.connect_func_alt_with_remove_export(
203                        start_import,
204                        &dest_name,
205                        ctx.unstable_print_debug,
206                    )?;
207                } else {
208                    // Destination not found. We should still resolve the import to avoid component encoding failure.
209                    if let Ok(import_id) = start_import.get_fid(&module.imports) {
210                        log::warn!(
211                            "Thread start destination not found for {}, connecting to trap.",
212                            wasm
213                        );
214                        // Connect to trap
215                        module
216                            .replace_imported_func(import_id, |(body, _)| {
217                                body.unreachable();
218                            })
219                            .to_eyre()
220                            .wrap_err_with(|| {
221                                eyre::eyre!("Failed to replace missing thread start import")
222                            })?;
223                    }
224                }
225
226                module
227                    .exports
228                    .erase_with(
229                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartAnchor(wasm)),
230                        ctx.unstable_print_debug,
231                    )
232                    .ok();
233
234                let spawn_import = (
235                    UniqueName::WASIP1_THREADS_ABI_MODULE,
236                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)),
237                );
238                let spawn_dest_name =
239                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
240
241                if let Ok(import_id) = spawn_import.get_fid(&module.imports) {
242                    if let Ok(_) = module.exports.get_fid_by_name(&spawn_dest_name) {
243                        module.connect_func_alt_with_remove_export(
244                            spawn_import,
245                            &spawn_dest_name,
246                            ctx.unstable_print_debug,
247                        )?;
248                    } else {
249                        module
250                            .replace_imported_func(import_id, |(body, _)| {
251                                body.unreachable();
252                            })
253                            .to_eyre()
254                            .wrap_err_with(|| {
255                                eyre::eyre!("Failed to replace missing thread spawn import")
256                            })?;
257                    }
258                }
259            }
260        }
261        Ok(())
262    }
263}
264
265/// Require before PatchComponent
266/// Require after ConnectWasip1ABI
267///
268/// **Why this is needed:**
269/// Sometimes the VFS implementation itself needs to call the host's real WASI functions
270/// (e.g., falling back to the real filesystem). If it just called the normal WASI imports,
271/// it could cause an infinite recursion because they are patched to point back to the VFS.
272/// This generator rewires special `non_recursive_...` invocations directly to the original
273/// host environment imports.
274#[derive(Debug, Default)]
275pub struct NonRecursiveWasiABI;
276
277impl Generator for NonRecursiveWasiABI {
278    fn pre_vfs(
279        &mut self,
280        module: &mut walrus::Module,
281        _: &super::GeneratorCtx,
282    ) -> eyre::Result<()> {
283        for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
284            if let Some(fid) = (UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT, import)
285                .get_fid(&module.imports)
286                .ok()
287            {
288                // If it already exists, make it possible to call it.
289                if let Some(import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
290                    .get_fid(&module.imports)
291                    .ok()
292                {
293                    module.renew_call_fn(fid, import_id)?;
294                } else {
295                    let import_id = module.imports.get_imported_func(fid).unwrap().id();
296                    let import = module.imports.get_mut(import_id);
297                    import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
298                }
299            }
300        }
301
302        module
303            .imports
304            .iter()
305            .filter(|import| import.module == UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT)
306            .map(|import| &import.name)
307            .for_each(|name| {
308                log::warn!(
309                    "Non-recursive Wasip1 ABI import exists: {name}, but this is not verified."
310                );
311            });
312
313        Ok(())
314    }
315}
316
317/// Adjust ABI to match wasip1-threads
318///
319/// **Why this is needed:**
320/// Target runners (like standard environments or `wasmtime`) expect exactly
321/// `wasi_snapshot_preview1` and standard threads module names. After all our
322/// patching using intermediate component names, this pass rename the finalized
323/// module imports back to standard names so that the result is syntactically a
324/// correct standard WASM matching the underlying runtime requirements.
325#[derive(Debug, Clone, Default)]
326pub struct AdjustABI;
327
328impl Generator for AdjustABI {
329    fn post_components(
330        &mut self,
331        module: &mut walrus::Module,
332        ctx: &super::ComponentCtx,
333    ) -> eyre::Result<()> {
334        if !ctx.adjust_abi {
335            return Ok(());
336        }
337
338        for import_name in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
339            if let Ok(import_id) = (
340                UniqueName::CORE_MODULE_ROOT,
341                &gen_component_name(UniqueName::WASIP1_ABI_MODULE_ALT, import_name),
342            )
343                .get_fid(&module.imports)
344            {
345                if let Ok(import_id) =
346                    (UniqueName::WASIP1_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_ABI_MODULE.to_string();
354                import.name = import_name.to_string();
355            }
356        }
357
358        let import_name = <Wasip1ThreadsABIFunc as strum::VariantNames>::VARIANTS
359            .iter()
360            .exactly_one()
361            .unwrap();
362
363        if let Ok(import_id) = (
364            UniqueName::THREADS_MODULE_ROOT,
365            &gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, import_name),
366        )
367            .get_fid(&module.imports)
368        {
369            if let Ok(import_id) =
370                (UniqueName::WASIP1_THREADS_ABI_MODULE, import_name).get_fid(&module.imports)
371            {
372                module.imports.erase(import_id).unwrap();
373            }
374
375            let import_id = module.imports.get_imported_func(import_id).unwrap().id();
376            let import = module.imports.get_mut(import_id);
377            import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
378            import.name = import_name.to_string();
379
380            let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
381                .iter()
382                .exactly_one()
383                .unwrap();
384
385            if let Ok(export_id) = export_name.get_fid(&module.exports) {
386                module.exports.erase(export_id)?;
387            }
388
389            // adjust export
390            let id = UniqueName::THREADS_EXPORT_MODULE_ROOT.get_fid(&module.exports)?;
391            let eid = module.exports.get_exported_func(id).unwrap().id();
392            let export = module.exports.get_mut(eid);
393            export.name = UniqueName::THREADS_EXPORT_MODULE_ROOT.to_string();
394        }
395
396        Ok(())
397    }
398}