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        Ok(())
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn strict_accepts_prefixed_thread_anchor() {
105        let exports = vec!["__wasip1_vfs_thread-spawn_import_anchor"];
106        assert!(has_library_import_anchor_names(&exports));
107    }
108
109    #[test]
110    fn strict_rejects_legacy_thread_anchor() {
111        let exports = vec!["thread-spawn_import_anchor"];
112        assert!(!has_library_import_anchor_names(&exports));
113    }
114
115    #[test]
116    fn strict_rejects_legacy_thread_anchor_with_wasip1_anchor() {
117        let exports = vec!["thread-spawn_import_anchor", "fd_write_import_anchor"];
118        assert!(!has_library_import_anchor_names(&exports));
119    }
120
121    #[test]
122    fn still_accepts_wasip1_import_anchor() {
123        let exports = vec!["fd_write_import_anchor"];
124        assert!(has_library_import_anchor_names(&exports));
125    }
126
127    #[test]
128    fn strict_accepts_prefixed_thread_anchor_with_wasip1_anchor() {
129        let exports = vec![
130            "__wasip1_vfs_thread-spawn_import_anchor",
131            "fd_write_import_anchor",
132        ];
133        assert!(has_library_import_anchor_names(&exports));
134    }
135}
136
137/// Strict check validating that compiled WASM matches intended thread-safe / single-threaded memory paradigms.
138#[derive(Debug, Default)]
139pub struct CheckVFSMemoryType;
140
141impl Generator for CheckVFSMemoryType {
142    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
143        let target_memory_type = module.get_memory_type(true)?;
144
145        if ctx.target_memory_type != target_memory_type {
146            eyre::bail!(
147                "Target memory type mismatch: expected {:?}, found {:?}. Why?",
148                ctx.target_memory_type,
149                target_memory_type
150            );
151        }
152
153        Ok(())
154    }
155}
156
157/// Detects unused thread imports and efficiently cleans thread-related exports statically.
158#[derive(Debug, Default)]
159pub struct CheckUnusedThreads;
160
161impl CheckUnusedThreads {
162    fn remove_unused_threads_function(wasm: &mut walrus::Module) -> eyre::Result<()> {
163        // if wasm doesn't have wasi.thread-spawn on import,
164        // wasm's export `wasi_thread_start` should be removed
165
166        if !wasm
167            .imports
168            .iter()
169            .any(|i| i.module == "wasi" && i.name == "thread-spawn")
170        {
171            if wasm.exports.iter().any(|e| e.name == "wasi_thread_start") {
172                wasm.exports
173                    .remove("wasi_thread_start")
174                    .to_eyre()
175                    .wrap_err("Failed to remove wasi_thread_start export")?;
176            } else {
177                log::warn!(
178                    "wasi.thread-spawn is not imported, and wasi_thread_start is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
179                );
180            }
181
182            // todo!() check memory id used on thread-spawn function
183            if let Some((mem, id)) = {
184                wasm.imports
185                    .iter()
186                    .filter_map(|e| match e.kind {
187                        walrus::ImportKind::Memory(mem) => Some((mem, e.id())),
188                        _ => None,
189                    })
190                    .find(|_| true)
191            } {
192                wasm.imports.delete(id);
193                wasm.memories
194                    .iter_mut()
195                    .find(|m| m.id() == mem)
196                    .unwrap()
197                    .import = None;
198            } else {
199                log::warn!(
200                    "wasi.thread-spawn is not imported, and shared memory is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
201                );
202            }
203        }
204
205        Ok(())
206    }
207}
208
209impl Generator for CheckUnusedThreads {
210    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
211        if ctx.threads {
212            Self::remove_unused_threads_function(module)
213                .wrap_err("Failed to remove unused threads function")?;
214        }
215        Ok(())
216    }
217
218    fn pre_target(
219        &mut self,
220        module: &mut walrus::Module,
221        ctx: &GeneratorCtx,
222        _: &ModuleExternal,
223    ) -> eyre::Result<()> {
224        if ctx.threads {
225            Self::remove_unused_threads_function(module)
226                .wrap_err("Failed to remove unused threads function")?;
227        }
228        Ok(())
229    }
230}
231
232/// Asserts the file comes from the Rust `rustc` compiler via `bindgen` standard structures.
233#[derive(Debug, Default)]
234pub struct IsRustWasm;
235
236impl Generator for IsRustWasm {
237    fn pre_target(
238        &mut self,
239        module: &mut walrus::Module,
240        _: &GeneratorCtx,
241        external: &ModuleExternal,
242    ) -> eyre::Result<()> {
243        let producers = format!("{:?}", module.producers);
244
245        if !["_start", "__main_void"]
246            .iter()
247            .all(|name| module.exports.iter().any(|e| e.name == *name))
248            || !["Rust", "rustc"]
249                .iter()
250                .all(|name| producers.contains(format!(r#""{name}""#).as_str()))
251        {
252            log::error!(
253                "This file: {} is not built by rust toolchain, or you forget to export _start or main_void function. If you use `cdylib` or `rlib`, please change to `bin` or `lib`.\nIf you use other language, create an issue.",
254                external.name
255            );
256        }
257
258        Ok(())
259    }
260}
261
262/// Quick invariant check asserting if Virtual Memory hooks exist inside Target Wasm representation.
263#[derive(Debug, Default)]
264pub struct CheckUseWasiVirtLayer;
265
266impl Generator for CheckUseWasiVirtLayer {
267    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
268        if "__wasip1_vfs_flag_vfs_memory"
269            .get_fid(&module.exports)
270            .ok()
271            .is_none()
272        {
273            eyre::bail!(
274                r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer;"#
275            );
276        }
277
278        Ok(())
279    }
280}