Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

1use std::{collections::HashMap, fs, io::Read as _, str::FromStr};
2
3use camino::Utf8PathBuf;
4use compact_str::{CompactString, ToCompactString as _};
5use eyre::{Context as _, ContextCompat};
6use itertools::Itertools;
7
8use crate::{
9    args::{self, TargetMemoryType},
10    compile,
11    config_checker::TomlRestorers,
12    unique_name::{MemoryUniqueName, UniqueName},
13    util::{CaminoUtilModule as _, WasmName, WasmNameHolder},
14};
15
16/// Represents the generation context, holding configuration arguments and targeted module info.
17#[derive(Debug, Clone)]
18pub struct GeneratorCtx {
19    /// The name of the VFS module.
20    pub vfs_name: WasmName,
21    /// The names of the target modules.
22    pub target_names: Box<[WasmName]>,
23    /// Including one's own WASI ABI
24    pub target_names_with_self: Box<[WasmName]>,
25
26    /// The memory type of the target modules (Single or Multi).
27    pub target_memory_type: TargetMemoryType,
28    /// Whether to print unstable debug information.
29    pub unstable_print_debug: bool,
30    /// Whether to include DWARF debug information.
31    pub dwarf: bool,
32    /// Whether to enable multi-threading support.
33    pub threads: bool,
34    /// Whether to adjust the ABI for standard environments.
35    pub adjust_abi: bool,
36    /// Whether to keep intermediate build artifacts.
37    pub keep_build_artifacts: bool,
38    /// Whether the VFS module is a library (has no start section / `_start` export).
39    /// Detected during `pre_vfs`; when `true`, the VFS start slot in the
40    /// combined start chain is skipped entirely.
41    pub vfs_is_library: bool,
42    pub wrap_unreachable_targets: std::collections::HashSet<String>,
43    pub main_void_synthesized_targets: Option<std::collections::HashSet<String>>,
44    /// Whether own-memory mode is enabled.
45    pub own_memory: bool,
46    /// Export-stack isolation configuration keyed by module name.
47    pub stack_config: StackConfig,
48    /// Whether to validate generated Wasm modules.
49    pub validate: bool,
50}
51
52/// Normalized export-stack isolation configuration.
53#[derive(Debug, Clone, Default)]
54pub struct StackConfig {
55    /// Stack sizes in bytes. The `vfs` key aliases the actual VFS module name.
56    pub sizes: HashMap<String, u32>,
57    /// Fixed slot counts for multi-memory target modules.
58    pub slots: HashMap<String, u32>,
59}
60
61impl StackConfig {
62    fn from_options(options: args::StackOptions) -> eyre::Result<Self> {
63        let mut config = Self::default();
64        for size in options.sizes {
65            if config
66                .sizes
67                .insert(size.module.clone(), size.bytes)
68                .is_some()
69            {
70                eyre::bail!("duplicate --stack-size for module `{}`", size.module);
71            }
72        }
73        for slots in options.slots {
74            if config
75                .slots
76                .insert(slots.module.clone(), slots.slots)
77                .is_some()
78            {
79                eyre::bail!("duplicate --stack-slots for module `{}`", slots.module);
80            }
81        }
82        Ok(config)
83    }
84
85    /// Returns the configured VFS stack size.
86    pub fn vfs_size(&self, vfs_name: &str) -> Option<u32> {
87        self.sizes
88            .get(vfs_name)
89            .or_else(|| self.sizes.get("vfs"))
90            .copied()
91    }
92
93    /// Returns the configured stack size for a target.
94    pub fn target_size(&self, target_name: &str) -> Option<u32> {
95        self.sizes.get(target_name).copied()
96    }
97}
98
99/// Sub-context for extracting and storing component variables during execution.
100#[derive(Debug, Default)]
101pub struct ComponentCtx {
102    /// Optional name of the VFS module.
103    pub vfs_name: Option<compact_str::CompactString>,
104    /// Optional names of the target modules.
105    pub target_names: Option<Box<[compact_str::CompactString]>>,
106    /// Optional memory type of the target modules.
107    pub target_memory_type: Option<args::TargetMemoryType>,
108    /// Optional flag for unstable debug printing.
109    pub unstable_print_debug: Option<bool>,
110    /// Flag for including DWARF debug information.
111    pub dwarf: bool,
112    /// Optional flag for multi-threading support.
113    pub threads: Option<bool>,
114    /// Flag for ABI adjustment.
115    pub adjust_abi: bool,
116    /// Flag for own-memory mode.
117    pub own_memory: bool,
118}
119
120impl ComponentCtx {
121    /// Creates a new `ComponentCtx` with the specified context parameters.
122    pub fn new(
123        vfs_name: compact_str::CompactString,
124        target_names: Box<[compact_str::CompactString]>,
125        target_memory_type: TargetMemoryType,
126        unstable_print_debug: bool,
127        dwarf: bool,
128        threads: bool,
129        adjust_abi: bool,
130        own_memory: bool,
131    ) -> Self {
132        Self {
133            vfs_name: Some(vfs_name),
134            target_names: Some(target_names),
135            target_memory_type: Some(target_memory_type),
136            unstable_print_debug: Some(unstable_print_debug),
137            dwarf,
138            threads: Some(threads),
139            adjust_abi,
140            own_memory,
141        }
142    }
143
144    /// Returns the name of the VFS module.
145    pub fn vfs_name(&self) -> &compact_str::CompactString {
146        self.vfs_name.as_ref().unwrap()
147    }
148
149    /// Returns the names of the target modules.
150    pub fn target_names(&self) -> &Box<[compact_str::CompactString]> {
151        self.target_names.as_ref().unwrap()
152    }
153
154    /// Returns the memory type of the target modules.
155    pub fn target_memory_type(&self) -> TargetMemoryType {
156        self.target_memory_type.unwrap()
157    }
158
159    /// Returns whether to print unstable debug information.
160    pub fn unstable_print_debug(&self) -> bool {
161        self.unstable_print_debug.unwrap()
162    }
163
164    /// Returns whether to include DWARF debug information.
165    pub fn dwarf(&self) -> bool {
166        self.dwarf
167    }
168
169    /// Returns whether to enable multi-threading support.
170    pub fn threads(&self) -> bool {
171        self.threads.unwrap()
172    }
173}
174
175/// Coordinates iterating over registered generators and merging external module logic into the VFS.
176#[derive(Debug)]
177pub struct GeneratorRunner {
178    /// The context used during generation.
179    pub ctx: GeneratorCtx,
180    /// The path to the WASM module.
181    pub path: WasmPath,
182    /// The paths to the target WASM modules.
183    pub targets: Box<[WasmPath]>,
184    /// Options for building the VFS module.
185    pub vfs_build_opts: args::VfsBuildOptions,
186    /// Options for building the target WASM modules.
187    pub target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
188    /// The TOML restorers used to reset configuration files.
189    pub toml_restorers: Option<TomlRestorers>,
190    /// Memory hints for the target modules.
191    pub memory_hint: HashMap<WasmName, usize>,
192    /// Holder for the names of the WASM modules.
193    pub wasm_name_holder: WasmNameHolder,
194}
195
196/// A runner that coordinates the generation of a WebAssembly component.
197#[derive(Debug)]
198pub struct ComponentRunner {
199    /// Encapsulates contextual settings across all generator components during transpilation.
200    pub ctx: Option<ComponentCtx>,
201    /// Specifies the target active WASM module destination.
202    pub path: WasmPath,
203    /// Manages dynamically generated and globally referenced named functions.
204    pub wasm_name_holder: Option<WasmNameHolder>,
205}
206
207pub(crate) trait WrapRunner<T> {
208    #[allow(unused_variables)]
209    fn wrap_run(
210        self,
211        path: &mut WasmPath,
212        dwarf: bool,
213        keep_build_artifacts: bool,
214        stream_pipeline: Option<crate::wasm_stream::pipeline::Pipeline>,
215        validate: bool,
216    ) -> eyre::Result<T>
217    where
218        Self: Sized;
219}
220
221impl<T, F: FnOnce() -> eyre::Result<T>> WrapRunner<T> for F {
222    fn wrap_run(
223        self,
224        path: &mut WasmPath,
225        _dwarf: bool,
226        keep_build_artifacts: bool,
227        mut stream_pipeline: Option<crate::wasm_stream::pipeline::Pipeline>,
228        validate: bool,
229    ) -> eyre::Result<T> {
230        let old_path = path.path()?.clone();
231
232        let result = (self)()?;
233
234        if let Some(pipeline) = &mut stream_pipeline {
235            let input_wasm = fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
236            let output_wasm = pipeline
237                .run(&input_wasm)
238                .wrap_err("Failed to run StreamPipeline pre-walrus")?;
239
240            let new_path = old_path.with_extension("adjusted.wasm");
241
242            if fs::metadata(&new_path).is_ok() {
243                fs::remove_file(&new_path)
244                    .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
245            }
246
247            std::fs::write(&new_path, &output_wasm)
248                .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;
249
250            if validate {
251                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
252                    .validate_all(&output_wasm)
253                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
254            }
255
256            if !keep_build_artifacts && !path.is_original(&old_path) {
257                std::fs::remove_file(&old_path).unwrap_or_else(|e| {
258                    log::warn!("Failed to remove intermediate file {old_path}: {e}")
259                });
260            }
261
262            path.set_path(new_path)?;
263        }
264
265        Ok(result)
266    }
267}
268
269pub(crate) trait EndWithOpt<T> {
270    #[allow(unused_variables)]
271    fn with_opt(
272        self,
273        path: &mut WasmPath,
274        dwarf: bool,
275        keep_build_artifacts: bool,
276        skip_opt: bool,
277        validate: bool,
278    ) -> eyre::Result<T>
279    where
280        Self: Sized;
281
282    #[allow(dead_code)]
283    fn with_opt_args(
284        self,
285        path: &mut WasmPath,
286        args: &[&str],
287        require_update: bool,
288        dwarf: bool,
289        keep_build_artifacts: bool,
290        skip_opt: bool,
291        validate: bool,
292    ) -> eyre::Result<T>
293    where
294        Self: Sized;
295}
296
297impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
298    fn with_opt(
299        self,
300        path: &mut WasmPath,
301        dwarf: bool,
302        keep_build_artifacts: bool,
303        skip_opt: bool,
304        validate: bool,
305    ) -> eyre::Result<T>
306    where
307        Self: Sized,
308    {
309        let result = (self)(path).wrap_err("Failed to run with with_opt")?;
310
311        if skip_opt {
312            println!("Skipping Wasm optimization...");
313            return Ok(result);
314        }
315
316        println!("Optimizing Wasm...");
317        let old_path = path.path()?.clone();
318        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
319            .wrap_err("Failed to optimize Wasm")?;
320
321        if validate {
322            let optimized_wasm = std::fs::read(&new_path)
323                .wrap_err_with(|| format!("Failed to read optimized Wasm from {new_path}"))?;
324            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
325                .validate_all(&optimized_wasm)
326                .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
327        }
328
329        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
330            std::fs::remove_file(&old_path)
331                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
332        }
333
334        path.set_path(new_path)?;
335
336        Ok(result)
337    }
338
339    fn with_opt_args(
340        self,
341        path: &mut WasmPath,
342        args: &[&str],
343        require_update: bool,
344        dwarf: bool,
345        keep_build_artifacts: bool,
346        skip_opt: bool,
347        validate: bool,
348    ) -> eyre::Result<T>
349    where
350        Self: Sized,
351    {
352        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;
353
354        if skip_opt {
355            println!("Skipping Wasm optimization...");
356            return Ok(result);
357        }
358
359        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
360        let old_path = path.path()?.clone();
361        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
362            .wrap_err("Failed to optimize Wasm")?;
363
364        if validate {
365            let optimized_wasm = std::fs::read(&new_path)
366                .wrap_err_with(|| format!("Failed to read optimized Wasm from {new_path}"))?;
367            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
368                .validate_all(&optimized_wasm)
369                .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
370        }
371
372        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
373            std::fs::remove_file(&old_path)
374                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
375        }
376
377        path.set_path(new_path)?;
378
379        Ok(result)
380    }
381}
382
383impl GeneratorRunner {
384    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
385    pub fn new(
386        path: WasmPath,
387        targets: Box<[WasmPath]>,
388        threads: bool,
389        dwarf: bool,
390        unstable_print_debug: bool,
391        adjust_abi: bool,
392        keep_build_artifacts: bool,
393        memory_type: TargetMemoryType,
394        vfs_build_opts: args::VfsBuildOptions,
395        target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
396        toml_restorers: TomlRestorers,
397        memory_hint: Box<[Option<usize>]>,
398        own_memory: bool,
399        stack_options: args::StackOptions,
400        validate: bool,
401    ) -> eyre::Result<Self> {
402        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
403            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
404            .collect::<eyre::Result<Box<_>>>()?;
405
406        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
407        let mut wasm_name_holder_iter = wasm_name_holder.iter();
408        let vfs_name = wasm_name_holder_iter
409            .next()
410            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;
411
412        let target_names = wasm_name_holder_iter.collect::<Box<_>>();
413
414        // log targeting info
415        for name in target_names.iter() {
416            log::info!("Targeting module: {name}");
417        }
418        log::info!("VFS module: {vfs_name}");
419
420        let target_names_with_self = target_names
421            .iter()
422            .cloned()
423            .chain(core::iter::once(vfs_name.clone()))
424            .collect::<Box<_>>();
425
426        let memory_hint = memory_hint
427            .into_iter()
428            .zip(target_names.iter().cloned())
429            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
430            .collect::<HashMap<_, _>>();
431        let stack_config = StackConfig::from_options(stack_options)?;
432
433        if stack_config.slots.contains_key("vfs")
434            || stack_config.slots.contains_key(vfs_name.as_ref())
435        {
436            eyre::bail!("--stack-slots is not valid for the VFS module");
437        }
438        if memory_type == TargetMemoryType::Single && !stack_config.slots.is_empty() {
439            eyre::bail!("--stack-slots is only valid with multi-memory targets");
440        }
441        if memory_type == TargetMemoryType::Single
442            && target_names
443                .iter()
444                .any(|name| stack_config.target_size(name.as_ref()).is_some())
445            && stack_config.vfs_size(vfs_name.as_ref()).is_none()
446        {
447            eyre::bail!("single-memory target stack isolation requires --stack-size vfs=SIZE");
448        }
449        for module in stack_config.sizes.keys().chain(stack_config.slots.keys()) {
450            if module != "vfs"
451                && module != vfs_name.as_ref()
452                && !target_names.iter().any(|name| name.as_ref() == module)
453            {
454                eyre::bail!("stack configuration names unknown module `{module}`");
455            }
456        }
457
458        Ok(Self {
459            ctx: GeneratorCtx {
460                vfs_name,
461                target_names,
462                target_names_with_self,
463                target_memory_type: memory_type,
464                unstable_print_debug,
465                dwarf,
466                threads,
467                adjust_abi,
468                keep_build_artifacts,
469
470                vfs_is_library: false,
471
472                wrap_unreachable_targets: std::collections::HashSet::new(),
473                main_void_synthesized_targets: None,
474                own_memory,
475                stack_config,
476                validate,
477            },
478            path,
479            targets,
480            vfs_build_opts,
481            target_vfs_build_opts,
482            toml_restorers: Some(toml_restorers),
483            memory_hint,
484            wasm_name_holder,
485        })
486    }
487
488    #[deprecated(
489        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
490    )]
491    /// Provides direct immutable access tracking the primary target structural path configuration.
492    pub const fn path(&self) -> &WasmPath {
493        &self.path
494    }
495
496    #[deprecated(
497        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
498    )]
499    /// Directly evaluates currently linked ancillary wasm dependencies.
500    pub const fn targets(&self) -> &Box<[WasmPath]> {
501        &self.targets
502    }
503
504    /// Securely uncovers operational variables tracking internal generational properties dynamically.
505    pub const fn ctx(&self) -> &GeneratorCtx {
506        &self.ctx
507    }
508
509    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
510    pub fn definitely(&mut self) -> eyre::Result<()> {
511        self.path
512            .definitely(self.ctx.threads, &self.vfs_build_opts)?;
513        for (i, target) in self.targets.iter_mut().enumerate() {
514            target.definitely(self.ctx.threads, &self.target_vfs_build_opts[i])?;
515        }
516        Ok(())
517    }
518
519    /// Primary operation chaining logic seamlessly running structural modifiers across all layered stages sequentially terminating out into WebAssembly components.
520    pub fn run_layers_to_component(
521        mut self,
522        out_dir: &Utf8PathBuf,
523        keep_build_artifacts: bool,
524    ) -> eyre::Result<ComponentRunner> {
525        self.definitely()?;
526
527        let toml_restorers = self
528            .toml_restorers
529            .take()
530            .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;
531
532        toml_restorers
533            .restore()
534            .wrap_err("Failed to restore toml files")?;
535
536        let dwarf = self.ctx.dwarf;
537        let validate = self.ctx.validate;
538
539        println!("Remove existing output directory...");
540        if std::fs::metadata(&out_dir).is_ok() {
541            std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
542        }
543        std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");
544
545        println!("Adjusting VFS Wasm...");
546        let skip_vfs_opt = self.vfs_build_opts.no_opt > 0 || self.vfs_build_opts.no_opt_all > 0;
547        (|path: &mut WasmPath| {
548            let wasm_bytes = std::fs::read(&path.path()?).unwrap();
549            let mut vfs_is_library = true;
550            let mut wrap_unreachable_targets = std::collections::HashSet::new();
551            for payload in wasmparser::Parser::new(0).parse_all(&wasm_bytes) {
552                if let Ok(wasmparser::Payload::StartSection { .. }) = payload {
553                    vfs_is_library = false;
554                }
555                if let Ok(wasmparser::Payload::ExportSection(s)) = payload {
556                    for e in s {
557                        if let Ok(e) = e {
558                            if e.name == "_start" {
559                                vfs_is_library = false;
560                            }
561                            for target in self.ctx.target_names.iter() {
562                                let marker = format!(
563                                    "__wasip1_virt_layer_{}_wrap_unreachable",
564                                    target.as_ref()
565                                );
566                                if e.name == marker {
567                                    wrap_unreachable_targets.insert(target.as_ref().to_string());
568                                }
569                            }
570                        }
571                    }
572                }
573            }
574            self.ctx.vfs_is_library = vfs_is_library;
575            self.ctx.wrap_unreachable_targets = wrap_unreachable_targets;
576            let pipeline_is_library = vfs_is_library;
577            let cloned_ctx = self.ctx.clone();
578
579            (|| {
580                // Detect VFS library mode: if the VFS module has no start section,
581                // it is a library and has no initialization entry point.
582                if pipeline_is_library {
583                    log::info!(
584                        "VFS module `{}` has no start section — treating as a library.",
585                        self.ctx.vfs_name
586                    );
587                }
588
589                Ok(())
590            })
591            .wrap_run(
592                path,
593                dwarf,
594                keep_build_artifacts,
595                {
596                    let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
597                    use crate::wasm_stream::passes::{
598                        abi_connect::{
599                            ConnectWasip1ABIPreVfsStreamPass, NonRecursiveWasiABIPreVfsStreamPass,
600                        },
601                        anonymous::AnonymousStreamPass,
602                        check::CheckUseWasiVirtLayerChecker,
603                        dummy_injector::DummyInjectorStreamPass,
604                        export_stack::ExportStackPreVfsStreamPass,
605                        patch_component::PatchComponentStreamPass,
606                        pre_vfs_memory_refuge::TemporaryRefugeMemoryStreamPass,
607                        starts_pre::StartsPreStreamPass,
608                    };
609
610                    let check_pass = crate::wasm_stream::pipeline::ParallelCheckStreamPass::new(
611                        vec![Box::new(CheckUseWasiVirtLayerChecker::new())],
612                    );
613                    pipeline.add_pass(Box::new(check_pass));
614                    pipeline.add_pass(Box::new(AnonymousStreamPass::new(cloned_ctx.clone())));
615                    pipeline.add_pass(Box::new(ConnectWasip1ABIPreVfsStreamPass::new()));
616                    pipeline.add_pass(Box::new(
617                    crate::wasm_stream::passes::threads_spawn::ThreadsSpawnPreVfsStreamPass::new(
618                        cloned_ctx.threads,
619                    ),
620                ));
621                    pipeline.add_pass(Box::new(NonRecursiveWasiABIPreVfsStreamPass::new()));
622                    pipeline.add_pass(Box::new(PatchComponentStreamPass::new()));
623
624                    let fn_in_starts =
625                        crate::wasm_stream::passes::fn_in_starts::FnInStarts::new::<String>(&[]);
626                    pipeline.add_pass(Box::new(StartsPreStreamPass::new(
627                        true,
628                        pipeline_is_library,
629                        fn_in_starts.flesh_vfs_start.clone(),
630                    )));
631                    pipeline.add_pass(Box::new(ExportStackPreVfsStreamPass::new(
632                        cloned_ctx
633                            .stack_config
634                            .vfs_size(cloned_ctx.vfs_name.as_ref()),
635                    )));
636                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![
637                        fn_in_starts.thread_patch.clone(),
638                        fn_in_starts.init_offset_global.clone(),
639                        fn_in_starts.save_target_memory.clone(),
640                        fn_in_starts.simple_debug_pre_init.clone(),
641                    ])));
642                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(None)));
643                    Some(pipeline)
644                },
645                cloned_ctx.validate,
646            )
647        })
648        .with_opt(
649            &mut self.path,
650            dwarf,
651            keep_build_artifacts,
652            skip_vfs_opt,
653            validate,
654        )?;
655
656        println!("Adjusting target Wasm...");
657
658        for (i, (target, target_name)) in self
659            .targets
660            .iter_mut()
661            .zip(self.ctx.target_names.clone())
662            .enumerate()
663        {
664            let skip_target_opt = self.vfs_build_opts.no_opt_all > 0
665                || self.target_vfs_build_opts[i].no_opt > 0
666                || self.target_vfs_build_opts[i].no_opt_all > 0;
667            let _cloned_ctx = self.ctx.clone();
668            let is_synthesized = std::sync::Arc::new(std::sync::Mutex::new(false));
669            (|path: &mut WasmPath| {
670                (|| {
671                    Ok(())
672                })
673                .wrap_run(path, dwarf, keep_build_artifacts, {
674                    let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
675                    use crate::wasm_stream::passes::{
676                        abi_connect::{
677                            ConnectWasip1ABIPreTargetStreamPass,
678                            ConnectWasip1ThreadsABIPreTargetStreamPass,
679                        },
680                        check::IsRustWasmChecker,
681                        dummy_injector::DummyInjectorStreamPass,
682                        pre_vfs_memory_refuge::TemporaryRefugeMemoryStreamPass,
683                        producer::ProducerStreamPass,
684                        starts_pre::StartsPreStreamPass,
685                        special_func::SpecialFuncPreTargetStreamPass,
686                        wrap_unreachable::WrapUnreachablePreTargetStreamPass,
687                        atomic_patch::AtomicPatchStreamPass,
688                        export_stack::ExportStackPreTargetStreamPass,
689                    };
690
691                    pipeline.add_pass(Box::new(ProducerStreamPass::new()));
692                    pipeline.add_pass(Box::new(SpecialFuncPreTargetStreamPass::new(
693                        target_name.to_string(),
694                        is_synthesized.clone(),
695                    )));
696
697                    let is_opted_in = _cloned_ctx.wrap_unreachable_targets.contains(&target_name.to_string());
698                    pipeline.add_pass(Box::new(WrapUnreachablePreTargetStreamPass::new(
699                        target_name.to_string(),
700                        is_opted_in,
701                    )));
702
703                    if _cloned_ctx.target_memory_type == TargetMemoryType::Single {
704                        pipeline.add_pass(Box::new(ExportStackPreTargetStreamPass::new(
705                            target_name.to_string(),
706                            crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
707                            i as u32,
708                            _cloned_ctx.stack_config.target_size(target_name.as_ref()),
709                        )));
710                    } else if let (Some(size), Some(slots)) = (
711                        _cloned_ctx.stack_config.target_size(target_name.as_ref()),
712                        _cloned_ctx.stack_config.slots.get(target_name.as_ref()).copied(),
713                    ) {
714                        if slots > 0 {
715                            let arena_pass = crate::wasm_stream::passes::export_stack_arena::ExportStackArenaStreamPass::new(size, slots);
716                            let arena_size = arena_pass.arena_offset() as u32;
717                            pipeline.add_pass(Box::new(arena_pass));
718                            pipeline.add_pass(Box::new(
719                                crate::wasm_stream::passes::export_stack_multi_memory_target::ExportStackMultiMemoryTargetStreamPass::new(
720                                    target_name.to_string(),
721                                    crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
722                                    arena_size,
723                                    size,
724                                ),
725                            ));
726                        }
727                    }
728
729                    pipeline.add_pass(Box::new(ConnectWasip1ABIPreTargetStreamPass::new(
730                        target_name.to_string(),
731                    )));
732                    pipeline.add_pass(Box::new(ConnectWasip1ThreadsABIPreTargetStreamPass::new(
733                        target_name.to_string(),
734                    )));
735                    pipeline.add_pass(Box::new(crate::wasm_stream::passes::threads_spawn::ThreadsSpawnPreTargetStreamPass::new(
736                        _cloned_ctx.threads,
737                        target_name.to_string(),
738                    )));
739                    pipeline.add_pass(Box::new(AtomicPatchStreamPass::new(
740                        _cloned_ctx.threads,
741                        i as u32,
742                    )));
743
744                    let check_pass = crate::wasm_stream::pipeline::ParallelCheckStreamPass::new(
745                        vec![Box::new(IsRustWasmChecker::new())],
746                    );
747                    pipeline.add_pass(Box::new(check_pass));
748
749                    let export_name = format!("__flesh_{}_start", target_name);
750                    pipeline.add_pass(Box::new(StartsPreStreamPass::new(
751                        false,
752                        false,
753                        export_name.clone(),
754                    )));
755                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![export_name])));
756                    let new_memory_name =
757                        crate::generator::UniqueName::Memory(&MemoryUniqueName::Memory(
758                            &target_name,
759                        ))
760                        .to_string();
761                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(Some(
762                        new_memory_name,
763                    ))));
764
765                    Some(pipeline)
766                }, _cloned_ctx.validate)
767            })
768            .with_opt(target, dwarf, keep_build_artifacts, skip_target_opt, validate)?;
769
770            if *is_synthesized.lock().unwrap() {
771                self.ctx
772                    .main_void_synthesized_targets
773                    .get_or_insert_default()
774                    .insert(target_name.to_string());
775            }
776        }
777
778        let skip_all_opt = self.vfs_build_opts.no_opt_all > 0
779            || self
780                .target_vfs_build_opts
781                .iter()
782                .any(|opts| opts.no_opt_all > 0);
783
784        println!("Combining Wasm modules...");
785
786        let output = format!("{out_dir}/merged.wasm");
787        let mut defined_funcs_counts = Vec::new();
788        (|path: &mut WasmPath| {
789            let old_path = path.path()?.clone();
790            defined_funcs_counts.push(count_defined_funcs(&old_path)?);
791            for target in self.targets.iter() {
792                defined_funcs_counts.push(count_defined_funcs(target.path()?)?);
793            }
794            merge(
795                &old_path,
796                &self
797                    .targets
798                    .iter()
799                    .map(|t| t.path())
800                    .collect::<eyre::Result<Vec<_>>>()?,
801                &output,
802                self.ctx.threads,
803                dwarf,
804            )
805            .wrap_err("Failed to combine Wasm modules")?;
806
807            if !keep_build_artifacts {
808                std::fs::remove_file(&old_path)
809                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
810                for target in self.targets.iter() {
811                    if let Ok(target_path) = target.path() {
812                        if !target.is_original(target_path) {
813                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
814                                log::warn!(
815                                    "Failed to remove intermediate target file {target_path}: {e}"
816                                );
817                            });
818                        }
819                    }
820                }
821            }
822
823            path.set_path(output.into())
824        })
825        .with_opt(
826            &mut self.path,
827            dwarf,
828            keep_build_artifacts,
829            skip_all_opt,
830            validate,
831        )?;
832
833        println!("Adjusting Merged Wasm (streaming pipeline)...");
834
835        (|path: &mut WasmPath| {
836            let old_path = path.path()?.clone();
837            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
838
839            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
840            let target_names: Vec<String> = self.ctx.target_names.iter().map(|n| n.as_ref().to_string()).collect();
841
842            let vfs_name = self.ctx.vfs_name.as_ref().to_string();
843            pipeline.add_pass(Box::new(
844                crate::wasm_stream::passes::post_combine::PostCombineStreamPass::new(
845                    vfs_name,
846                    target_names.clone(),
847                    defined_funcs_counts.clone(),
848                    self.ctx.threads,
849                )
850            ));
851
852            if self.ctx.target_memory_type == TargetMemoryType::Single {
853                println!("Generating single memory Merged Wasm (streaming lowering)...");
854                pipeline.add_pass(Box::new(
855                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), true)
856                ));
857                pipeline.add_pass(Box::new(
858                    crate::wasm_stream::passes::shared_global::SharedGlobalStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names)
859                ));
860            } else if self.ctx.own_memory {
861                println!("Adjusting own memory for Multi Memory Merged Wasm (streaming lowering)...");
862                pipeline.add_pass(Box::new(
863                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), false)
864                ));
865            }
866
867            let output_wasm = pipeline
868                .run(&input_wasm)
869                .wrap_err("Failed to run StreamPipeline")?;
870
871            let new_path = old_path.with_extension("lowered.wasm");
872            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write lowered Wasm file")?;
873
874            if self.ctx.validate {
875                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
876                    .validate_all(&output_wasm)
877                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
878            }
879
880            if !keep_build_artifacts {
881                std::fs::remove_file(&old_path).wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
882            }
883
884            path.set_path(new_path)?;
885            Ok(())
886        }).with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt, validate)?;
887
888        println!("Translating Wasm to Component...");
889        let old_path = self.path.path()?.clone();
890        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
891            .wrap_err("Failed to translate Wasm to Component")?;
892        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
893        let component_bytes = std::fs::read(&component)?;
894        let component_bytes_with_ctx =
895            crate::wasm_stream::passes::component_ctx::append_component_ctx(
896                &component_bytes,
897                &self.ctx,
898            )?;
899        std::fs::write(&new_component, &component_bytes_with_ctx)?;
900
901        if self.ctx.validate {
902            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
903                .validate_all(&component_bytes_with_ctx)
904                .wrap_err_with(|| format!("Wasm validation failed for {}", new_component))?;
905        }
906
907        if !keep_build_artifacts {
908            std::fs::remove_file(&component)
909                .wrap_err_with(|| format!("Failed to remove existing file {component}"))?;
910            std::fs::remove_file(&old_path)
911                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
912        }
913
914        self.path.set_path(Utf8PathBuf::from(new_component))?;
915
916        Ok(ComponentRunner {
917            ctx: None,
918            path: self.path,
919            wasm_name_holder: None,
920        })
921    }
922}
923
924impl ComponentRunner {
925    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
926    pub fn new(path: WasmPath) -> Self {
927        Self {
928            ctx: None,
929            path,
930            wasm_name_holder: None,
931        }
932    }
933
934    /// return is_threads, core_name, mem_size
935    pub fn component_to_files(
936        &mut self,
937        parsed_args: &(impl args::PostBuildContext + ?Sized),
938        dwarf: bool,
939        only_core: bool,
940    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
941        let out_dir = parsed_args.out_dir();
942
943        let name = self.path.name()?;
944
945        println!("Translating Component to JS...");
946        let component_bytes = std::fs::read(&self.path.path()?)?;
947        self.ctx =
948            Some(crate::wasm_stream::passes::component_ctx::read_component_ctx(&component_bytes)?);
949
950        let core_wasm_path = (|path: &mut WasmPath| {
951            let old_path = path.path()?.clone();
952            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
953            let transpiled = parsed_args
954                .transpile_to_js(&binary, &name)
955                .wrap_err("Failed to transpile to JS")?;
956
957            let mut core_wasm = None;
958            for (name, data) in transpiled.files.iter() {
959                let name = camino::Utf8PathBuf::from(name);
960                let file_name = out_dir.join(&name);
961                if std::fs::metadata(&file_name).is_ok() {
962                    std::fs::remove_file(&file_name).wrap_err_with(|| {
963                        eyre::eyre!("Failed to remove existing file: {file_name}")
964                    })?;
965                }
966                if name.as_str().ends_with(".core.wasm") {
967                    let file_name = camino::Utf8PathBuf::from(file_name);
968                    std::fs::write(&file_name, &data).wrap_err_with(|| {
969                        eyre::eyre!("Failed to write core wasm file: {file_name}")
970                    })?;
971                    core_wasm = Some(file_name);
972                } else {
973                    if let Some(parent) = name.parent() {
974                        if !parent.as_str().is_empty() {
975                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
976                                eyre::eyre!("Failed to get parent directory: {}", name)
977                            })?;
978                            let joined_dir = out_dir.join(dir);
979                            if !std::fs::metadata(&joined_dir).is_ok() {
980                                if dir.as_str() != "interfaces" {
981                                    log::warn!("Creating directory: {joined_dir}");
982                                }
983                                if only_core {
984                                    continue;
985                                }
986                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
987                                    eyre::eyre!("Failed to create directory: {joined_dir}")
988                                })?;
989                            }
990                        }
991                    }
992                    if only_core {
993                        continue;
994                    }
995                    std::fs::write(&file_name, &data).wrap_err_with(|| {
996                        eyre::eyre!("Failed to write transpiled file: {file_name}")
997                    })?;
998                }
999            }
1000
1001            let core_wasm = core_wasm
1002                .as_ref()
1003                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1004
1005            if !parsed_args.keep_build_artifacts() {
1006                std::fs::remove_file(&old_path)
1007                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1008            }
1009            path.set_path(core_wasm.clone())?;
1010
1011            Ok(core_wasm.clone())
1012        })
1013        .with_opt(
1014            &mut self.path,
1015            dwarf,
1016            parsed_args.keep_build_artifacts(),
1017            parsed_args.dev(),
1018            parsed_args.validate(),
1019        )?;
1020
1021        let mem_sizes = {
1022            let wasm_bytes =
1023                std::fs::read(&self.path.path()?).wrap_err("Failed to read core wasm")?;
1024            crate::wasm_stream::passes::extract_mem_sizes::extract_memory_sizes(&wasm_bytes)?
1025        };
1026
1027        println!("Adjusting component Merged Wasm...");
1028        (|path: &mut WasmPath| {
1029            let old_path = path.path()?.clone();
1030            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
1031
1032            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
1033
1034            pipeline.add_pass(Box::new(
1035                crate::wasm_stream::passes::memory_post_components::PostComponentsMemoryFixStreamPass::new(self.ctx.as_ref().unwrap().threads.unwrap_or(false))
1036            ));
1037
1038            let output_wasm = pipeline
1039                .run(&input_wasm)
1040                .wrap_err("Failed to run StreamPipeline")?;
1041            let new_path = old_path.with_extension("post-comp-stream.wasm");
1042            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write Wasm file")?;
1043
1044            if parsed_args.validate() {
1045                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
1046                    .validate_all(&output_wasm)
1047                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
1048            }
1049
1050            if !parsed_args.keep_build_artifacts() {
1051                std::fs::remove_file(&old_path).unwrap_or_default();
1052            }
1053            path.set_path(new_path)?;
1054
1055            Ok(())
1056        })
1057        .with_opt(
1058            &mut self.path,
1059            dwarf,
1060            parsed_args.keep_build_artifacts(),
1061            parsed_args.dev(),
1062            parsed_args.validate(),
1063        )?;
1064
1065        let _dwarf = {
1066            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1067            if dwarf && !new_dwarf {
1068                log::warn!(
1069                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1070                );
1071            }
1072            new_dwarf
1073        };
1074
1075        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1076            eyre::eyre!(
1077                "Failed to rename final wasm from {} to {}",
1078                self.path.path().unwrap(),
1079                core_wasm_path
1080            )
1081        })?;
1082
1083        Ok((
1084            self.ctx.as_ref().unwrap().threads.unwrap_or(false),
1085            core_wasm_path
1086                .get_file_main_name()
1087                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1088            mem_sizes,
1089        ))
1090    }
1091}
1092
1093/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1094#[derive(Debug, Clone, Hash)]
1095pub enum WasmPath {
1096    /// Indicates the target still needs compilation through standard cargo dependencies.
1097    Maybe {
1098        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1099        manifest_path: Utf8PathBuf,
1100        /// Specified internal crate package identifier.
1101        package: String,
1102    },
1103    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1104    Definitely(Utf8PathBuf),
1105    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1106    Component(Utf8PathBuf),
1107    /// A user-provided raw WebAssembly binary file that should never be deleted.
1108    /// The inner path tracks the original file location.
1109    Original {
1110        /// The current working path (may change as transformations produce new files).
1111        current: Utf8PathBuf,
1112        /// The original user-provided path that must be preserved.
1113        original: Utf8PathBuf,
1114    },
1115}
1116
1117impl FromStr for WasmPath {
1118    type Err = eyre::Error;
1119
1120    /// manifest_path :: package
1121    fn from_str(s: &str) -> Result<Self, Self::Err> {
1122        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1123            let split = s.split("::").collect::<Vec<_>>();
1124            if split.len() == 2 {
1125                let manifest_path = Utf8PathBuf::from_str(split[0])
1126                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1127                let package = split[1].to_string();
1128                return Ok(Some(WasmPath::Maybe {
1129                    manifest_path,
1130                    package,
1131                }));
1132            }
1133            Ok(None)
1134        }
1135
1136        if let Some(wasm_path) =
1137            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1138        {
1139            return Ok(wasm_path);
1140        }
1141
1142        if s.ends_with(".wasm") {
1143            let path = Utf8PathBuf::from_str(s)
1144                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1145            return WasmPath::with_wasm(path);
1146        }
1147
1148        if s.ends_with("Cargo.toml") {
1149            let manifest_path = Utf8PathBuf::from_str(s)
1150                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1151            return WasmPath::with_maybe_only_manifest(manifest_path);
1152        }
1153
1154        WasmPath::with_maybe_only_package(s.to_string())
1155            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1156    }
1157}
1158
1159impl WasmPath {
1160    /// Computes the unique short name used during module linking and identification.
1161    pub fn name(&self) -> eyre::Result<CompactString> {
1162        match self {
1163            WasmPath::Maybe { package, .. } => {
1164                // Normalize package name by replacing hyphens with underscores
1165                // This is necessary because Rust package names can have hyphens (e.g., "test-package")
1166                // but they are converted to underscores in module identifiers (e.g., "test_package")
1167                let normalized = package.replace('-', "_");
1168                Ok(normalized.to_compact_string())
1169            }
1170            WasmPath::Definitely(path)
1171            | WasmPath::Component(path)
1172            | WasmPath::Original { current: path, .. } => path
1173                .get_file_main_name()
1174                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1175        }
1176    }
1177
1178    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1179    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1180        match self {
1181            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1182            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1183        }
1184    }
1185
1186    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1187    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1188        match self {
1189            WasmPath::Maybe { manifest_path, .. } => {
1190                let cargo_metadata = {
1191                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1192                    metadata_command.manifest_path(&manifest_path);
1193                    metadata_command.exec().unwrap()
1194                };
1195                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1196            }
1197            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1198        }
1199    }
1200
1201    /// Statically assigns an unresolved target using defined package specifications.
1202    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1203        Self::Maybe {
1204            manifest_path,
1205            package,
1206        }
1207    }
1208
1209    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1210    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1211        let cargo_metadata = {
1212            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1213            metadata_command.manifest_path(&manifest_path);
1214            metadata_command.exec().unwrap()
1215        };
1216        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1217
1218        Ok(Self::Maybe {
1219            manifest_path,
1220            package: building_crate.name.to_string(),
1221        })
1222    }
1223
1224    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1225    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1226        let cargo_metadata = {
1227            let metadata_command = cargo_metadata::MetadataCommand::new();
1228            metadata_command.exec().unwrap()
1229        };
1230        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1231
1232        Ok(Self::Maybe {
1233            manifest_path: building_crate.manifest_path,
1234            package: building_crate.name.to_string(),
1235        })
1236    }
1237
1238    /// Loads an unresolved dependency using current environment cargo bounds natively.
1239    pub fn with_maybe_none() -> eyre::Result<Self> {
1240        let cargo_metadata = {
1241            let metadata_command = cargo_metadata::MetadataCommand::new();
1242            metadata_command.exec().unwrap()
1243        };
1244        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1245
1246        Ok(Self::Maybe {
1247            manifest_path: building_crate.manifest_path,
1248            package: building_crate.name.to_string(),
1249        })
1250    }
1251
1252    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1253    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1254    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1255        if path.extension() != Some("wasm") {
1256            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1257        }
1258        if !fs::metadata(&path).is_ok() {
1259            // Assume it's an original Wasm file even if it doesn't exist yet
1260            return Ok(Self::Original {
1261                current: path.clone(),
1262                original: path,
1263            });
1264        }
1265
1266        let mut file =
1267            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1268        let mut magic = [0u8; 8];
1269        file.read_exact(&mut magic)
1270            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1271        if !magic.starts_with(b"\0asm") {
1272            eyre::bail!("Wasm file does not have valid magic number: {path}");
1273        }
1274        let version = &magic[4..8];
1275        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1276        if version == [0x0D, 0x00, 0x01, 0x00] {
1277            return Ok(Self::Component(path));
1278        }
1279        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1280        if version != [0x01, 0x00, 0x00, 0x00] {
1281            eyre::bail!("Wasm file does not have valid version: {path}");
1282        }
1283
1284        Ok(Self::Original {
1285            current: path.clone(),
1286            original: path,
1287        })
1288    }
1289
1290    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1291    pub fn definitely(
1292        &mut self,
1293        threads: bool,
1294        vfs_build_opts: &args::VfsBuildOptions,
1295    ) -> eyre::Result<()> {
1296        if let WasmPath::Maybe {
1297            manifest_path,
1298            package,
1299        } = self
1300        {
1301            let cargo_metadata = {
1302                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1303                metadata_command.manifest_path(&manifest_path);
1304                metadata_command.exec().unwrap()
1305            };
1306            let building_crate =
1307                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1308            let vfs_name = building_crate.name.to_string();
1309
1310            let path = compile::build_vfs(
1311                Some(&manifest_path.to_string()),
1312                &building_crate,
1313                threads,
1314                vfs_build_opts,
1315            )
1316            .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1317            *self = WasmPath::Definitely(path);
1318        }
1319
1320        // Original variant is already resolved, no action needed.
1321
1322        Ok(())
1323    }
1324
1325    /// Returns the path to the WASM module.
1326    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1327        match self {
1328            WasmPath::Maybe { .. } => {
1329                eyre::bail!("WasmPath is not definitely set: {self:?}")
1330            }
1331            WasmPath::Definitely(p)
1332            | WasmPath::Component(p)
1333            | WasmPath::Original { current: p, .. } => Ok(p),
1334        }
1335    }
1336
1337    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1338    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1339        matches!(self, WasmPath::Original { original, .. } if original == path)
1340    }
1341
1342    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1343    /// For `Original` variants, preserves the original path tracking.
1344    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1345        match self {
1346            WasmPath::Maybe { .. } => {
1347                eyre::bail!("WasmPath is not definitely set: {path}")
1348            }
1349            WasmPath::Original { current, .. } => {
1350                // Keep the original path, only update current
1351                *current = path;
1352            }
1353            _ => {
1354                *self = WasmPath::Definitely(path);
1355            }
1356        }
1357        Ok(())
1358    }
1359}
1360
1361/// Combines prepared VFS and target modules into one core Wasm module.
1362fn count_defined_funcs(wasm_path: &camino::Utf8PathBuf) -> eyre::Result<u32> {
1363    let wasm = std::fs::read(wasm_path)?;
1364    for payload in wasmparser::Parser::new(0).parse_all(&wasm) {
1365        let payload = payload.map_err(|e| eyre::eyre!("Parse error: {}", e))?;
1366        if let wasmparser::Payload::FunctionSection(s) = payload {
1367            return Ok(s.count());
1368        }
1369    }
1370    Ok(0)
1371}
1372
1373pub fn merge(
1374    vfs: &Utf8PathBuf,
1375    wasm: &[impl AsRef<std::path::Path>],
1376    output: impl AsRef<std::path::Path>,
1377    _threads: bool,
1378    dwarf: bool,
1379) -> eyre::Result<()> {
1380    let mut inputs = Vec::with_capacity(wasm.len() + 1);
1381    inputs.push(crate::wasm_stream::merge::MergeInput {
1382        alias: UniqueName::WASIP1_ABI_MODULE.to_string(),
1383        path: vfs.as_std_path(),
1384    });
1385    for wasm in wasm {
1386        inputs.push(crate::wasm_stream::merge::MergeInput {
1387            alias: format!(
1388                "wasip1_vfs_{}",
1389                wasm.as_ref()
1390                    .get_file_main_name()
1391                    .ok_or_else(|| eyre::eyre!("Failed to get Wasm module name"))?
1392            ),
1393            path: wasm.as_ref(),
1394        });
1395    }
1396    crate::wasm_stream::merge::merge_modules(&inputs, output, dwarf)
1397}
1398
1399macro_rules! _add_generators_by_type {
1400    ($runner:expr, $($ty:ty),* $(,)?) => {
1401        $(
1402            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1403                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1404            }
1405            $runner.add_generator(<$ty>::default());
1406        )*
1407    };
1408}