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