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