Skip to main content

wasi_virt_layer_cli/generator/
check.rs

1use eyre::Context as _;
2use strum::VariantNames;
3
4use crate::{
5    abi::{Wasip1ABIFunc, Wasip1ThreadsABIFunc},
6    generator::{Generator, GeneratorCtx, ModuleExternal, threads::ThreadsSpawnName},
7    unique_name::UniqueName,
8    util::{ResultUtil as _, WalrusFID as _, WalrusUtilModule},
9};
10
11fn has_library_import_anchor_names(export_names: &[&str]) -> bool {
12    let has_legacy_thread_anchor = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
13        .iter()
14        .map(|name| format!("{name}_import_anchor"))
15        .any(|legacy| export_names.iter().any(|name| *name == legacy));
16
17    if has_legacy_thread_anchor {
18        return false;
19    }
20
21    let has_wasip1_anchor = <Wasip1ABIFunc as VariantNames>::VARIANTS
22        .iter()
23        .map(|name| format!("{name}_import_anchor"))
24        .any(|required| export_names.iter().any(|name| *name == required));
25
26    let has_prefixed_thread_anchor = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
27        .iter()
28        .map(|name| UniqueName::ThreadsSpawn(&ThreadsSpawnName::ImportAnchor(name)).to_string())
29        .any(|required| export_names.iter().any(|name| *name == required));
30
31    has_wasip1_anchor || has_prefixed_thread_anchor
32}
33
34/// Checks if the provided Wasm securely linked `wasi_virt_layer` anchors correctly.
35#[derive(Debug, Default)]
36pub struct CheckUseLibrary;
37
38fn normalize_name(s: &str) -> String {
39    s.replace('-', "_")
40}
41
42impl Generator for CheckUseLibrary {
43    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
44        // If you're using the library, anchors should be generated automatically.
45        let export_names = module
46            .exports
47            .iter()
48            .map(|e| e.name.as_str())
49            .collect::<Vec<_>>();
50
51        if !has_library_import_anchor_names(&export_names) {
52            eyre::bail!(
53                r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer; or, it does not import a crate."#
54            );
55        }
56
57        // check use import_wasm!
58        for wasm_name in &ctx.target_names {
59            let normalized_name = normalize_name(wasm_name.as_ref());
60            if !module.exports.iter().any(|export| {
61                export.name == format!("__wasip1_vfs_{normalized_name}__start_anchor")
62            }) {
63                let suggests = module
64                    .exports
65                    .iter()
66                    .filter_map(|e| {
67                        e.name
68                            .strip_prefix("__wasip1_vfs_")?
69                            .strip_suffix("__start_anchor")
70                            .map(|s| s.to_string())
71                    })
72                    .collect::<Vec<_>>();
73
74                let best_suggest = suggests
75                    .iter()
76                    .map(|s| (strsim::jaro_winkler(&s, &normalized_name), s))
77                    .min_by(|(a, _), (b, _)| b.partial_cmp(a).unwrap());
78
79                let msg = if let Some((score, suggest)) = best_suggest
80                    && score > 0.8
81                {
82                    format!(
83                        "\nDid you mean `{wasm_name}`? You used `{suggest}` in `import_wasm!` macro."
84                    )
85                } else {
86                    String::new()
87                };
88
89                eyre::bail!(
90                    "Failed to get __start_anchor export on {wasm_name}. You may forget definition `import_wasm!` macro with wasm name.{msg}",
91                );
92            }
93        }
94
95        // Check that all import_wasm! declarations have corresponding target WASM arguments
96        // Note: `anonymous` is excluded here as it's handled separately by the `Anonymous` generator
97        let declared_wasm_names = module
98            .exports
99            .iter()
100            .filter_map(|e| {
101                e.name
102                    .strip_prefix("__wasip1_vfs_")?
103                    .strip_suffix("__start_anchor")
104                    .map(|s| s.to_string())
105            })
106            .collect::<Vec<_>>();
107
108        for declared_name in declared_wasm_names {
109            // Skip validation for anonymous - it's handled by the Anonymous generator
110            // Also skip if it's the VFS module itself (self-virtualization)
111            if declared_name == "anonymous" || normalize_name(&declared_name) == normalize_name(ctx.vfs_name.as_ref()) {
112                continue;
113            }
114
115            if !ctx.target_names.iter().any(|target| {
116                normalize_name(target.as_ref()) == normalize_name(&declared_name)
117            }) {
118                eyre::bail!(
119                    "WASM module `{declared_name}` is declared with `import_wasm!` macro in VFS, but not provided as a target argument. \
120                     Did you forget to specify this WASM file in the CLI arguments?"
121                );
122            }
123        }
124
125        Ok(())
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn strict_accepts_prefixed_thread_anchor() {
135        let exports = vec!["__wasip1_vfs_thread-spawn_import_anchor"];
136        assert!(has_library_import_anchor_names(&exports));
137    }
138
139    #[test]
140    fn strict_rejects_legacy_thread_anchor() {
141        let exports = vec!["thread-spawn_import_anchor"];
142        assert!(!has_library_import_anchor_names(&exports));
143    }
144
145    #[test]
146    fn strict_rejects_legacy_thread_anchor_with_wasip1_anchor() {
147        let exports = vec!["thread-spawn_import_anchor", "fd_write_import_anchor"];
148        assert!(!has_library_import_anchor_names(&exports));
149    }
150
151    #[test]
152    fn still_accepts_wasip1_import_anchor() {
153        let exports = vec!["fd_write_import_anchor"];
154        assert!(has_library_import_anchor_names(&exports));
155    }
156
157    #[test]
158    fn strict_accepts_prefixed_thread_anchor_with_wasip1_anchor() {
159        let exports = vec![
160            "__wasip1_vfs_thread-spawn_import_anchor",
161            "fd_write_import_anchor",
162        ];
163        assert!(has_library_import_anchor_names(&exports));
164    }
165}
166
167/// Strict check validating that compiled WASM matches intended thread-safe / single-threaded memory paradigms.
168#[derive(Debug, Default)]
169pub struct CheckVFSMemoryType;
170
171impl Generator for CheckVFSMemoryType {
172    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
173        let target_memory_type = module.get_memory_type(true)?;
174
175        if ctx.target_memory_type != target_memory_type {
176            eyre::bail!(
177                "Target memory type mismatch: expected {:?}, found {:?}. Why?",
178                ctx.target_memory_type,
179                target_memory_type
180            );
181        }
182
183        Ok(())
184    }
185}
186
187/// Detects unused thread imports and efficiently cleans thread-related exports statically.
188#[derive(Debug, Default)]
189pub struct CheckUnusedThreads;
190
191impl CheckUnusedThreads {
192    fn remove_unused_threads_function(wasm: &mut walrus::Module) -> eyre::Result<()> {
193        // if wasm doesn't have wasi.thread-spawn on import,
194        // wasm's export `wasi_thread_start` should be removed
195
196        if !wasm
197            .imports
198            .iter()
199            .any(|i| i.module == "wasi" && i.name == "thread-spawn")
200        {
201            if wasm.exports.iter().any(|e| e.name == "wasi_thread_start") {
202                wasm.exports
203                    .remove("wasi_thread_start")
204                    .to_eyre()
205                    .wrap_err("Failed to remove wasi_thread_start export")?;
206            } else {
207                log::warn!(
208                    "wasi.thread-spawn is not imported, and wasi_thread_start is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
209                );
210            }
211
212            // todo!() check memory id used on thread-spawn function
213            if let Some((mem, id)) = {
214                wasm.imports
215                    .iter()
216                    .filter_map(|e| match e.kind {
217                        walrus::ImportKind::Memory(mem) => Some((mem, e.id())),
218                        _ => None,
219                    })
220                    .find(|_| true)
221            } {
222                wasm.imports.delete(id);
223                wasm.memories
224                    .iter_mut()
225                    .find(|m| m.id() == mem)
226                    .unwrap()
227                    .import = None;
228            } else {
229                log::warn!(
230                    "wasi.thread-spawn is not imported, and shared memory is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
231                );
232            }
233        }
234
235        Ok(())
236    }
237}
238
239impl Generator for CheckUnusedThreads {
240    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
241        if ctx.threads {
242            Self::remove_unused_threads_function(module)
243                .wrap_err("Failed to remove unused threads function")?;
244        }
245        Ok(())
246    }
247
248    fn pre_target(
249        &mut self,
250        module: &mut walrus::Module,
251        ctx: &GeneratorCtx,
252        _: &ModuleExternal,
253    ) -> eyre::Result<()> {
254        if ctx.threads {
255            Self::remove_unused_threads_function(module)
256                .wrap_err("Failed to remove unused threads function")?;
257        }
258        Ok(())
259    }
260}
261
262/// Checks whether the file comes from the Rust `rustc` compiler.
263///
264/// If the target is not a Rust module (e.g. C/C++ compiled via LLVM/Clang),
265/// this generator emits a warning instead of failing, because C/C++ targets
266/// are supported — the CLI will synthesize the missing `__main_void` export
267/// automatically.
268#[derive(Debug, Default)]
269pub struct IsRustWasm;
270
271impl Generator for IsRustWasm {
272    fn pre_target(
273        &mut self,
274        module: &mut walrus::Module,
275        _: &GeneratorCtx,
276        external: &ModuleExternal,
277    ) -> eyre::Result<()> {
278        let producers = format!("{:?}", module.producers);
279
280        let is_rust = ["Rust", "rustc"]
281            .iter()
282            .all(|name| producers.contains(format!(r#""{name}""#).as_str()));
283
284        let has_start = module.exports.iter().any(|e| e.name == "_start");
285        let has_main_void = module.exports.iter().any(|e| e.name == "__main_void");
286
287        if !has_start {
288            eyre::bail!(
289                "Target module `{}` does not export `_start`. A WASI executable must export `_start`.",
290                external.name
291            );
292        }
293
294        if !is_rust || !has_main_void {
295            log::warn!(
296                "Target module `{}` appears to be compiled by a non-Rust toolchain (e.g. C/C++ via LLVM/Clang). \
297                 A synthetic `__main_void` wrapper will be generated automatically.",
298                external.name
299            );
300        }
301
302        Ok(())
303    }
304}
305
306/// Quick invariant check asserting if Virtual Memory hooks exist inside Target Wasm representation.
307#[derive(Debug, Default)]
308pub struct CheckUseWasiVirtLayer;
309
310impl Generator for CheckUseWasiVirtLayer {
311    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
312        if "__wasip1_vfs_flag_vfs_memory"
313            .get_fid(&module.exports)
314            .ok()
315            .is_none()
316        {
317            eyre::bail!(
318                r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer;"#
319            );
320        }
321
322        Ok(())
323    }
324}