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"
112                || normalize_name(&declared_name) == normalize_name(ctx.vfs_name.as_ref())
113            {
114                continue;
115            }
116
117            if !ctx
118                .target_names
119                .iter()
120                .any(|target| normalize_name(target.as_ref()) == normalize_name(&declared_name))
121            {
122                eyre::bail!(
123                    "WASM module `{declared_name}` is declared with `import_wasm!` macro in VFS, but not provided as a target argument. \
124                     Did you forget to specify this WASM file in the CLI arguments?"
125                );
126            }
127        }
128
129        Ok(())
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn strict_accepts_prefixed_thread_anchor() {
139        let exports = vec!["__wasip1_vfs_thread-spawn_import_anchor"];
140        assert!(has_library_import_anchor_names(&exports));
141    }
142
143    #[test]
144    fn strict_rejects_legacy_thread_anchor() {
145        let exports = vec!["thread-spawn_import_anchor"];
146        assert!(!has_library_import_anchor_names(&exports));
147    }
148
149    #[test]
150    fn strict_rejects_legacy_thread_anchor_with_wasip1_anchor() {
151        let exports = vec!["thread-spawn_import_anchor", "fd_write_import_anchor"];
152        assert!(!has_library_import_anchor_names(&exports));
153    }
154
155    #[test]
156    fn still_accepts_wasip1_import_anchor() {
157        let exports = vec!["fd_write_import_anchor"];
158        assert!(has_library_import_anchor_names(&exports));
159    }
160
161    #[test]
162    fn strict_accepts_prefixed_thread_anchor_with_wasip1_anchor() {
163        let exports = vec![
164            "__wasip1_vfs_thread-spawn_import_anchor",
165            "fd_write_import_anchor",
166        ];
167        assert!(has_library_import_anchor_names(&exports));
168    }
169}
170
171/// Strict check validating that compiled WASM matches intended thread-safe / single-threaded memory paradigms.
172#[derive(Debug, Default)]
173pub struct CheckVFSMemoryType;
174
175impl Generator for CheckVFSMemoryType {
176    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
177        let target_memory_type = module.get_memory_type(true)?;
178
179        if ctx.target_memory_type != target_memory_type {
180            eyre::bail!(
181                "Target memory type mismatch: expected {:?}, found {:?}. Why?",
182                ctx.target_memory_type,
183                target_memory_type
184            );
185        }
186
187        Ok(())
188    }
189}
190
191/// Detects unused thread imports and efficiently cleans thread-related exports statically.
192#[derive(Debug, Default)]
193pub struct CheckUnusedThreads;
194
195impl CheckUnusedThreads {
196    fn remove_unused_threads_function(wasm: &mut walrus::Module) -> eyre::Result<()> {
197        // if wasm doesn't have wasi.thread-spawn on import,
198        // wasm's export `wasi_thread_start` should be removed
199
200        if !wasm
201            .imports
202            .iter()
203            .any(|i| i.module == "wasi" && i.name == "thread-spawn")
204        {
205            if wasm.exports.iter().any(|e| e.name == "wasi_thread_start") {
206                wasm.exports
207                    .remove("wasi_thread_start")
208                    .to_eyre()
209                    .wrap_err("Failed to remove wasi_thread_start export")?;
210            } else {
211                log::warn!(
212                    "wasi.thread-spawn is not imported, and wasi_thread_start is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
213                );
214            }
215
216            // todo!() check memory id used on thread-spawn function
217            if let Some((mem, id)) = {
218                wasm.imports
219                    .iter()
220                    .filter_map(|e| match e.kind {
221                        walrus::ImportKind::Memory(mem) => Some((mem, e.id())),
222                        _ => None,
223                    })
224                    .find(|_| true)
225            } {
226                wasm.imports.delete(id);
227                wasm.memories
228                    .iter_mut()
229                    .find(|m| m.id() == mem)
230                    .unwrap()
231                    .import = None;
232            } else {
233                log::warn!(
234                    "wasi.thread-spawn is not imported, and shared memory is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
235                );
236            }
237        }
238
239        Ok(())
240    }
241}
242
243impl Generator for CheckUnusedThreads {
244    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
245        if ctx.threads {
246            Self::remove_unused_threads_function(module)
247                .wrap_err("Failed to remove unused threads function")?;
248        }
249        Ok(())
250    }
251
252    fn pre_target(
253        &mut self,
254        module: &mut walrus::Module,
255        ctx: &GeneratorCtx,
256        _: &ModuleExternal,
257    ) -> eyre::Result<()> {
258        if ctx.threads {
259            Self::remove_unused_threads_function(module)
260                .wrap_err("Failed to remove unused threads function")?;
261        }
262        Ok(())
263    }
264}
265
266/// Checks whether the file comes from the Rust `rustc` compiler.
267///
268/// If the target is not a Rust module (e.g. C/C++ compiled via LLVM/Clang),
269/// this generator emits a warning instead of failing, because C/C++ targets
270/// are supported — the CLI will synthesize the missing `__main_void` export
271/// automatically.
272#[derive(Debug, Default)]
273pub struct IsRustWasm;
274
275impl Generator for IsRustWasm {
276    fn pre_target(
277        &mut self,
278        module: &mut walrus::Module,
279        _: &GeneratorCtx,
280        external: &ModuleExternal,
281    ) -> eyre::Result<()> {
282        let producers = format!("{:?}", module.producers);
283
284        let is_rust = ["Rust", "rustc"]
285            .iter()
286            .all(|name| producers.contains(format!(r#""{name}""#).as_str()));
287
288        let has_start = module.exports.iter().any(|e| e.name == "_start");
289        let has_main_void = module.exports.iter().any(|e| e.name == "__main_void");
290
291        if !has_start {
292            eyre::bail!(
293                "Target module `{}` does not export `_start`. A WASI executable must export `_start`.",
294                external.name
295            );
296        }
297
298        if !is_rust || !has_main_void {
299            log::warn!(
300                "Target module `{}` appears to be compiled by a non-Rust toolchain (e.g. C/C++ via LLVM/Clang). \
301                 A synthetic `__main_void` wrapper will be generated automatically.",
302                external.name
303            );
304        }
305
306        Ok(())
307    }
308}
309
310/// Quick invariant check asserting if Virtual Memory hooks exist inside Target Wasm representation.
311#[derive(Debug, Default)]
312pub struct CheckUseWasiVirtLayer;
313
314impl Generator for CheckUseWasiVirtLayer {
315    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
316        if "__wasip1_vfs_flag_vfs_memory"
317            .get_fid(&module.exports)
318            .ok()
319            .is_none()
320        {
321            eyre::bail!(
322                r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer;"#
323            );
324        }
325
326        Ok(())
327    }
328}