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 pre_target(
161 &mut self,
162 module: &mut walrus::Module,
163 _: &crate::generator::GeneratorCtx,
164 external: &crate::generator::ModuleExternal,
165 ) -> eyre::Result<()> {
166 module
167 .imports
168 .iter_mut()
169 .filter(|import| {
170 import.name == "wasi_thread_spawn"
171 && (import.module == "wasi" || import.module == "env")
172 })
173 .for_each(|import| {
174 import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
175 import.name = UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(
176 &external.name,
177 ))
178 .to_string();
179 });
180
181 Ok(())
182 }
183
184 fn post_combine(
185 &mut self,
186 module: &mut walrus::Module,
187 ctx: &crate::generator::GeneratorCtx,
188 ) -> eyre::Result<()> {
189 if ctx.threads {
190 for wasm in &ctx.target_names {
191 let start_import = (
192 UniqueName::NAMESPACE,
193 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStart(wasm)),
194 );
195
196 let dest_name =
197 UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
198 .to_string();
199 let dest_fid = module.exports.get_fid_by_name(&dest_name).ok();
200
201 if let Some(_) = dest_fid {
202 module.connect_func_alt_with_remove_export(
203 start_import,
204 &dest_name,
205 ctx.unstable_print_debug,
206 )?;
207 } else {
208 if let Ok(import_id) = start_import.get_fid(&module.imports) {
210 log::warn!(
211 "Thread start destination not found for {}, connecting to trap.",
212 wasm
213 );
214 module
216 .replace_imported_func(import_id, |(body, _)| {
217 body.unreachable();
218 })
219 .to_eyre()
220 .wrap_err_with(|| {
221 eyre::eyre!("Failed to replace missing thread start import")
222 })?;
223 }
224 }
225
226 module
227 .exports
228 .erase_with(
229 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartAnchor(wasm)),
230 ctx.unstable_print_debug,
231 )
232 .ok();
233
234 let spawn_import = (
235 UniqueName::WASIP1_THREADS_ABI_MODULE,
236 &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)),
237 );
238 let spawn_dest_name =
239 UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
240
241 if let Ok(import_id) = spawn_import.get_fid(&module.imports) {
242 if let Ok(_) = module.exports.get_fid_by_name(&spawn_dest_name) {
243 module.connect_func_alt_with_remove_export(
244 spawn_import,
245 &spawn_dest_name,
246 ctx.unstable_print_debug,
247 )?;
248 } else {
249 module
250 .replace_imported_func(import_id, |(body, _)| {
251 body.unreachable();
252 })
253 .to_eyre()
254 .wrap_err_with(|| {
255 eyre::eyre!("Failed to replace missing thread spawn import")
256 })?;
257 }
258 }
259 }
260 }
261 Ok(())
262 }
263}
264
265#[derive(Debug, Default)]
275pub struct NonRecursiveWasiABI;
276
277impl Generator for NonRecursiveWasiABI {
278 fn pre_vfs(
279 &mut self,
280 module: &mut walrus::Module,
281 _: &super::GeneratorCtx,
282 ) -> eyre::Result<()> {
283 for import in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
284 if let Some(fid) = (UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT, import)
285 .get_fid(&module.imports)
286 .ok()
287 {
288 if let Some(import_id) = (UniqueName::WASIP1_ABI_MODULE, import)
290 .get_fid(&module.imports)
291 .ok()
292 {
293 module.renew_call_fn(fid, import_id)?;
294 } else {
295 let import_id = module.imports.get_imported_func(fid).unwrap().id();
296 let import = module.imports.get_mut(import_id);
297 import.module = UniqueName::WASIP1_ABI_MODULE.to_string();
298 }
299 }
300 }
301
302 module
303 .imports
304 .iter()
305 .filter(|import| import.module == UniqueName::CORE_NON_RECURSIVE_MODULE_ROOT)
306 .map(|import| &import.name)
307 .for_each(|name| {
308 log::warn!(
309 "Non-recursive Wasip1 ABI import exists: {name}, but this is not verified."
310 );
311 });
312
313 Ok(())
314 }
315}
316
317#[derive(Debug, Clone, Default)]
326pub struct AdjustABI;
327
328impl Generator for AdjustABI {
329 fn post_components(
330 &mut self,
331 module: &mut walrus::Module,
332 ctx: &super::ComponentCtx,
333 ) -> eyre::Result<()> {
334 if !ctx.adjust_abi {
335 return Ok(());
336 }
337
338 for import_name in <Wasip1ABIFunc as strum::VariantNames>::VARIANTS {
339 if let Ok(import_id) = (
340 UniqueName::CORE_MODULE_ROOT,
341 &gen_component_name(UniqueName::WASIP1_ABI_MODULE_ALT, import_name),
342 )
343 .get_fid(&module.imports)
344 {
345 if let Ok(import_id) =
346 (UniqueName::WASIP1_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_ABI_MODULE.to_string();
354 import.name = import_name.to_string();
355 }
356 }
357
358 let import_name = <Wasip1ThreadsABIFunc as strum::VariantNames>::VARIANTS
359 .iter()
360 .exactly_one()
361 .unwrap();
362
363 if let Ok(import_id) = (
364 UniqueName::THREADS_MODULE_ROOT,
365 &gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, import_name),
366 )
367 .get_fid(&module.imports)
368 {
369 if let Ok(import_id) =
370 (UniqueName::WASIP1_THREADS_ABI_MODULE, import_name).get_fid(&module.imports)
371 {
372 module.imports.erase(import_id).unwrap();
373 }
374
375 let import_id = module.imports.get_imported_func(import_id).unwrap().id();
376 let import = module.imports.get_mut(import_id);
377 import.module = UniqueName::WASIP1_THREADS_ABI_MODULE.to_string();
378 import.name = import_name.to_string();
379
380 let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
381 .iter()
382 .exactly_one()
383 .unwrap();
384
385 if let Ok(export_id) = export_name.get_fid(&module.exports) {
386 module.exports.erase(export_id)?;
387 }
388
389 let id = UniqueName::THREADS_EXPORT_MODULE_ROOT.get_fid(&module.exports)?;
391 let eid = module.exports.get_exported_func(id).unwrap().id();
392 let export = module.exports.get_mut(eid);
393 export.name = UniqueName::THREADS_EXPORT_MODULE_ROOT.to_string();
394 }
395
396 Ok(())
397 }
398}