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
38impl Generator for CheckUseLibrary {
39    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
40        // If you're using the library, anchors should be generated automatically.
41        let export_names = module
42            .exports
43            .iter()
44            .map(|e| e.name.as_str())
45            .collect::<Vec<_>>();
46
47        if !has_library_import_anchor_names(&export_names) {
48            eyre::bail!(
49                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."#
50            );
51        }
52
53        // check use import_wasm!
54        for wasm_name in &ctx.target_names {
55            if !module
56                .exports
57                .iter()
58                .any(|export| export.name == format!("__wasip1_vfs_{wasm_name}__start_anchor"))
59            {
60                let suggests = module
61                    .exports
62                    .iter()
63                    .filter_map(|e| {
64                        e.name
65                            .strip_prefix("__wasip1_vfs_")?
66                            .strip_suffix("__start_anchor")
67                            .map(|s| s.to_string())
68                    })
69                    .collect::<Vec<_>>();
70
71                let best_suggest = suggests
72                    .iter()
73                    .map(|s| (strsim::jaro_winkler(&s, wasm_name.as_ref()), s))
74                    .min_by(|(a, _), (b, _)| b.partial_cmp(a).unwrap());
75
76                let msg = if let Some((score, suggest)) = best_suggest
77                    && score > 0.8
78                {
79                    format!(
80                        "\nDid you mean `{wasm_name}`? You used `{suggest}` in `import_wasm!` macro."
81                    )
82                } else {
83                    String::new()
84                };
85
86                eyre::bail!(
87                    "Failed to get __start_anchor export on {wasm_name}. You may forget definition `import_wasm!` macro with wasm name.{msg}",
88                );
89            }
90        }
91
92        Ok(())
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn strict_accepts_prefixed_thread_anchor() {
102        let exports = vec!["__wasip1_vfs_thread-spawn_import_anchor"];
103        assert!(has_library_import_anchor_names(&exports));
104    }
105
106    #[test]
107    fn strict_rejects_legacy_thread_anchor() {
108        let exports = vec!["thread-spawn_import_anchor"];
109        assert!(!has_library_import_anchor_names(&exports));
110    }
111
112    #[test]
113    fn strict_rejects_legacy_thread_anchor_with_wasip1_anchor() {
114        let exports = vec!["thread-spawn_import_anchor", "fd_write_import_anchor"];
115        assert!(!has_library_import_anchor_names(&exports));
116    }
117
118    #[test]
119    fn still_accepts_wasip1_import_anchor() {
120        let exports = vec!["fd_write_import_anchor"];
121        assert!(has_library_import_anchor_names(&exports));
122    }
123
124    #[test]
125    fn strict_accepts_prefixed_thread_anchor_with_wasip1_anchor() {
126        let exports = vec![
127            "__wasip1_vfs_thread-spawn_import_anchor",
128            "fd_write_import_anchor",
129        ];
130        assert!(has_library_import_anchor_names(&exports));
131    }
132}
133
134/// Strict check validating that compiled WASM matches intended thread-safe / single-threaded memory paradigms.
135#[derive(Debug, Default)]
136pub struct CheckVFSMemoryType;
137
138impl Generator for CheckVFSMemoryType {
139    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
140        let target_memory_type = module.get_memory_type(true)?;
141
142        if ctx.target_memory_type != target_memory_type {
143            eyre::bail!(
144                "Target memory type mismatch: expected {:?}, found {:?}. Why?",
145                ctx.target_memory_type,
146                target_memory_type
147            );
148        }
149
150        Ok(())
151    }
152}
153
154/// Detects unused thread imports and efficiently cleans thread-related exports statically.
155#[derive(Debug, Default)]
156pub struct CheckUnusedThreads;
157
158impl CheckUnusedThreads {
159    fn remove_unused_threads_function(wasm: &mut walrus::Module) -> eyre::Result<()> {
160        // if wasm doesn't have wasi.thread-spawn on import,
161        // wasm's export `wasi_thread_start` should be removed
162
163        if !wasm
164            .imports
165            .iter()
166            .any(|i| i.module == "wasi" && i.name == "thread-spawn")
167        {
168            if wasm.exports.iter().any(|e| e.name == "wasi_thread_start") {
169                wasm.exports
170                    .remove("wasi_thread_start")
171                    .to_eyre()
172                    .wrap_err("Failed to remove wasi_thread_start export")?;
173            } else {
174                log::warn!(
175                    "wasi.thread-spawn is not imported, and wasi_thread_start is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
176                );
177            }
178
179            // todo!() check memory id used on thread-spawn function
180            if let Some((mem, id)) = {
181                wasm.imports
182                    .iter()
183                    .filter_map(|e| match e.kind {
184                        walrus::ImportKind::Memory(mem) => Some((mem, e.id())),
185                        _ => None,
186                    })
187                    .find(|_| true)
188            } {
189                wasm.imports.delete(id);
190                wasm.memories
191                    .iter_mut()
192                    .find(|m| m.id() == mem)
193                    .unwrap()
194                    .import = None;
195            } else {
196                log::warn!(
197                    "wasi.thread-spawn is not imported, and shared memory is not exported. This expect multi-threaded Wasm. Is this non rust-lang wasm?"
198                );
199            }
200        }
201
202        Ok(())
203    }
204}
205
206impl Generator for CheckUnusedThreads {
207    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
208        if ctx.threads {
209            Self::remove_unused_threads_function(module)
210                .wrap_err("Failed to remove unused threads function")?;
211        }
212        Ok(())
213    }
214
215    fn pre_target(
216        &mut self,
217        module: &mut walrus::Module,
218        ctx: &GeneratorCtx,
219        _: &ModuleExternal,
220    ) -> eyre::Result<()> {
221        if ctx.threads {
222            Self::remove_unused_threads_function(module)
223                .wrap_err("Failed to remove unused threads function")?;
224        }
225        Ok(())
226    }
227}
228
229/// Asserts the file comes from the Rust `rustc` compiler via `bindgen` standard structures.
230#[derive(Debug, Default)]
231pub struct IsRustWasm;
232
233impl Generator for IsRustWasm {
234    fn pre_target(
235        &mut self,
236        module: &mut walrus::Module,
237        _: &GeneratorCtx,
238        external: &ModuleExternal,
239    ) -> eyre::Result<()> {
240        let producers = format!("{:?}", module.producers);
241
242        if !["_start", "__main_void"]
243            .iter()
244            .all(|name| module.exports.iter().any(|e| e.name == *name))
245            || !["Rust", "rustc"]
246                .iter()
247                .all(|name| producers.contains(format!(r#""{name}""#).as_str()))
248        {
249            log::error!(
250                "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.",
251                external.name
252            );
253        }
254
255        Ok(())
256    }
257}
258
259/// Quick invariant check asserting if Virtual Memory hooks exist inside Target Wasm representation.
260#[derive(Debug, Default)]
261pub struct CheckUseWasiVirtLayer;
262
263impl Generator for CheckUseWasiVirtLayer {
264    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
265        if "__wasip1_vfs_flag_vfs_memory"
266            .get_fid(&module.exports)
267            .ok()
268            .is_none()
269        {
270            eyre::bail!(
271                r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer;"#
272            );
273        }
274
275        Ok(())
276    }
277}