Skip to main content

wasi_virt_layer_cli/wasm_stream/passes/
patch_component.rs

1use crate::wasm_stream::pipeline::StreamPass;
2use crate::{abi::Wasip1ABIFunc, unique_name::UniqueName, util::gen_component_name};
3use eyre::Result;
4use strum::VariantNames;
5use wasm_encoder::{EntityType, ExportSection, ImportSection, Module};
6use wasmparser::Parser;
7
8/// Apply the patch to use wit-bindgen.
9/// As it will be rejected otherwise,
10/// swap the import function generated by wit with the wasip1 import function.
11pub struct PatchComponentStreamPass;
12
13impl PatchComponentStreamPass {
14    pub fn new() -> Self {
15        Self
16    }
17}
18
19impl StreamPass for PatchComponentStreamPass {
20    fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
21        let mut module = Module::new();
22        let parser = Parser::new(0);
23
24        // Build forward replacements: (CORE_MODULE_ROOT, component_name) -> (WASIP1_ABI_MODULE, name)
25        let mut forward_replacements = std::collections::HashMap::new();
26        // Build reverse replacements: (WASIP1_ABI_MODULE, name) -> (CORE_MODULE_ROOT, component_name)
27        let mut reverse_replacements = std::collections::HashMap::new();
28        let mut anchors_to_remove = std::collections::HashSet::new();
29
30        for (name, (namespace, root)) in
31            <Wasip1ABIFunc as VariantNames>::VARIANTS
32                .iter()
33                .zip(core::iter::repeat((
34                    UniqueName::WASIP1_ABI_MODULE_ALT,
35                    UniqueName::CORE_MODULE_ROOT,
36                )))
37        {
38            let component_name = gen_component_name(namespace, name);
39            forward_replacements.insert(
40                (root.to_string(), component_name.clone()),
41                (UniqueName::WASIP1_ABI_MODULE.to_string(), name.to_string()),
42            );
43            reverse_replacements.insert(
44                (UniqueName::WASIP1_ABI_MODULE.to_string(), name.to_string()),
45                (root.to_string(), component_name),
46            );
47            anchors_to_remove.insert(format!("{name}_import_anchor"));
48        }
49
50        // First pass: collect all import keys to determine which forward/reverse pairs exist
51        let mut has_forward = std::collections::HashSet::new();
52        let mut has_reverse = std::collections::HashSet::new();
53        for payload in wasmparser::Parser::new(0).parse_all(input_wasm) {
54            if let wasmparser::Payload::ImportSection(s) = payload? {
55                for import_group in s {
56                    for import_res in import_group? {
57                        let (_, import) = import_res?;
58                        let key = (import.module.to_string(), import.name.to_string());
59                        if forward_replacements.contains_key(&key) {
60                            has_forward.insert(key);
61                        } else if reverse_replacements.contains_key(&key) {
62                            has_reverse.insert(key);
63                        }
64                    }
65                }
66            }
67        }
68
69        for payload in parser.parse_all(input_wasm) {
70            let payload = payload?;
71            let section_info = payload.as_section().map(|(id, r)| (id, r.clone()));
72
73            match payload {
74                wasmparser::Payload::ImportSection(s) => {
75                    let mut new_import_section = ImportSection::new();
76                    for import_group in s {
77                        for import_res in import_group.unwrap() {
78                            let (_, import) = import_res.unwrap();
79                            let entity_type = match import.ty {
80                                wasmparser::TypeRef::Func(f) => EntityType::Function(f),
81                                wasmparser::TypeRef::Table(t) => EntityType::Table(
82                                    crate::wasm_stream::translator::translate_table_type(
83                                        t,
84                                        &crate::wasm_stream::translator::DefaultRebinder,
85                                    ),
86                                ),
87                                wasmparser::TypeRef::Memory(m) => EntityType::Memory(
88                                    crate::wasm_stream::translator::translate_memory_type(m),
89                                ),
90                                wasmparser::TypeRef::Global(g) => EntityType::Global(
91                                    crate::wasm_stream::translator::translate_global_type(
92                                        g,
93                                        &crate::wasm_stream::translator::DefaultRebinder,
94                                    ),
95                                ),
96                                wasmparser::TypeRef::Tag(t) => EntityType::Tag(
97                                    crate::wasm_stream::translator::translate_tag_type(t),
98                                ),
99                                _ => unimplemented!("TypeRef variant not supported"),
100                            };
101
102                            let key = (import.module.to_string(), import.name.to_string());
103                            let (new_module, new_name) =
104                                if let Some((m, n)) = forward_replacements.get(&key) {
105                                    // Forward: WIT-component import -> wasi_snapshot_preview1
106                                    (m.as_str(), n.as_str())
107                                } else if let Some((m, n)) = reverse_replacements.get(&key) {
108                                    // Only apply reverse if the forward counterpart also exists
109                                    // (i.e., do a true swap only when both sides are present)
110                                    if has_forward.contains(&(m.clone(), n.clone())) {
111                                        (m.as_str(), n.as_str())
112                                    } else {
113                                        (import.module, import.name)
114                                    }
115                                } else {
116                                    (import.module, import.name)
117                                };
118
119                            new_import_section.import(new_module, new_name, entity_type);
120                        }
121                    }
122                    module.section(&new_import_section);
123                }
124                wasmparser::Payload::ExportSection(s) => {
125                    let mut new_export_section = ExportSection::new();
126                    for export in s {
127                        let export = export?;
128                        if !anchors_to_remove.contains(export.name) {
129                            let export_kind = match export.kind {
130                                wasmparser::ExternalKind::Func => wasm_encoder::ExportKind::Func,
131                                wasmparser::ExternalKind::Table => wasm_encoder::ExportKind::Table,
132                                wasmparser::ExternalKind::Memory => {
133                                    wasm_encoder::ExportKind::Memory
134                                }
135                                wasmparser::ExternalKind::Global => {
136                                    wasm_encoder::ExportKind::Global
137                                }
138                                wasmparser::ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
139                                _ => unimplemented!("ExternalKind variant not supported"),
140                            };
141                            new_export_section.export(export.name, export_kind, export.index);
142                        }
143                    }
144                    module.section(&new_export_section);
145                }
146                _ => {
147                    if let Some((id, range)) = section_info {
148                        module.section(&wasm_encoder::RawSection {
149                            id,
150                            data: &input_wasm[range.clone()],
151                        });
152                    }
153                }
154            }
155        }
156
157        Ok(module.finish())
158    }
159}