wasi_virt_layer_cli/generator/
abi_connect.rs1use itertools::Itertools;
2use strum::VariantNames;
3
4use crate::{
5 abi::{Wasip1ABIFunc, Wasip1ThreadsABIExportFunc, Wasip1ThreadsABIFunc},
6 generator::{Generator, threads::ThreadsSpawnName},
7 unique_name::UniqueName,
8 util::{
9 ResultUtil as _, WalrusFID, WalrusFIDAssister as _, WalrusUtilExport, WalrusUtilImport,
10 WalrusUtilModule, WasmName, gen_component_name,
11 },
12};
13use eyre::WrapErr as _;
14
15#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
17#[strum(serialize_all = "snake_case")]
18pub enum Wasip1ABIName<'a> {
19 #[strum(serialize = "__self")]
20 SelfDefault {
22 import: &'a str,
24 },
25 #[strum(serialize = "")]
26 TargetTemporal {
28 wasm: &'a WasmName,
30 import: &'a str,
32 },
33}
34
35#[derive(Debug, Default)]
47pub struct ConnectWasip1ABI;
48
49impl Generator for ConnectWasip1ABI {
50 fn pre_vfs(
53 &mut self,
54 module: &mut walrus::Module,
55 ctx: &super::GeneratorCtx,
56 ) -> eyre::Result<()> {
57 for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
58 let export = UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import })
59 .get_fid(&module.exports)
60 .ok();
61
62 if let Some(import_id) = (
63 UniqueName::WASIP1_ABI_MODULE,
66 import,
67 )
68 .get_fid(&module.imports)
69 .ok()
70 {
71 if let Some(_) = export {
72 module.connect_func_alt_with_remove_export(
73 import_id,
74 &UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import }).to_string(),
75 ctx.unstable_print_debug,
76 )?;
77 } else {
78 log::warn!("No plug found for Wasip1 ABI import self: {import}");
79 }
80 } else {
81 if let Some(_) = export {
82 module
83 .exports
84 .remove(
85 &UniqueName::Wasip1ABI(&Wasip1ABIName::SelfDefault { import })
86 .to_string(),
87 )
88 .unwrap();
89 }
90 }
91 }
92
93 Ok(())
94 }
95
96 fn pre_target(
97 &mut self,
98 module: &mut walrus::Module,
99 _: &crate::generator::GeneratorCtx,
100 external: &crate::generator::ModuleExternal,
101 ) -> eyre::Result<()> {
102 module
103 .imports
104 .iter_mut()
105 .filter(|import| {
106 <Wasip1ABIFunc as strum::VariantNames>::VARIANTS.contains(&import.name.as_str())
107 && import.module == UniqueName::WASIP1_ABI_MODULE
108 })
109 .for_each(|import| {
110 import.name =
111 crate::unique_name::UniqueName::Wasip1ABI(&Wasip1ABIName::TargetTemporal {
112 wasm: &external.name,
113 import: import.name.as_str(),
114 })
115 .to_string();
116 });
117
118 Ok(())
119 }
120
121 fn post_combine(
122 &mut self,
123 module: &mut walrus::Module,
124 ctx: &crate::generator::GeneratorCtx,
125 ) -> eyre::Result<()> {
126 for wasm in &ctx.target_names {
127 for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
128 if let Some(_import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
129 .get_fid(&module.imports)
130 .ok()
131 {
132 unreachable!();
133 } else {
135 module
136 .exports
137 .erase_with(
138 &UniqueName::Wasip1ABI(&Wasip1ABIName::TargetTemporal { wasm, import }),
139 ctx.unstable_print_debug,
140 )
141 .ok();
142 }
143 }
144 }
145 Ok(())
146 }
147}
148
149#[derive(Debug, Default)]
157pub struct ConnectWasip1ThreadsABI;
158
159impl Generator for ConnectWasip1ThreadsABI {
160 fn post_combine(
161 &mut self,
162 module: &mut walrus::Module,
163 ctx: &crate::generator::GeneratorCtx,
164 ) -> eyre::Result<()> {
165 if ctx.threads {
166 for wasm in &ctx.target_names {
167 let start_import = (
168 UniqueName::NAMESPACE,
169 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStart(wasm)),
170 );
171
172 let dest_name =
173 UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
174 .to_string();
175 let dest_fid = module.exports.get_fid_by_name(&dest_name).ok();
176
177 if let Some(_) = dest_fid {
178 module.connect_func_alt_with_remove_export(
179 start_import,
180 &dest_name,
181 ctx.unstable_print_debug,
182 )?;
183 } else {
184 if let Ok(import_id) = start_import.get_fid(&module.imports) {
186 log::warn!(
187 "Thread start destination not found for {}, connecting to trap.",
188 wasm
189 );
190 module
192 .replace_imported_func(import_id, |(body, _)| {
193 body.unreachable();
194 })
195 .to_eyre()
196 .wrap_err_with(|| {
197 eyre::eyre!("Failed to replace missing thread start import")
198 })?;
199 }
200 }
201
202 module
203 .exports
204 .erase_with(
205 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartAnchor(wasm)),
206 ctx.unstable_print_debug,
207 )
208 .ok();
209
210 let spawn_import = (
211 UniqueName::WASIP1_THREADS_ABI_MODULE,
212 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)),
213 );
214 let spawn_dest_name =
215 UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
216
217 if let Ok(import_id) = spawn_import.get_fid(&module.imports) {
218 if let Ok(_) = module.exports.get_fid_by_name(&spawn_dest_name) {
219 module.connect_func_alt_with_remove_export(
220 spawn_import,
221 &spawn_dest_name,
222 ctx.unstable_print_debug,
223 )?;
224 } else {
225 module
226 .replace_imported_func(import_id, |(body, _)| {
227 body.unreachable();
228 })
229 .to_eyre()
230 .wrap_err_with(|| {
231 eyre::eyre!("Failed to replace missing thread spawn import")
232 })?;
233 }
234 }
235 }
236 }
237 Ok(())
238 }
239}
240
241#[derive(Debug, Default)]
251pub struct NonRecursiveWasiABI;
252
253impl Generator for NonRecursiveWasiABI {
254 fn pre_vfs(
255 &mut self,
256 module: &mut walrus::Module,
257 _: &super::GeneratorCtx,
258 ) -> eyre::Result<()> {
259 for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
260 if let Some(fid) = (UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT, import)
261 .get_fid(&module.imports)
262 .ok()
263 {
264 if let Some(import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
266 .get_fid(&module.imports)
267 .ok()
268 {
269 module.renew_call_fn(fid, import_id)?;
270 } else {
271 let import_id = module.imports.get_imported_func(fid).unwrap().id();
272 let import = module.imports.get_mut(import_id);
273 import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
274 }
275 }
276 }
277
278 module
279 .imports
280 .iter()
281 .filter(|import| import.module == UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT)
282 .map(|import| &import.name)
283 .for_each(|name| {
284 log::warn!(
285 "Non-recursive Wasip1 ABI import exists: {name}, but this is not verified."
286 );
287 });
288
289 Ok(())
290 }
291}
292
293#[derive(Debug, Clone, Default)]
302pub struct AdjustABI;
303
304impl Generator for AdjustABI {
305 fn post_components(
306 &mut self,
307 module: &mut walrus::Module,
308 ctx: &super::ComponentCtx,
309 ) -> eyre::Result<()> {
310 if !ctx.adjust_abi {
311 return Ok(());
312 }
313
314 for import_name in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
315 if let Ok(import_id) = (
316 UniqueName::CORE_MODULE_ROOT,
317 &gen_component_name(UniqueName::WASIP1_ABI_MODULE_ALT, import_name),
318 )
319 .get_fid(&module.imports)
320 {
321 if let Ok(import_id) =
322 (UniqueName::WASIP1_ABI_MODULE, import_name).get_fid(&module.imports)
323 {
324 module.imports.erase(import_id).unwrap();
325 }
326
327 let import_id = module.imports.get_imported_func(import_id).unwrap().id();
328 let import = module.imports.get_mut(import_id);
329 import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
330 import.name = import_name.to_string();
331 }
332 }
333
334 let import_name = <Wasip1ThreadsABIFunc as strum::VariantNames>::VARIANTS
335 .iter()
336 .exactly_one()
337 .unwrap();
338
339 if let Ok(import_id) = (
340 UniqueName::THREADS_MODULE_ROOT,
341 &gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, import_name),
342 )
343 .get_fid(&module.imports)
344 {
345 if let Ok(import_id) =
346 (UniqueName::WASIP1_THREADS_ABI_MODULE, import_name).get_fid(&module.imports)
347 {
348 module.imports.erase(import_id).unwrap();
349 }
350
351 let import_id = module.imports.get_imported_func(import_id).unwrap().id();
352 let import = module.imports.get_mut(import_id);
353 import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
354 import.name = import_name.to_string();
355
356 let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
357 .iter()
358 .exactly_one()
359 .unwrap();
360
361 if let Ok(export_id) = export_name.get_fid(&module.exports) {
362 module.exports.erase(export_id)?;
363 }
364
365 let id = UniqueName::THREADS_EXPORT_MODULE_ROOT.get_fid(&module.exports)?;
367 let eid = module.exports.get_exported_func(id).unwrap().id();
368 let export = module.exports.get_mut(eid);
369 export.name = UniqueName::THREADS_EXPORT_MODULE_ROOT.to_string();
370 }
371
372 Ok(())
373 }
374}