1pub mod abi_connect;
3pub mod anonymous;
5pub mod check;
7pub mod debug;
9pub mod memory;
11pub mod patch_component;
13pub mod producer;
15pub mod shared_global;
17pub mod special_func;
19pub mod start_section;
21pub mod threads;
23pub mod wrap_unreachable;
25
26use std::{any::Any, collections::HashMap, fs, io::Read as _, str::FromStr};
27
28use camino::Utf8PathBuf;
29use compact_str::{CompactString, ToCompactString as _};
30use eyre::{Context as _, ContextCompat};
31use itertools::Itertools;
32use walrus::MemoryId;
33
34use crate::{
35 args::{self, TargetMemoryType},
36 compile,
37 config_checker::TomlRestorers,
38 fallback_command,
39 generator::start_section::StartSectionGenerator,
40 unique_name::UniqueName,
41 util::{
42 CaminoUtilModule as _, ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilModule,
43 WasmName, WasmNameHolder,
44 },
45};
46
47#[derive(Debug)]
49pub struct GeneratorCtx {
50 pub vfs_name: WasmName,
52 pub target_names: Box<[WasmName]>,
54 pub target_names_with_self: Box<[WasmName]>,
56 pub vfs_used_memory_id: Option<MemoryId>,
58 pub vfs_used_global_id: Option<Box<[walrus::GlobalId]>>,
60 pub target_used_memory_id: Option<HashMap<WasmName, MemoryId>>,
62 pub target_used_global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
64 pub start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
67 pub target_memory_type: TargetMemoryType,
69 pub unstable_print_debug: bool,
71 pub dwarf: bool,
73 pub threads: bool,
75 pub adjust_abi: bool,
77 pub keep_build_artifacts: bool,
79 pub start_section_builder: Option<start_section::StartSectionBuilder>,
81}
82
83#[derive(Debug, Default)]
85pub struct ComponentCtx {
86 vfs_name: Option<WasmName>,
88 target_names: Option<Box<[WasmName]>>,
90 target_memory_type: Option<TargetMemoryType>,
92 unstable_print_debug: Option<bool>,
94 dwarf: bool,
96 threads: Option<bool>,
98 adjust_abi: bool,
100}
101
102struct CompressNames {
103 names: Box<[String]>,
104}
105
106impl ToString for CompressNames {
107 fn to_string(&self) -> String {
108 self.names
109 .iter()
110 .map(|s| {
111 let len = s.len();
112 let len_len = len.to_string().len();
113 format!("{:09}{}{}", len_len, len, s)
114 })
115 .join("")
116 }
117}
118
119impl FromStr for CompressNames {
120 type Err = eyre::Report;
121
122 fn from_str(s: &str) -> Result<Self, Self::Err> {
123 let mut names = Vec::new();
124 let mut rest = s;
125 while !rest.is_empty() {
126 let len_len = &rest[0..9];
127 let len_len: usize = len_len[len_len
128 .chars()
129 .position(|c| c != '0')
130 .unwrap_or(len_len.chars().count() - 1)..]
131 .parse()
132 .wrap_err_with(|| format!("Failed to parse length of length: {len_len}"))?;
133 rest = rest.get(9..).unwrap();
134 let len: usize = rest
135 .get(0..len_len)
136 .ok_or_else(|| eyre::eyre!("Failed to get length"))?
137 .parse()
138 .wrap_err_with(|| format!("Failed to parse length: {rest}"))?;
139 rest = rest.get(len_len..).unwrap();
140 let name = rest
141 .get(0..len)
142 .ok_or_else(|| eyre::eyre!("Failed to get name"))?;
143 names.push(name.to_string());
144 rest = rest.get(len..).unwrap();
145 }
146 Ok(Self {
147 names: names.into_boxed_slice(),
148 })
149 }
150}
151
152#[derive(Debug, Default)]
154pub struct ComponentCtxVisitor {
155 vfs_name: Option<CompactString>,
156 target_names: Option<Box<[CompactString]>>,
157 target_memory_type: Option<TargetMemoryType>,
158 unstable_print_debug: Option<bool>,
159 dwarf: Option<bool>,
160 threads: Option<bool>,
161 adjust_abi: bool,
162}
163
164impl ComponentCtxVisitor {
165 pub fn new(
167 vfs_name: WasmName,
168 target_names: Box<[WasmName]>,
169 target_memory_type: TargetMemoryType,
170 unstable_print_debug: bool,
171 dwarf: bool,
172 threads: bool,
173 adjust_abi: bool,
174 ) -> Self {
175 Self {
176 vfs_name: Some(vfs_name.to_compact_string()),
177 target_names: Some(
178 target_names
179 .into_iter()
180 .map(|s| s.to_compact_string())
181 .collect(),
182 ),
183 target_memory_type: Some(target_memory_type),
184 unstable_print_debug: Some(unstable_print_debug),
185 dwarf: Some(dwarf),
186 threads: Some(threads),
187 adjust_abi,
188 }
189 }
190}
191
192impl Generator for ComponentCtxVisitor {
193 fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
194 let vfs_name = ctx.vfs_name.to_compact_string();
195 let target_names = CompressNames {
196 names: ctx
197 .target_names
198 .iter()
199 .map(|s| s.to_string())
200 .collect::<Box<_>>(),
201 };
202 let GeneratorCtx {
203 vfs_name: _,
204 target_names: _,
205 target_memory_type,
206 unstable_print_debug,
207 dwarf,
208 threads,
209 adjust_abi,
210 target_names_with_self: _,
211 vfs_used_memory_id: _,
212 vfs_used_global_id: _,
213 target_used_memory_id: _,
214 target_used_global_id: _,
215 start_func_id: _,
216 keep_build_artifacts: _,
217 start_section_builder: _,
218 } = ctx;
219 module.save_info("vfs_name", vfs_name.to_string())?;
220 module.save_info("target_names", target_names)?;
221 module.save_info("target_memory_type", *target_memory_type)?;
222 module.save_info("unstable_print_debug", *unstable_print_debug)?;
223 module.save_info("dwarf", *dwarf)?;
224 module.save_info("threads", *threads)?;
225 module.save_info("adjust_abi", *adjust_abi)?;
226 Ok(())
227 }
228
229 fn post_components(
230 &mut self,
231 module: &mut walrus::Module,
232 _: &ComponentCtx,
233 ) -> eyre::Result<()> {
234 let vfs_name = module.load_info::<String>("vfs_name")?;
235 let target_names = module.load_info::<CompressNames>("target_names")?;
236 let target_memory_type = module.load_info::<TargetMemoryType>("target_memory_type")?;
237 let unstable_print_debug = module.load_info::<bool>("unstable_print_debug")?;
238 let dwarf = module.load_info::<bool>("dwarf")?;
239 let threads = module.load_info::<bool>("threads")?;
240 let adjust_abi = module.load_info::<bool>("adjust_abi")?;
241 self.vfs_name = Some(vfs_name.to_compact_string());
242 self.target_names = Some(
243 target_names
244 .names
245 .into_iter()
246 .map(|s| s.to_compact_string())
247 .collect(),
248 );
249 self.target_memory_type = Some(target_memory_type);
250 self.unstable_print_debug = Some(unstable_print_debug);
251 self.dwarf = Some(dwarf);
252 self.threads = Some(threads);
253 self.adjust_abi = adjust_abi;
254
255 Ok(())
256 }
257}
258
259impl ComponentCtx {
260 pub fn new(
262 vfs_name: WasmName,
263 target_names: Box<[WasmName]>,
264 target_memory_type: TargetMemoryType,
265 unstable_print_debug: bool,
266 dwarf: bool,
267 threads: bool,
268 adjust_abi: bool,
269 ) -> Self {
270 Self {
271 vfs_name: Some(vfs_name),
272 target_names: Some(target_names),
273 target_memory_type: Some(target_memory_type),
274 unstable_print_debug: Some(unstable_print_debug),
275 dwarf,
276 threads: Some(threads),
277 adjust_abi,
278 }
279 }
280
281 pub fn vfs_name(&self) -> &WasmName {
283 self.vfs_name.as_ref().unwrap()
284 }
285
286 pub fn target_names(&self) -> &Box<[WasmName]> {
288 self.target_names.as_ref().unwrap()
289 }
290
291 pub fn target_memory_type(&self) -> TargetMemoryType {
293 self.target_memory_type.unwrap()
294 }
295
296 pub fn unstable_print_debug(&self) -> bool {
298 self.unstable_print_debug.unwrap()
299 }
300
301 pub fn dwarf(&self) -> bool {
303 self.dwarf
304 }
305
306 pub fn threads(&self) -> bool {
308 self.threads.unwrap()
309 }
310}
311
312pub trait Generator: std::fmt::Debug + Any {
314 #[allow(unused_variables)]
316 fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
317 Ok(())
318 }
319
320 #[allow(unused_variables)]
322 fn pre_target(
323 &mut self,
324 module: &mut walrus::Module,
325 ctx: &GeneratorCtx,
326 external: &ModuleExternal,
327 ) -> eyre::Result<()> {
328 Ok(())
329 }
330
331 #[allow(unused_variables)]
333 fn post_combine(
334 &mut self,
335 module: &mut walrus::Module,
336 ctx: &GeneratorCtx,
337 ) -> eyre::Result<()> {
338 Ok(())
339 }
340
341 #[allow(unused_variables)]
344 fn post_lower_memory(
345 &mut self,
346 module: &mut walrus::Module,
347 ctx: &GeneratorCtx,
348 ) -> eyre::Result<()> {
349 Ok(())
350 }
351
352 #[allow(unused_variables)]
354 fn post_components(
355 &mut self,
356 module: &mut walrus::Module,
357 ctx: &ComponentCtx,
358 ) -> eyre::Result<()> {
359 Ok(())
360 }
361
362 #[allow(unused_variables)]
367 fn post_all_optimize(
368 &mut self,
369 module: &mut walrus::Module,
370 ctx: &ComponentCtx,
371 ) -> eyre::Result<bool> {
372 Ok(false)
373 }
374}
375impl<T: std::fmt::Debug + Any + Generator> Generator for [T] {
376 fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
377 for generator in self {
378 generator.pre_vfs(module, ctx).wrap_err_with(|| {
379 eyre::eyre!(format!("Failed to run pre_vfs for {generator:?}"))
380 })?;
381 }
382 Ok(())
383 }
384
385 fn pre_target(
386 &mut self,
387 module: &mut walrus::Module,
388 ctx: &GeneratorCtx,
389 external: &ModuleExternal,
390 ) -> eyre::Result<()> {
391 for generator in self {
392 generator
393 .pre_target(module, ctx, external)
394 .wrap_err_with(|| {
395 eyre::eyre!(format!("Failed to run pre_target for {generator:?}"))
396 })?;
397 }
398 Ok(())
399 }
400
401 fn post_combine(
402 &mut self,
403 module: &mut walrus::Module,
404 ctx: &GeneratorCtx,
405 ) -> eyre::Result<()> {
406 for generator in self {
407 generator.post_combine(module, ctx).wrap_err_with(|| {
408 eyre::eyre!(format!("Failed to run post_combine for {generator:?}"))
409 })?;
410 }
411 Ok(())
412 }
413
414 fn post_lower_memory(
415 &mut self,
416 module: &mut walrus::Module,
417 ctx: &GeneratorCtx,
418 ) -> eyre::Result<()> {
419 for generator in self {
420 generator.post_lower_memory(module, ctx).wrap_err_with(|| {
421 eyre::eyre!(format!("Failed to run post_lower_memory for {generator:?}"))
422 })?;
423 }
424 Ok(())
425 }
426
427 fn post_components(
428 &mut self,
429 module: &mut walrus::Module,
430 ctx: &ComponentCtx,
431 ) -> eyre::Result<()> {
432 for generator in self {
433 generator.post_components(module, ctx).wrap_err_with(|| {
434 eyre::eyre!(format!("Failed to run post_components for {generator:?}"))
435 })?;
436 }
437 Ok(())
438 }
439
440 fn post_all_optimize(
441 &mut self,
442 module: &mut walrus::Module,
443 ctx: &ComponentCtx,
444 ) -> eyre::Result<bool> {
445 let mut changed = false;
446 for generator in self {
447 changed |= generator.post_all_optimize(module, ctx).wrap_err_with(|| {
448 eyre::eyre!(format!("Failed to run post_all_optimize for {generator:?}"))
449 })?;
450 }
451 Ok(changed)
452 }
453}
454impl Generator for Box<dyn Generator + 'static> {
455 fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
456 (**self).pre_vfs(module, ctx)
457 }
458
459 fn pre_target(
460 &mut self,
461 module: &mut walrus::Module,
462 ctx: &GeneratorCtx,
463 external: &ModuleExternal,
464 ) -> eyre::Result<()> {
465 (**self).pre_target(module, ctx, external)
466 }
467
468 fn post_combine(
469 &mut self,
470 module: &mut walrus::Module,
471 ctx: &GeneratorCtx,
472 ) -> eyre::Result<()> {
473 (**self).post_combine(module, ctx)
474 }
475
476 fn post_lower_memory(
477 &mut self,
478 module: &mut walrus::Module,
479 ctx: &GeneratorCtx,
480 ) -> eyre::Result<()> {
481 (**self).post_lower_memory(module, ctx)
482 }
483
484 fn post_components(
485 &mut self,
486 module: &mut walrus::Module,
487 ctx: &ComponentCtx,
488 ) -> eyre::Result<()> {
489 (**self).post_components(module, ctx)
490 }
491
492 fn post_all_optimize(
493 &mut self,
494 module: &mut walrus::Module,
495 ctx: &ComponentCtx,
496 ) -> eyre::Result<bool> {
497 (**self).post_all_optimize(module, ctx)
498 }
499}
500impl<'a> Generator for &'a mut (dyn Generator + 'a) {
501 fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
502 (**self).pre_vfs(module, ctx)
503 }
504
505 fn pre_target(
506 &mut self,
507 module: &mut walrus::Module,
508 ctx: &GeneratorCtx,
509 external: &ModuleExternal,
510 ) -> eyre::Result<()> {
511 (**self).pre_target(module, ctx, external)
512 }
513
514 fn post_combine(
515 &mut self,
516 module: &mut walrus::Module,
517 ctx: &GeneratorCtx,
518 ) -> eyre::Result<()> {
519 (**self).post_combine(module, ctx)
520 }
521
522 fn post_lower_memory(
523 &mut self,
524 module: &mut walrus::Module,
525 ctx: &GeneratorCtx,
526 ) -> eyre::Result<()> {
527 (**self).post_lower_memory(module, ctx)
528 }
529
530 fn post_components(
531 &mut self,
532 module: &mut walrus::Module,
533 ctx: &ComponentCtx,
534 ) -> eyre::Result<()> {
535 (**self).post_components(module, ctx)
536 }
537
538 fn post_all_optimize(
539 &mut self,
540 module: &mut walrus::Module,
541 ctx: &ComponentCtx,
542 ) -> eyre::Result<bool> {
543 (**self).post_all_optimize(module, ctx)
544 }
545}
546
547#[derive(Debug)]
549pub struct ModuleExternal {
550 pub name: WasmName,
552}
553
554impl ModuleExternal {
555 pub fn new(name: &WasmName) -> Self {
557 Self { name: name.clone() }
558 }
559}
560
561#[derive(Debug)]
563pub struct GeneratorRunner {
564 pub checkers: Vec<Box<dyn Generator + 'static>>,
566 pub generators: Vec<Box<dyn Generator + 'static>>,
568 pub ctx: GeneratorCtx,
570 pub path: WasmPath,
572 pub targets: Box<[WasmPath]>,
574 pub toml_restorers: Option<TomlRestorers>,
576 pub memory_hint: HashMap<WasmName, usize>,
578 pub wasm_name_holder: WasmNameHolder,
580}
581
582#[derive(Debug)]
584pub struct ComponentRunner {
585 pub generators: Vec<Box<dyn Generator + 'static>>,
587 pub ctx: Option<ComponentCtx>,
589 pub path: WasmPath,
591 pub wasm_name_holder: Option<WasmNameHolder>,
593}
594
595pub(crate) trait WrapRunner<T> {
596 #[allow(unused_variables)]
597 fn wrap_run(
598 self,
599 path: &mut WasmPath,
600 dwarf: bool,
601 keep_build_artifacts: bool,
602 ) -> eyre::Result<T>
603 where
604 Self: Sized;
605}
606
607impl<T, F: FnOnce(&mut walrus::Module) -> eyre::Result<T>> WrapRunner<T> for F {
608 fn wrap_run(
609 self,
610 path: &mut WasmPath,
611 dwarf: bool,
612 keep_build_artifacts: bool,
613 ) -> eyre::Result<T> {
614 let old_path = path.path()?.clone();
615 let module =
616 &mut walrus::Module::load(&old_path, dwarf).wrap_err("Failed to load Wasm module")?;
617
618 let result = (self)(module)?;
619
620 let new_path = old_path.with_extension("adjusted.wasm");
621
622 if fs::metadata(&new_path).is_ok() {
623 fs::remove_file(&new_path)
624 .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
625 }
626
627 module
628 .emit_wasm_file(&new_path)
629 .to_eyre()
630 .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;
631
632 if !keep_build_artifacts && !path.is_original(&old_path) {
633 std::fs::remove_file(&old_path)
634 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
635 }
636
637 path.set_path(new_path)?;
638
639 Ok(result)
640 }
641}
642
643pub(crate) trait EndWithOpt<T> {
644 #[allow(unused_variables)]
645 fn with_opt(
646 self,
647 path: &mut WasmPath,
648 dwarf: bool,
649 keep_build_artifacts: bool,
650 ) -> eyre::Result<T>
651 where
652 Self: Sized;
653
654 #[allow(dead_code)]
655 fn with_opt_args(
656 self,
657 path: &mut WasmPath,
658 args: &[&str],
659 require_update: bool,
660 dwarf: bool,
661 keep_build_artifacts: bool,
662 ) -> eyre::Result<T>
663 where
664 Self: Sized;
665}
666
667impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
668 fn with_opt(
669 self,
670 path: &mut WasmPath,
671 dwarf: bool,
672 keep_build_artifacts: bool,
673 ) -> eyre::Result<T>
674 where
675 Self: Sized,
676 {
677 let result = (self)(path).wrap_err("Failed to run with with_opt")?;
678
679 println!("Optimizing Wasm...");
680 let old_path = path.path()?.clone();
681 let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
682 .wrap_err("Failed to optimize Wasm")?;
683
684 if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
685 std::fs::remove_file(&old_path)
686 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
687 }
688
689 path.set_path(new_path)?;
690
691 Ok(result)
692 }
693
694 fn with_opt_args(
695 self,
696 path: &mut WasmPath,
697 args: &[&str],
698 require_update: bool,
699 dwarf: bool,
700 keep_build_artifacts: bool,
701 ) -> eyre::Result<T>
702 where
703 Self: Sized,
704 {
705 let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;
706
707 println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
708 let old_path = path.path()?.clone();
709 let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
710 .wrap_err("Failed to optimize Wasm")?;
711
712 if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
713 std::fs::remove_file(&old_path)
714 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
715 }
716
717 path.set_path(new_path)?;
718
719 Ok(result)
720 }
721}
722
723impl GeneratorRunner {
724 pub fn new(
726 path: WasmPath,
727 targets: Box<[WasmPath]>,
728 threads: bool,
729 dwarf: bool,
730 unstable_print_debug: bool,
731 adjust_abi: bool,
732 keep_build_artifacts: bool,
733 memory_type: TargetMemoryType,
734 toml_restorers: TomlRestorers,
735 memory_hint: Box<[Option<usize>]>,
736 ) -> eyre::Result<Self> {
737 let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
738 .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
739 .collect::<eyre::Result<Box<_>>>()?;
740
741 let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
742 let mut wasm_name_holder_iter = wasm_name_holder.iter();
743 let vfs_name = wasm_name_holder_iter
744 .next()
745 .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;
746
747 let target_names = wasm_name_holder_iter.collect::<Box<_>>();
748
749 for name in target_names.iter() {
751 log::info!("Targeting module: {name}");
752 }
753 log::info!("VFS module: {vfs_name}");
754
755 let target_names_with_self = target_names
756 .iter()
757 .cloned()
758 .chain(core::iter::once(vfs_name.clone()))
759 .collect::<Box<_>>();
760
761 let memory_hint = memory_hint
762 .into_iter()
763 .zip(target_names.iter().cloned())
764 .filter_map(|(hint, name)| hint.map(|h| (name, h)))
765 .collect::<HashMap<_, _>>();
766
767 Ok(Self {
768 checkers: Vec::new(),
769 generators: Vec::new(),
770 ctx: GeneratorCtx {
771 vfs_name,
772 target_names,
773 target_names_with_self,
774 target_memory_type: memory_type,
775 unstable_print_debug,
776 dwarf,
777 threads,
778 adjust_abi,
779 keep_build_artifacts,
780 vfs_used_memory_id: None,
781 vfs_used_global_id: None,
782 target_used_memory_id: None,
783 target_used_global_id: None,
784 start_func_id: None,
785 start_section_builder: None,
786 },
787 path,
788 targets,
789 toml_restorers: Some(toml_restorers),
790 memory_hint,
791 wasm_name_holder,
792 })
793 }
794
795 pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
797 self.generators.push(Box::new(generator));
798 }
799
800 pub fn checker(&mut self, checker: impl Generator + 'static) {
802 self.checkers.push(Box::new(checker));
803 }
804
805 pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
807 fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
808 if b.is::<T>() {
809 Some(b.downcast_ref::<T>().unwrap())
810 } else {
811 None
812 }
813 }
814
815 self.generators
816 .iter()
817 .map(|g| g.as_ref())
818 .find_map(|g| downcast_ref::<T>(g))
819 .wrap_err_with(|| {
820 eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
821 })
822 .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
823 }
824
825 #[deprecated(
826 note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
827 )]
828 pub const fn path(&self) -> &WasmPath {
830 &self.path
831 }
832
833 #[deprecated(
834 note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
835 )]
836 pub const fn targets(&self) -> &Box<[WasmPath]> {
838 &self.targets
839 }
840
841 pub const fn ctx(&self) -> &GeneratorCtx {
843 &self.ctx
844 }
845
846 pub fn definitely(&mut self) -> eyre::Result<()> {
848 self.path.definitely(self.ctx.threads)?;
849 for target in &mut self.targets {
850 target.definitely(self.ctx.threads)?;
851 }
852 Ok(())
853 }
854
855 pub fn run_layers_to_component(
857 mut self,
858 out_dir: &Utf8PathBuf,
859 keep_build_artifacts: bool,
860 ) -> eyre::Result<ComponentRunner> {
861 self.definitely()?;
862
863 let toml_restorers = self
864 .toml_restorers
865 .take()
866 .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;
867
868 toml_restorers
869 .restore()
870 .wrap_err("Failed to restore toml files")?;
871
872 let mut mem_id_visitor = MemoryIDVisitor {
873 memory_hint: self.memory_hint.clone(),
874 used_vfs_memory_id: None,
875 used_target_memory_id: None,
876 };
877 let mut global_id_visitor = GlobalIdVisitor {
878 vfs_global_id: None,
879 global_id: None,
880 };
881 let mut start_section_generator = StartSectionGenerator::default();
882
883 let dwarf = self.ctx.dwarf;
884
885 println!("Remove existing output directory...");
886 if std::fs::metadata(&out_dir).is_ok() {
887 std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
888 }
889 std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");
890
891 let mut component_ctx_visitor = ComponentCtxVisitor::new(
892 self.ctx.vfs_name.clone(),
893 self.ctx.target_names.clone(),
894 self.ctx.target_memory_type,
895 self.ctx.unstable_print_debug,
896 self.ctx.dwarf,
897 self.ctx.threads,
898 self.ctx.adjust_abi,
899 );
900
901 println!("Adjusting VFS Wasm...");
902 (|path: &mut WasmPath| {
903 (|module: &mut walrus::Module| {
904 self.checkers
905 .pre_vfs(module, &self.ctx)
906 .wrap_err("Failed to run checkers in pre_vfs")?;
907
908 mem_id_visitor
909 .pre_vfs(module, &self.ctx)
910 .wrap_err("Failed in pre_vfs")?;
911 global_id_visitor
912 .pre_vfs(module, &self.ctx)
913 .wrap_err("Failed in pre_vfs")?;
914
915 self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id;
916
917 component_ctx_visitor
918 .pre_vfs(module, &self.ctx)
919 .wrap_err("Failed in pre_vfs")?;
920
921 start_section_generator.init(
922 module,
923 self.ctx.vfs_name.clone(),
924 &self.ctx.target_names,
925 );
926
927 self.ctx.start_section_builder = Some(start_section_generator.builder());
928
929 self.generators
930 .pre_vfs(module, &self.ctx)
931 .wrap_err("Failed in run_pre_vfs")
932 })
933 .wrap_run(path, dwarf, keep_build_artifacts)
934 })
935 .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
936
937 let mut start_section_generator = Some(start_section_generator);
938
939 println!("Adjusting target Wasm...");
940 self.ctx.vfs_used_memory_id = None;
941 for (target, target_name) in self.targets.iter_mut().zip(self.ctx.target_names.clone()) {
942 (|path: &mut WasmPath| {
943 (|module: &mut walrus::Module| {
944 let external = ModuleExternal::new(&target_name);
945 mem_id_visitor
946 .pre_target(module, &self.ctx, &external)
947 .wrap_err("Failed in pre_target")?;
948 global_id_visitor
949 .pre_target(module, &self.ctx, &external)
950 .wrap_err("Failed in pre_target")?;
951
952 self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.clone();
953
954 self.generators
955 .pre_target(module, &self.ctx, &external)
956 .wrap_err("Failed in run_pre_target")
957 })
958 .wrap_run(path, dwarf, keep_build_artifacts)
959 })
960 .with_opt(target, dwarf, keep_build_artifacts)?;
961 }
962
963 println!("Combining Wasm modules...");
964 self.ctx.vfs_used_memory_id = None;
965 self.ctx.target_used_memory_id = None;
966 let output = format!("{out_dir}/merged.wasm");
967 (|path: &mut WasmPath| {
968 let old_path = path.path()?.clone();
969 merge(
970 &old_path,
971 &self
972 .targets
973 .iter()
974 .map(|t| t.path())
975 .collect::<eyre::Result<Vec<_>>>()?,
976 &output,
977 self.ctx.threads,
978 dwarf,
979 )
980 .wrap_err("Failed to combine Wasm modules")?;
981
982 if !keep_build_artifacts {
983 std::fs::remove_file(&old_path)
984 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
985 for target in self.targets.iter() {
986 if let Ok(target_path) = target.path() {
987 if !target.is_original(target_path) {
988 std::fs::remove_file(target_path).unwrap_or_else(|e| {
989 log::warn!(
990 "Failed to remove intermediate target file {target_path}: {e}"
991 );
992 });
993 }
994 }
995 }
996 }
997
998 path.set_path(output.into())
999 })
1000 .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1001
1002 println!("Adjusting Merged Wasm...");
1003 (|path: &mut WasmPath| {
1004 (|module: &mut walrus::Module| {
1005 mem_id_visitor
1006 .post_combine(module, &self.ctx)
1007 .wrap_err("Failed in post_combine")?;
1008 global_id_visitor
1009 .post_combine(module, &self.ctx)
1010 .wrap_err("Failed in post_combine")?;
1011 let mut start_func_id_visitor = StartFuncIdVisitor::default();
1012 start_func_id_visitor
1013 .post_combine(module, &self.ctx)
1014 .wrap_err("Failed in post_combine")?;
1015
1016 self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1017 self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1018
1019 self.ctx.vfs_used_global_id = global_id_visitor.vfs_global_id.take();
1020 self.ctx.target_used_global_id = global_id_visitor.global_id.take();
1021
1022 self.ctx.start_func_id = start_func_id_visitor.start_func_id.take();
1023
1024 self.generators.post_combine(module, &self.ctx)?;
1025
1026 if self.ctx.target_memory_type == TargetMemoryType::Multi {
1027 start_section_generator
1028 .take()
1029 .unwrap()
1030 .build(module, &self.ctx)?;
1031 }
1032
1033 Ok(())
1034 })
1035 .wrap_run(path, dwarf, keep_build_artifacts)
1036 })
1037 .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1038
1039 self.ctx.vfs_used_memory_id = None;
1040 self.ctx.target_used_memory_id = None;
1041
1042 self.ctx.vfs_used_global_id = None;
1043 self.ctx.target_used_global_id = None;
1044
1045 self.ctx.start_func_id = None;
1046
1047 if self.ctx.target_memory_type == TargetMemoryType::Single {
1048 let old_path = self.path.path()?.clone();
1049
1050 println!("Generating single memory Merged Wasm...");
1051 let optimized_path =
1052 compile::optimize_wasm(&old_path, &["--multi-memory-lowering"], true, dwarf)?;
1053
1054 if !keep_build_artifacts {
1055 std::fs::remove_file(&old_path)
1056 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1057 }
1058
1059 self.path.set_path(optimized_path)?;
1060
1061 (|path: &mut WasmPath| {
1062 (|module: &mut walrus::Module| {
1063 mem_id_visitor
1064 .post_lower_memory(module, &self.ctx)
1065 .wrap_err("Failed in post_lower_memory")?;
1066
1067 self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1068 self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1069
1070 self.generators
1071 .post_lower_memory(module, &self.ctx)
1072 .wrap_err("Failed in run_post_lower_memory")?;
1073
1074 start_section_generator
1075 .take()
1076 .unwrap()
1077 .build(module, &self.ctx)?;
1078
1079 Ok(())
1080 })
1081 .wrap_run(path, dwarf, keep_build_artifacts)
1082 })
1083 .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1084 }
1085
1086 println!("Translating Wasm to Component...");
1087 let old_path = self.path.path()?.clone();
1088 let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
1089 .wrap_err("Failed to translate Wasm to Component")?;
1090 if !keep_build_artifacts {
1091 std::fs::remove_file(&old_path)
1092 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1093 }
1094
1095 let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
1096 std::fs::rename(&component, &new_component)
1097 .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;
1098
1099 self.path.set_path(Utf8PathBuf::from(new_component))?;
1100
1101 Ok(ComponentRunner::with_generators(self.path, self.generators))
1102 }
1103}
1104
1105impl ComponentRunner {
1106 pub fn new(path: WasmPath) -> Self {
1108 Self {
1109 generators: Vec::new(),
1110 ctx: None,
1111 path,
1112 wasm_name_holder: None,
1113 }
1114 }
1115
1116 pub fn checker(&mut self, checker: impl Generator + 'static) {
1118 self.generators.push(Box::new(checker));
1119 }
1120
1121 pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
1123 Self {
1124 generators,
1125 ctx: None,
1126 path,
1127 wasm_name_holder: None,
1128 }
1129 }
1130
1131 pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
1133 self.generators.push(Box::new(generator));
1134 }
1135
1136 pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
1138 fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
1139 if b.is::<T>() {
1140 Some(b.downcast_ref::<T>().unwrap())
1141 } else {
1142 None
1143 }
1144 }
1145
1146 self.generators
1147 .iter()
1148 .map(|g| g.as_ref())
1149 .find_map(|g| downcast_ref::<T>(g))
1150 .wrap_err_with(|| {
1151 eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
1152 })
1153 .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
1154 }
1155
1156 pub fn component_to_files(
1158 &mut self,
1159 parsed_args: &(impl args::PostBuildContext + ?Sized),
1160 dwarf: bool,
1161 only_core: bool,
1162 ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
1163 let out_dir = parsed_args.out_dir();
1164
1165 let name = self.path.name()?;
1166
1167 println!("Translating Component to JS...");
1168 let core_wasm_path = (|path: &mut WasmPath| {
1169 let old_path = path.path()?.clone();
1170 let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
1171 let transpiled = parsed_args
1172 .transpile_to_js(&binary, &name)
1173 .wrap_err("Failed to transpile to JS")?;
1174
1175 let mut core_wasm = None;
1176 for (name, data) in transpiled.files.iter() {
1177 let name = camino::Utf8PathBuf::from(name);
1178 let file_name = out_dir.join(&name);
1179 if std::fs::metadata(&file_name).is_ok() {
1180 std::fs::remove_file(&file_name).wrap_err_with(|| {
1181 eyre::eyre!("Failed to remove existing file: {file_name}")
1182 })?;
1183 }
1184 if name.as_str().ends_with(".core.wasm") {
1185 let file_name = camino::Utf8PathBuf::from(file_name);
1186 std::fs::write(&file_name, &data).wrap_err_with(|| {
1187 eyre::eyre!("Failed to write core wasm file: {file_name}")
1188 })?;
1189 core_wasm = Some(file_name);
1190 } else {
1191 if let Some(parent) = name.parent() {
1192 if !parent.as_str().is_empty() {
1193 let dir = name.ancestors().nth(1).wrap_err_with(|| {
1194 eyre::eyre!("Failed to get parent directory: {}", name)
1195 })?;
1196 let joined_dir = out_dir.join(dir);
1197 if !std::fs::metadata(&joined_dir).is_ok() {
1198 if dir.as_str() != "interfaces" {
1199 log::warn!("Creating directory: {joined_dir}");
1200 }
1201 if only_core {
1202 continue;
1203 }
1204 std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1205 eyre::eyre!("Failed to create directory: {joined_dir}")
1206 })?;
1207 }
1208 }
1209 }
1210 if only_core {
1211 continue;
1212 }
1213 std::fs::write(&file_name, &data).wrap_err_with(|| {
1214 eyre::eyre!("Failed to write transpiled file: {file_name}")
1215 })?;
1216 }
1217 }
1218
1219 let core_wasm = core_wasm
1220 .as_ref()
1221 .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1222
1223 if !parsed_args.keep_build_artifacts() {
1224 std::fs::remove_file(&old_path)
1225 .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1226 }
1227 path.set_path(core_wasm.clone())?;
1228
1229 Ok(core_wasm.clone())
1230 })
1231 .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1232
1233 let mem_size_visitor = MemorySizeVisitor::default();
1234 self.generators.push(Box::new(mem_size_visitor));
1235
1236 println!("Adjusting component Merged Wasm...");
1237 (|path: &mut WasmPath| {
1238 (|module: &mut walrus::Module| {
1239 let mut visitor = ComponentCtxVisitor::default();
1240 visitor
1241 .post_components(
1242 module,
1243 &ComponentCtx {
1244 dwarf,
1245 ..Default::default()
1246 },
1247 )
1248 .wrap_err("Failed in post_components")?;
1249 let wasm_name_holder = WasmNameHolder::new(
1250 visitor
1251 .target_names
1252 .unwrap()
1253 .into_iter()
1254 .chain(core::iter::once(visitor.vfs_name.unwrap()))
1255 .collect::<Box<_>>(),
1256 );
1257 self.wasm_name_holder = Some(wasm_name_holder);
1258 let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
1259 self.ctx = Some(ComponentCtx {
1260 vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
1261 target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
1262 target_memory_type: Some(visitor.target_memory_type.unwrap()),
1263 unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
1264 dwarf: visitor.dwarf.unwrap(),
1265 threads: Some(visitor.threads.unwrap()),
1266 adjust_abi: visitor.adjust_abi,
1267 });
1268
1269 self.generators
1270 .post_components(module, self.ctx.as_ref().unwrap())
1271 .wrap_err("Failed in run_post_components")
1272 })
1273 .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
1274 })
1275 .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1276
1277 let dwarf = {
1278 let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1279 if dwarf && !new_dwarf {
1280 log::warn!(
1281 "Dwarf was disabled in component processing, you should re-run with --dwarf"
1282 );
1283 }
1284 new_dwarf
1285 };
1286
1287 println!("Final optimizing Merged Wasm...");
1288 let mut i = 0;
1289 while i < self.generators.len() {
1290 (|module: &mut walrus::Module| {
1291 loop {
1292 if self.generators[i]
1293 .post_all_optimize(module, self.ctx.as_ref().unwrap())
1294 .wrap_err("Failed in post_all_optimize")?
1295 {
1296 i += 1;
1297 return Ok(());
1298 }
1299 i += 1;
1300 if i >= self.generators.len() {
1301 return Ok(());
1302 }
1303 }
1304 })
1305 .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1306 }
1307
1308 std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1309 eyre::eyre!(
1310 "Failed to rename final wasm from {} to {}",
1311 self.path.path().unwrap(),
1312 core_wasm_path
1313 )
1314 })?;
1315
1316 Ok((
1317 self.ctx.as_ref().unwrap().threads(),
1318 core_wasm_path
1319 .get_file_main_name()
1320 .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1321 self.get_generator_ref::<MemorySizeVisitor>()?
1322 .mem_size
1323 .clone()
1324 .unwrap(),
1325 ))
1326 }
1327}
1328
1329#[derive(Debug, Default, Clone)]
1330struct MemoryIDVisitor {
1331 pub memory_hint: HashMap<WasmName, usize>,
1332 pub used_vfs_memory_id: Option<MemoryId>,
1333 pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
1334}
1335
1336impl Generator for MemoryIDVisitor {
1337 fn pre_vfs(
1338 &mut self,
1339 module: &mut walrus::Module,
1340 _: &crate::generator::GeneratorCtx,
1341 ) -> eyre::Result<()> {
1342 println!("Finding VFS memory id...");
1343
1344 let id = module
1345 .get_memory_anchor("vfs", false)
1346 .wrap_err("Failed to get target memory id")?;
1347 self.used_vfs_memory_id = Some(id);
1348 Ok(())
1349 }
1350
1351 fn pre_target(
1352 &mut self,
1353 module: &mut walrus::Module,
1354 _: &crate::generator::GeneratorCtx,
1355 external: &ModuleExternal,
1356 ) -> eyre::Result<()> {
1357 let id = module
1358 .find_used_memory_id(self.memory_hint.get(&external.name).copied())
1359 .wrap_err("Failed to find used memory id")?;
1360 module
1361 .create_memory_anchor(&external.name, id)
1362 .wrap_err("Failed to create memory anchor")?;
1363 self.used_target_memory_id
1364 .get_or_insert_default()
1365 .insert(external.name.clone(), id);
1366 Ok(())
1367 }
1368
1369 fn post_combine(
1370 &mut self,
1371 module: &mut walrus::Module,
1372 ctx: &GeneratorCtx,
1373 ) -> eyre::Result<()> {
1374 let id = module
1375 .get_memory_anchor("vfs", true)
1376 .wrap_err("Failed to find used memory id after combine")?;
1377 self.used_vfs_memory_id = Some(id);
1378
1379 self.used_target_memory_id.get_or_insert_default().clear();
1380 for wasm in &ctx.target_names {
1381 let id = module
1382 .get_memory_anchor(wasm, true)
1383 .wrap_err("Failed to find used memory id after combine")?;
1384 self.used_target_memory_id
1385 .as_mut()
1386 .unwrap()
1387 .insert(wasm.clone(), id);
1388 }
1389
1390 Ok(())
1391 }
1392
1393 fn post_lower_memory(
1394 &mut self,
1395 module: &mut walrus::Module,
1396 _: &GeneratorCtx,
1397 ) -> eyre::Result<()> {
1398 let id = module
1399 .get_memory_id()
1400 .to_eyre()
1401 .wrap_err("Failed to get single memory id after lowering")?;
1402 self.used_vfs_memory_id = Some(id);
1403 self.used_target_memory_id = None;
1404
1405 Ok(())
1406 }
1407}
1408
1409#[derive(Debug, Default, Clone)]
1410struct MemorySizeVisitor {
1411 mem_size: Option<HashMap<CompactString, (u64, u64)>>,
1412}
1413
1414impl Generator for MemorySizeVisitor {
1415 fn post_components(
1416 &mut self,
1417 module: &mut walrus::Module,
1418 _: &ComponentCtx,
1419 ) -> eyre::Result<()> {
1420 let mem_size = module
1421 .memories
1422 .iter()
1423 .filter(|mem| mem.import.is_some())
1424 .map(|mem| {
1425 (
1426 module
1427 .imports
1428 .get(mem.import.unwrap())
1429 .name
1430 .to_compact_string(),
1431 (
1432 mem.initial as u64,
1433 mem.maximum.unwrap_or(mem.initial) as u64,
1434 ),
1435 )
1436 })
1437 .collect::<HashMap<_, _>>();
1438 self.mem_size = Some(mem_size);
1439
1440 Ok(())
1441 }
1442}
1443
1444#[derive(Debug, Default)]
1445struct GlobalIdVisitor {
1446 vfs_global_id: Option<Box<[walrus::GlobalId]>>,
1447 global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
1448}
1449impl Generator for GlobalIdVisitor {
1450 fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
1451 module
1452 .create_global_anchor("vfs")
1453 .wrap_err("Failed to create global anchor")?;
1454
1455 Ok(())
1456 }
1457
1458 fn pre_target(
1459 &mut self,
1460 module: &mut walrus::Module,
1461 _: &GeneratorCtx,
1462 external: &ModuleExternal,
1463 ) -> eyre::Result<()> {
1464 module
1465 .create_global_anchor(&external.name)
1466 .wrap_err("Failed to create global anchor")?;
1467
1468 Ok(())
1469 }
1470
1471 fn post_combine(
1472 &mut self,
1473 module: &mut walrus::Module,
1474 ctx: &GeneratorCtx,
1475 ) -> eyre::Result<()> {
1476 self.global_id = Some(HashMap::new());
1477
1478 let vfs_globals = module
1479 .get_global_anchor("vfs")
1480 .wrap_err("Failed to get global anchor for vfs")?;
1481 self.vfs_global_id = Some(vfs_globals);
1482
1483 for wasm in &ctx.target_names {
1484 let globals = module
1485 .get_global_anchor(wasm)
1486 .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
1487 self.global_id
1488 .as_mut()
1489 .unwrap()
1490 .insert(wasm.clone(), globals);
1491 }
1492
1493 Ok(())
1494 }
1495}
1496
1497#[derive(Debug, Default)]
1500struct StartFuncIdVisitor {
1501 start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
1502}
1503
1504impl Generator for StartFuncIdVisitor {
1505 fn post_combine(
1506 &mut self,
1507 module: &mut walrus::Module,
1508 ctx: &GeneratorCtx,
1509 ) -> eyre::Result<()> {
1510 for wasm in &ctx.target_names {
1511 let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
1512 self.start_func_id
1513 .get_or_insert_default()
1514 .insert(wasm.clone(), export);
1515
1516 module
1517 .exports
1518 .erase_with(export, ctx.unstable_print_debug)?;
1519
1520 module.exports.erase_with(
1521 &format!("__wasip1_vfs_{wasm}__start_anchor"),
1522 ctx.unstable_print_debug,
1523 )?;
1524 }
1525
1526 Ok(())
1527 }
1528}
1529
1530#[derive(Debug, Clone)]
1532pub enum WasmPath {
1533 Maybe {
1535 manifest_path: Utf8PathBuf,
1537 package: String,
1539 },
1540 Definitely(Utf8PathBuf),
1542 Component(Utf8PathBuf),
1544 Original {
1547 current: Utf8PathBuf,
1549 original: Utf8PathBuf,
1551 },
1552}
1553
1554impl FromStr for WasmPath {
1555 type Err = eyre::Error;
1556
1557 fn from_str(s: &str) -> Result<Self, Self::Err> {
1559 fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1560 let split = s.split("::").collect::<Vec<_>>();
1561 if split.len() == 2 {
1562 let manifest_path = Utf8PathBuf::from_str(split[0])
1563 .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1564 let package = split[1].to_string();
1565 return Ok(Some(WasmPath::Maybe {
1566 manifest_path,
1567 package,
1568 }));
1569 }
1570 Ok(None)
1571 }
1572
1573 if let Some(wasm_path) =
1574 parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1575 {
1576 return Ok(wasm_path);
1577 }
1578
1579 if s.ends_with(".wasm") {
1580 let path = Utf8PathBuf::from_str(s)
1581 .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1582 return WasmPath::with_wasm(path);
1583 }
1584
1585 if s.ends_with("Cargo.toml") {
1586 let manifest_path = Utf8PathBuf::from_str(s)
1587 .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1588 return WasmPath::with_maybe_only_manifest(manifest_path);
1589 }
1590
1591 WasmPath::with_maybe_only_package(s.to_string())
1592 .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1593 }
1594}
1595
1596impl WasmPath {
1597 pub fn name(&self) -> eyre::Result<CompactString> {
1599 match self {
1600 WasmPath::Maybe { package, .. } => Ok(package.to_compact_string()),
1601 WasmPath::Definitely(path)
1602 | WasmPath::Component(path)
1603 | WasmPath::Original { current: path, .. } => path
1604 .get_file_main_name()
1605 .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1606 }
1607 }
1608
1609 pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1611 match self {
1612 WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1613 WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1614 }
1615 }
1616
1617 pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1619 match self {
1620 WasmPath::Maybe { manifest_path, .. } => {
1621 let cargo_metadata = {
1622 let mut metadata_command = cargo_metadata::MetadataCommand::new();
1623 metadata_command.manifest_path(&manifest_path);
1624 metadata_command.exec().unwrap()
1625 };
1626 Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1627 }
1628 WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1629 }
1630 }
1631
1632 pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1634 Self::Maybe {
1635 manifest_path,
1636 package,
1637 }
1638 }
1639
1640 pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1642 let cargo_metadata = {
1643 let mut metadata_command = cargo_metadata::MetadataCommand::new();
1644 metadata_command.manifest_path(&manifest_path);
1645 metadata_command.exec().unwrap()
1646 };
1647 let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1648
1649 Ok(Self::Maybe {
1650 manifest_path,
1651 package: building_crate.name.to_string(),
1652 })
1653 }
1654
1655 pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1657 let cargo_metadata = {
1658 let metadata_command = cargo_metadata::MetadataCommand::new();
1659 metadata_command.exec().unwrap()
1660 };
1661 let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1662
1663 Ok(Self::Maybe {
1664 manifest_path: building_crate.manifest_path,
1665 package: building_crate.name.to_string(),
1666 })
1667 }
1668
1669 pub fn with_maybe_none() -> eyre::Result<Self> {
1671 let cargo_metadata = {
1672 let metadata_command = cargo_metadata::MetadataCommand::new();
1673 metadata_command.exec().unwrap()
1674 };
1675 let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1676
1677 Ok(Self::Maybe {
1678 manifest_path: building_crate.manifest_path,
1679 package: building_crate.name.to_string(),
1680 })
1681 }
1682
1683 pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1686 if path.extension() != Some("wasm") {
1687 eyre::bail!("Wasm file does not have .wasm extension: {path}");
1688 }
1689 if !fs::metadata(&path).is_ok() {
1690 eyre::bail!("Wasm file does not exist: {path}");
1691 }
1692
1693 let mut file =
1694 fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1695 let mut magic = [0u8; 8];
1696 file.read_exact(&mut magic)
1697 .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1698 if !magic.starts_with(b"\0asm") {
1699 eyre::bail!("Wasm file does not have valid magic number: {path}");
1700 }
1701 let version = &magic[4..8];
1702 if version == [0x0D, 0x00, 0x01, 0x00] {
1704 return Ok(Self::Component(path));
1705 }
1706 if version != [0x01, 0x00, 0x00, 0x00] {
1708 eyre::bail!("Wasm file does not have valid version: {path}");
1709 }
1710
1711 Ok(Self::Original {
1712 current: path.clone(),
1713 original: path,
1714 })
1715 }
1716
1717 pub fn definitely(&mut self, threads: bool) -> eyre::Result<()> {
1719 if let WasmPath::Maybe {
1720 manifest_path,
1721 package,
1722 } = self
1723 {
1724 let cargo_metadata = {
1725 let mut metadata_command = cargo_metadata::MetadataCommand::new();
1726 metadata_command.manifest_path(&manifest_path);
1727 metadata_command.exec().unwrap()
1728 };
1729 let building_crate =
1730 compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1731 let vfs_name = building_crate.name.to_string();
1732
1733 let path =
1734 compile::build_vfs(Some(&manifest_path.to_string()), &building_crate, threads)
1735 .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1736 *self = WasmPath::Definitely(path);
1737 }
1738
1739 Ok(())
1742 }
1743
1744 pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1746 match self {
1747 WasmPath::Maybe { .. } => {
1748 eyre::bail!("WasmPath is not definitely set: {self:?}")
1749 }
1750 WasmPath::Definitely(p)
1751 | WasmPath::Component(p)
1752 | WasmPath::Original { current: p, .. } => Ok(p),
1753 }
1754 }
1755
1756 pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1758 matches!(self, WasmPath::Original { original, .. } if original == path)
1759 }
1760
1761 pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1764 match self {
1765 WasmPath::Maybe { .. } => {
1766 eyre::bail!("WasmPath is not definitely set: {path}")
1767 }
1768 WasmPath::Original { current, .. } => {
1769 *current = path;
1771 }
1772 _ => {
1773 *self = WasmPath::Definitely(path);
1774 }
1775 }
1776 Ok(())
1777 }
1778}
1779
1780pub fn merge(
1782 vfs: &Utf8PathBuf,
1783 wasm: &[impl AsRef<std::path::Path>],
1784 output: impl AsRef<std::path::Path>,
1785 _threads: bool,
1786 dwarf: bool,
1787) -> eyre::Result<()> {
1788 let custom_section = {
1789 let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
1790 let custom_section_names = vfs_module
1791 .customs
1792 .iter()
1793 .map(|(_, section)| section.name().to_string())
1794 .filter(|name| name.starts_with("component-type:"))
1795 .collect::<Vec<_>>();
1796 let custom_section = custom_section_names
1799 .iter()
1800 .map(|id| {
1801 let section = vfs_module.customs.remove_raw(id);
1802 section.unwrap()
1803 })
1804 .collect::<Vec<_>>();
1805
1806 custom_section
1807 };
1808
1809 let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");
1810
1811 if dwarf {
1816 merge_cmd.arg("--debuginfo");
1817 }
1818
1819 merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);
1820
1821 for wasm in wasm {
1822 merge_cmd
1823 .arg(wasm.as_ref().as_os_str().to_str().unwrap())
1824 .arg(format!(
1825 "wasip1_vfs_{}",
1826 wasm.as_ref().get_file_main_name().unwrap()
1827 ));
1828 }
1829
1830 merge_cmd
1831 .arg("--output")
1832 .arg(output.as_ref().as_os_str().to_str().unwrap())
1833 .arg("--enable-multimemory")
1835 .arg("--enable-threads");
1836
1837 let result = merge_cmd
1838 .spawn()
1839 .map_err(|e| match e.kind() {
1840 std::io::ErrorKind::NotFound => eyre::eyre!(
1841 "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
1842 ),
1843 _ => e.into(),
1844 })?
1845 .wait_with_output()
1846 .wrap_err("Failed to wait for wasm-merge process")?;
1847
1848 if !result.success {
1849 return Err(eyre::eyre!("wasm-merge command failed"));
1850 }
1851
1852 let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
1853 for section in custom_section {
1854 module.customs.add(section);
1855 }
1856
1857 fs::remove_file(output.as_ref()).expect("Failed to remove existing file");
1859
1860 module
1861 .emit_wasm_file(output.as_ref())
1862 .expect("Failed to emit wasm file");
1863
1864 Ok(())
1865}
1866
1867macro_rules! _add_generators_by_type {
1868 ($runner:expr, $($ty:ty),* $(,)?) => {
1869 $(
1870 if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1871 panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1872 }
1873 $runner.add_generator(<$ty>::default());
1874 )*
1875 };
1876}
1877pub(crate) use _add_generators_by_type as add_generators_by_type;