wasi_virt_layer_cli/generator/
mod.rs

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