Skip to main content

wasi_virt_layer_cli/wasm_stream/passes/
check.rs

1use crate::abi::{Wasip1ABIFunc, Wasip1ThreadsABIFunc};
2use crate::generator::GeneratorCtx;
3use crate::unique_name::UniqueName;
4use crate::wasm_stream::pipeline::StreamChecker;
5use eyre::Result;
6use strum::VariantNames;
7use wasmparser::Payload;
8
9/// Checks whether the file comes from the Rust `rustc` compiler.
10#[derive(Debug, Default)]
11pub struct IsRustWasmChecker {
12    is_rust: bool,
13}
14
15impl IsRustWasmChecker {
16    pub fn new() -> Self {
17        Self { is_rust: false }
18    }
19}
20
21impl StreamChecker for IsRustWasmChecker {
22    fn check(&mut self, payload: &Payload) -> Result<()> {
23        if let Payload::CustomSection(c) = payload {
24            if c.name() == ".rustc" || c.name() == ".cargo" {
25                self.is_rust = true;
26            }
27        } else if let Payload::End(_) = payload {
28            if !self.is_rust {
29                log::warn!("Target is not a Rust module. Missing .rustc or .cargo custom section.");
30            }
31        }
32        Ok(())
33    }
34}
35
36/// Checks if the provided Wasm securely linked `wasi_virt_layer` anchors correctly.
37#[derive(Debug)]
38pub struct CheckUseLibraryChecker {
39    ctx: GeneratorCtx,
40    export_names: Vec<String>,
41}
42
43impl CheckUseLibraryChecker {
44    pub fn new(ctx: GeneratorCtx) -> Self {
45        Self {
46            ctx,
47            export_names: Vec::new(),
48        }
49    }
50}
51
52fn has_library_import_anchor_names(export_names: &[&str]) -> bool {
53    let has_legacy_thread_anchor = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
54        .iter()
55        .map(|name| format!("{name}_import_anchor"))
56        .any(|legacy| export_names.iter().any(|name| *name == legacy));
57
58    if has_legacy_thread_anchor {
59        return false;
60    }
61
62    let has_wasip1_anchor = <Wasip1ABIFunc as VariantNames>::VARIANTS
63        .iter()
64        .map(|name| format!("{name}_import_anchor"))
65        .any(|required| export_names.iter().any(|name| *name == required));
66
67    let has_prefixed_thread_anchor = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
68        .iter()
69        .map(|name| {
70            UniqueName::ThreadsSpawn(&crate::unique_name::ThreadsSpawnName::ImportAnchor(name))
71                .to_string()
72        })
73        .any(|required| export_names.iter().any(|name| *name == required));
74
75    has_wasip1_anchor || has_prefixed_thread_anchor
76}
77
78fn normalize_name(s: &str) -> String {
79    s.replace('-', "_")
80}
81
82impl StreamChecker for CheckUseLibraryChecker {
83    fn check(&mut self, payload: &Payload) -> Result<()> {
84        if let Payload::ExportSection(s) = payload {
85            for export in s.clone() {
86                let export = export.unwrap();
87                self.export_names.push(export.name.to_string());
88            }
89        } else if let Payload::End(_) = payload {
90            let names_ref: Vec<&str> = self.export_names.iter().map(|s| s.as_str()).collect();
91
92            if !has_library_import_anchor_names(&names_ref) {
93                eyre::bail!(
94                    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."#
95                );
96            }
97
98            // check use import_wasm!
99            for wasm_name in self.ctx.target_names.iter() {
100                let normalized_name = normalize_name(wasm_name.as_ref());
101                if !self
102                    .export_names
103                    .iter()
104                    .any(|name| name == &format!("__wasip1_vfs_{normalized_name}__start_anchor"))
105                {
106                    let suggests = self
107                        .export_names
108                        .iter()
109                        .filter_map(|name| {
110                            if name.starts_with("__wasip1_vfs_") && name.ends_with("__start_anchor")
111                            {
112                                Some(
113                                    name.replace("__wasip1_vfs_", "")
114                                        .replace("__start_anchor", ""),
115                                )
116                            } else {
117                                None
118                            }
119                        })
120                        .collect::<Vec<_>>();
121                    eyre::bail!(
122                        "WASM module `{wasm_name}` is provided as a target argument, but not declared with `import_wasm!` macro in VFS. Found: {suggests:?}"
123                    );
124                }
125            }
126
127            // Check that all import_wasm! declarations have corresponding target WASM arguments
128            let declared_wasm_names = self
129                .export_names
130                .iter()
131                .filter_map(|name| {
132                    name.strip_prefix("__wasip1_vfs_")?
133                        .strip_suffix("__start_anchor")
134                        .map(|s| s.to_string())
135                })
136                .collect::<Vec<_>>();
137
138            for declared_name in declared_wasm_names {
139                if declared_name == "anonymous"
140                    || normalize_name(&declared_name) == normalize_name(self.ctx.vfs_name.as_ref())
141                {
142                    continue;
143                }
144
145                if !self
146                    .ctx
147                    .target_names
148                    .iter()
149                    .any(|target| normalize_name(target.as_ref()) == normalize_name(&declared_name))
150                {
151                    eyre::bail!(
152                        "WASM module `{declared_name}` is declared with `import_wasm!` macro in VFS, but not provided as a target argument. \
153                         Did you forget to specify this WASM file in the CLI arguments?"
154                    );
155                }
156            }
157        }
158        Ok(())
159    }
160}
161
162/// Strict check validating that compiled WASM matches intended thread-safe / single-threaded memory paradigms.
163#[derive(Debug)]
164pub struct CheckVFSMemoryTypeChecker {
165    ctx: GeneratorCtx,
166    target_memory_type: Option<crate::args::TargetMemoryType>,
167}
168
169impl CheckVFSMemoryTypeChecker {
170    pub fn new(ctx: GeneratorCtx) -> Self {
171        Self {
172            ctx,
173            target_memory_type: None,
174        }
175    }
176}
177
178impl StreamChecker for CheckVFSMemoryTypeChecker {
179    fn check(&mut self, payload: &Payload) -> Result<()> {
180        if let Payload::MemorySection(s) = payload {
181            for memory in s.clone().into_iter() {
182                let memory = memory.unwrap();
183                // Determine memory type from the first memory definition
184                if memory.shared {
185                    self.target_memory_type = Some(crate::args::TargetMemoryType::Multi);
186                } else {
187                    self.target_memory_type = Some(crate::args::TargetMemoryType::Single);
188                }
189                break;
190            }
191        } else if let Payload::End(_) = payload {
192            if let Some(target_memory_type) = self.target_memory_type {
193                if self.ctx.target_memory_type != target_memory_type {
194                    eyre::bail!(
195                        "Target memory type mismatch: expected {:?}, found {:?}. Why?",
196                        self.ctx.target_memory_type,
197                        target_memory_type
198                    );
199                }
200            } else {
201                log::warn!("No memory section found to check memory type.");
202            }
203        }
204        Ok(())
205    }
206}
207
208/// Quick invariant check asserting if Virtual Memory hooks exist inside Target Wasm representation.
209#[derive(Debug, Default)]
210pub struct CheckUseWasiVirtLayerChecker {
211    found: bool,
212}
213
214impl CheckUseWasiVirtLayerChecker {
215    pub fn new() -> Self {
216        Self { found: false }
217    }
218}
219
220impl StreamChecker for CheckUseWasiVirtLayerChecker {
221    fn check(&mut self, payload: &Payload) -> Result<()> {
222        match payload {
223            Payload::ExportSection(s) => {
224                for export in s.clone().into_iter() {
225                    let export = export?;
226                    if export.name == "__wasip1_vfs_flag_vfs_memory" {
227                        self.found = true;
228                    }
229                }
230            }
231            Payload::End(_) => {
232                if !self.found {
233                    eyre::bail!(
234                        r#"This wasm file is not use "wasi_virt_layer" crate, you need to add it to your dependencies and use wasi_virt_layer;"#
235                    );
236                }
237            }
238            _ => {}
239        }
240        Ok(())
241    }
242}