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(StartsPreStreamPass::new(
641                        true,
642                        pipeline_is_library,
643                        fn_in_starts.flesh_vfs_start.clone(),
644                    )));
645                    pipeline.add_pass(Box::new(ExportStackPreVfsStreamPass::new(
646                        cloned_ctx
647                            .stack_config
648                            .vfs_size(cloned_ctx.vfs_name.as_ref()),
649                    )));
650                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![
651                        fn_in_starts.thread_patch.clone(),
652                        fn_in_starts.init_offset_global.clone(),
653                        fn_in_starts.save_target_memory.clone(),
654                        fn_in_starts.simple_debug_pre_init.clone(),
655                    ])));
656                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(None)));
657                    Some(pipeline)
658                },
659                cloned_ctx.validate,
660            )
661        })
662        .with_opt(
663            &mut self.path,
664            dwarf,
665            keep_build_artifacts,
666            skip_vfs_opt,
667            validate,
668        )?;
669
670        println!("Adjusting target Wasm...");
671
672        for (i, (target, target_name)) in self
673            .targets
674            .iter_mut()
675            .zip(self.ctx.target_names.clone())
676            .enumerate()
677        {
678            let skip_target_opt = self.vfs_build_opts.no_opt_all > 0
679                || self.target_vfs_build_opts[i].no_opt > 0
680                || self.target_vfs_build_opts[i].no_opt_all > 0;
681            let _cloned_ctx = self.ctx.clone();
682            let is_synthesized = std::sync::Arc::new(std::sync::Mutex::new(false));
683            (|path: &mut WasmPath| {
684                (|| {
685                    Ok(())
686                })
687                .wrap_run(path, dwarf, keep_build_artifacts, {
688                    let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
689                    use crate::wasm_stream::passes::{
690                        abi_connect::{
691                            ConnectWasip1ABIPreTargetStreamPass,
692                            ConnectWasip1ThreadsABIPreTargetStreamPass,
693                        },
694                        check::IsRustWasmChecker,
695                        dummy_injector::DummyInjectorStreamPass,
696                        pre_vfs_memory_refuge::TemporaryRefugeMemoryStreamPass,
697                        producer::ProducerStreamPass,
698                        starts_pre::StartsPreStreamPass,
699                        special_func::SpecialFuncPreTargetStreamPass,
700                        wrap_unreachable::WrapUnreachablePreTargetStreamPass,
701                        atomic_patch::AtomicPatchStreamPass,
702                        export_stack::ExportStackPreTargetStreamPass,
703                    };
704
705                    pipeline.add_pass(Box::new(ProducerStreamPass::new()));
706                    pipeline.add_pass(Box::new(SpecialFuncPreTargetStreamPass::new(
707                        target_name.to_string(),
708                        is_synthesized.clone(),
709                    )));
710
711                    let is_opted_in = _cloned_ctx.wrap_unreachable_targets.contains(&target_name.to_string());
712                    pipeline.add_pass(Box::new(WrapUnreachablePreTargetStreamPass::new(
713                        target_name.to_string(),
714                        is_opted_in,
715                    )));
716                    pipeline.add_pass(Box::new(
717                        crate::wasm_stream::passes::deadlock_thread_id::DeadlockThreadIdPreTargetStreamPass::for_target(
718                            _cloned_ctx.detect_deadlock,
719                            target_name.to_string(),
720                        ),
721                    ));
722
723                    if _cloned_ctx.target_memory_type == TargetMemoryType::Single {
724                        pipeline.add_pass(Box::new(ExportStackPreTargetStreamPass::new(
725                            target_name.to_string(),
726                            crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
727                            i as u32,
728                            _cloned_ctx.stack_config.target_size(target_name.as_ref()),
729                        )));
730                    } else if let (Some(size), Some(slots)) = (
731                        _cloned_ctx.stack_config.target_size(target_name.as_ref()),
732                        _cloned_ctx.stack_config.slots.get(target_name.as_ref()).copied(),
733                    ) {
734                        if slots > 0 {
735                            let arena_pass = crate::wasm_stream::passes::export_stack_arena::ExportStackArenaStreamPass::new(size, slots);
736                            let arena_size = arena_pass.arena_offset() as u32;
737                            pipeline.add_pass(Box::new(arena_pass));
738                            pipeline.add_pass(Box::new(
739                                crate::wasm_stream::passes::export_stack_multi_memory_target::ExportStackMultiMemoryTargetStreamPass::new(
740                                    target_name.to_string(),
741                                    crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
742                                    arena_size,
743                                    size,
744                                ),
745                            ));
746                        }
747                    }
748
749                    pipeline.add_pass(Box::new(ConnectWasip1ABIPreTargetStreamPass::new(
750                        target_name.to_string(),
751                    )));
752                    pipeline.add_pass(Box::new(ConnectWasip1ThreadsABIPreTargetStreamPass::new(
753                        target_name.to_string(),
754                    )));
755                    pipeline.add_pass(Box::new(crate::wasm_stream::passes::threads_spawn::ThreadsSpawnPreTargetStreamPass::new(
756                        _cloned_ctx.threads,
757                        target_name.to_string(),
758                    )));
759                    pipeline.add_pass(Box::new(AtomicPatchStreamPass::new(
760                        _cloned_ctx.threads,
761                        i as u32,
762                        _cloned_ctx.detect_deadlock,
763                    )));
764
765                    let check_pass = crate::wasm_stream::pipeline::ParallelCheckStreamPass::new(
766                        vec![Box::new(IsRustWasmChecker::new())],
767                    );
768                    pipeline.add_pass(Box::new(check_pass));
769
770                    let export_name = format!("__flesh_{}_start", target_name);
771                    let thread_start_export_name =
772                        format!("__wasip1_vfs_{}__thread_start", target_name);
773                    pipeline.add_pass(Box::new(
774                        StartsPreStreamPass::new(false, false, export_name.clone())
775                            .with_thread_start_export_name(thread_start_export_name),
776                    ));
777                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![export_name])));
778                    let new_memory_name =
779                        crate::generator::UniqueName::Memory(&MemoryUniqueName::Memory(
780                            &target_name,
781                        ))
782                        .to_string();
783                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(Some(
784                        new_memory_name,
785                    ))));
786
787                    Some(pipeline)
788                }, _cloned_ctx.validate)
789            })
790            .with_opt(target, dwarf, keep_build_artifacts, skip_target_opt, validate)?;
791
792            if *is_synthesized.lock().unwrap() {
793                self.ctx
794                    .main_void_synthesized_targets
795                    .get_or_insert_default()
796                    .insert(target_name.to_string());
797            }
798        }
799
800        let skip_all_opt = self.vfs_build_opts.no_opt_all > 0
801            || self
802                .target_vfs_build_opts
803                .iter()
804                .any(|opts| opts.no_opt_all > 0);
805
806        println!("Combining Wasm modules...");
807
808        let output = format!("{out_dir}/merged.wasm");
809        let mut defined_funcs_counts = Vec::new();
810        (|path: &mut WasmPath| {
811            let old_path = path.path()?.clone();
812            defined_funcs_counts.push(count_defined_funcs(&old_path)?);
813            for target in self.targets.iter() {
814                defined_funcs_counts.push(count_defined_funcs(target.path()?)?);
815            }
816            merge(
817                &old_path,
818                &self
819                    .targets
820                    .iter()
821                    .map(|t| t.path())
822                    .collect::<eyre::Result<Vec<_>>>()?,
823                &output,
824                self.ctx.threads,
825                dwarf,
826            )
827            .wrap_err("Failed to combine Wasm modules")?;
828
829            if !keep_build_artifacts {
830                std::fs::remove_file(&old_path)
831                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
832                for target in self.targets.iter() {
833                    if let Ok(target_path) = target.path() {
834                        if !target.is_original(target_path) {
835                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
836                                log::warn!(
837                                    "Failed to remove intermediate target file {target_path}: {e}"
838                                );
839                            });
840                        }
841                    }
842                }
843            }
844
845            path.set_path(output.into())
846        })
847        .with_opt(
848            &mut self.path,
849            dwarf,
850            keep_build_artifacts,
851            skip_all_opt,
852            validate,
853        )?;
854
855        println!("Adjusting Merged Wasm (streaming pipeline)...");
856
857        (|path: &mut WasmPath| {
858            let old_path = path.path()?.clone();
859            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
860
861            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
862            let target_names: Vec<String> = self.ctx.target_names.iter().map(|n| n.as_ref().to_string()).collect();
863
864            let vfs_name = self.ctx.vfs_name.as_ref().to_string();
865            pipeline.add_pass(Box::new(
866                crate::wasm_stream::passes::post_combine::PostCombineStreamPass::new(
867                    vfs_name,
868                    target_names.clone(),
869                    defined_funcs_counts.clone(),
870                    self.ctx.threads,
871                )
872            ));
873
874            if self.ctx.target_memory_type == TargetMemoryType::Single {
875                println!("Generating single memory Merged Wasm (streaming lowering)...");
876                pipeline.add_pass(Box::new(
877                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), true)
878                ));
879                pipeline.add_pass(Box::new(
880                    crate::wasm_stream::passes::shared_global::SharedGlobalStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names)
881                ));
882            } else if self.ctx.own_memory {
883                println!("Adjusting own memory for Multi Memory Merged Wasm (streaming lowering)...");
884                pipeline.add_pass(Box::new(
885                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), false)
886                ));
887            }
888
889            let output_wasm = pipeline
890                .run(&input_wasm)
891                .wrap_err("Failed to run StreamPipeline")?;
892
893            let new_path = old_path.with_extension("lowered.wasm");
894            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write lowered Wasm file")?;
895
896            if self.ctx.validate {
897                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
898                    .validate_all(&output_wasm)
899                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
900            }
901
902            if !keep_build_artifacts {
903                std::fs::remove_file(&old_path).wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
904            }
905
906            path.set_path(new_path)?;
907            Ok(())
908        }).with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt, validate)?;
909
910        println!("Translating Wasm to Component...");
911        let old_path = self.path.path()?.clone();
912        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
913            .wrap_err("Failed to translate Wasm to Component")?;
914        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
915        let component_bytes = std::fs::read(&component)?;
916        let component_bytes_with_ctx =
917            crate::wasm_stream::passes::component_ctx::append_component_ctx(
918                &component_bytes,
919                &self.ctx,
920            )?;
921        std::fs::write(&new_component, &component_bytes_with_ctx)?;
922
923        if self.ctx.validate {
924            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
925                .validate_all(&component_bytes_with_ctx)
926                .wrap_err_with(|| format!("Wasm validation failed for {}", new_component))?;
927        }
928
929        if !keep_build_artifacts {
930            std::fs::remove_file(&component)
931                .wrap_err_with(|| format!("Failed to remove existing file {component}"))?;
932            std::fs::remove_file(&old_path)
933                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
934        }
935
936        self.path.set_path(Utf8PathBuf::from(new_component))?;
937
938        Ok(ComponentRunner {
939            ctx: None,
940            path: self.path,
941            wasm_name_holder: None,
942        })
943    }
944}
945
946impl ComponentRunner {
947    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
948    pub fn new(path: WasmPath) -> Self {
949        Self {
950            ctx: None,
951            path,
952            wasm_name_holder: None,
953        }
954    }
955
956    /// return is_threads, core_name, mem_size
957    pub fn component_to_files(
958        &mut self,
959        parsed_args: &(impl args::PostBuildContext + ?Sized),
960        dwarf: bool,
961        only_core: bool,
962    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
963        let out_dir = parsed_args.out_dir();
964
965        let name = self.path.name()?;
966
967        println!("Translating Component to JS...");
968        let component_bytes = std::fs::read(&self.path.path()?)?;
969        self.ctx =
970            Some(crate::wasm_stream::passes::component_ctx::read_component_ctx(&component_bytes)?);
971
972        let core_wasm_path = (|path: &mut WasmPath| {
973            let old_path = path.path()?.clone();
974            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
975            let transpiled = parsed_args
976                .transpile_to_js(&binary, &name)
977                .wrap_err("Failed to transpile to JS")?;
978
979            let mut core_wasm = None;
980            for (name, data) in transpiled.files.iter() {
981                let name = camino::Utf8PathBuf::from(name);
982                let file_name = out_dir.join(&name);
983                if std::fs::metadata(&file_name).is_ok() {
984                    std::fs::remove_file(&file_name).wrap_err_with(|| {
985                        eyre::eyre!("Failed to remove existing file: {file_name}")
986                    })?;
987                }
988                if name.as_str().ends_with(".core.wasm") {
989                    let file_name = camino::Utf8PathBuf::from(file_name);
990                    std::fs::write(&file_name, &data).wrap_err_with(|| {
991                        eyre::eyre!("Failed to write core wasm file: {file_name}")
992                    })?;
993                    core_wasm = Some(file_name);
994                } else {
995                    if let Some(parent) = name.parent() {
996                        if !parent.as_str().is_empty() {
997                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
998                                eyre::eyre!("Failed to get parent directory: {}", name)
999                            })?;
1000                            let joined_dir = out_dir.join(dir);
1001                            if !std::fs::metadata(&joined_dir).is_ok() {
1002                                if dir.as_str() != "interfaces" {
1003                                    log::warn!("Creating directory: {joined_dir}");
1004                                }
1005                                if only_core {
1006                                    continue;
1007                                }
1008                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1009                                    eyre::eyre!("Failed to create directory: {joined_dir}")
1010                                })?;
1011                            }
1012                        }
1013                    }
1014                    if only_core {
1015                        continue;
1016                    }
1017                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1018                        eyre::eyre!("Failed to write transpiled file: {file_name}")
1019                    })?;
1020                }
1021            }
1022
1023            let core_wasm = core_wasm
1024                .as_ref()
1025                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1026
1027            if !parsed_args.keep_build_artifacts() {
1028                std::fs::remove_file(&old_path)
1029                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1030            }
1031            path.set_path(core_wasm.clone())?;
1032
1033            Ok(core_wasm.clone())
1034        })
1035        .with_opt(
1036            &mut self.path,
1037            dwarf,
1038            parsed_args.keep_build_artifacts(),
1039            parsed_args.dev(),
1040            parsed_args.validate(),
1041        )?;
1042
1043        let mem_sizes = {
1044            let wasm_bytes =
1045                std::fs::read(&self.path.path()?).wrap_err("Failed to read core wasm")?;
1046            crate::wasm_stream::passes::extract_mem_sizes::extract_memory_sizes(&wasm_bytes)?
1047        };
1048
1049        println!("Adjusting component Merged Wasm...");
1050        (|path: &mut WasmPath| {
1051            let old_path = path.path()?.clone();
1052            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
1053
1054            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
1055
1056            pipeline.add_pass(Box::new(
1057                crate::wasm_stream::passes::memory_post_components::PostComponentsMemoryFixStreamPass::new(self.ctx.as_ref().unwrap().threads.unwrap_or(false))
1058            ));
1059
1060            let output_wasm = pipeline
1061                .run(&input_wasm)
1062                .wrap_err("Failed to run StreamPipeline")?;
1063            let new_path = old_path.with_extension("post-comp-stream.wasm");
1064            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write Wasm file")?;
1065
1066            if parsed_args.validate() {
1067                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
1068                    .validate_all(&output_wasm)
1069                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
1070            }
1071
1072            if !parsed_args.keep_build_artifacts() {
1073                std::fs::remove_file(&old_path).unwrap_or_default();
1074            }
1075            path.set_path(new_path)?;
1076
1077            Ok(())
1078        })
1079        .with_opt(
1080            &mut self.path,
1081            dwarf,
1082            parsed_args.keep_build_artifacts(),
1083            parsed_args.dev(),
1084            parsed_args.validate(),
1085        )?;
1086
1087        let _dwarf = {
1088            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1089            if dwarf && !new_dwarf {
1090                log::warn!(
1091                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1092                );
1093            }
1094            new_dwarf
1095        };
1096
1097        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1098            eyre::eyre!(
1099                "Failed to rename final wasm from {} to {}",
1100                self.path.path().unwrap(),
1101                core_wasm_path
1102            )
1103        })?;
1104
1105        Ok((
1106            self.ctx.as_ref().unwrap().threads.unwrap_or(false),
1107            core_wasm_path
1108                .get_file_main_name()
1109                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1110            mem_sizes,
1111        ))
1112    }
1113}
1114
1115/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1116#[derive(Debug, Clone, Hash)]
1117pub enum WasmPath {
1118    /// Indicates the target still needs compilation through standard cargo dependencies.
1119    Maybe {
1120        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1121        manifest_path: Utf8PathBuf,
1122        /// Specified internal crate package identifier.
1123        package: String,
1124    },
1125    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1126    Definitely(Utf8PathBuf),
1127    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1128    Component(Utf8PathBuf),
1129    /// A user-provided raw WebAssembly binary file that should never be deleted.
1130    /// The inner path tracks the original file location.
1131    Original {
1132        /// The current working path (may change as transformations produce new files).
1133        current: Utf8PathBuf,
1134        /// The original user-provided path that must be preserved.
1135        original: Utf8PathBuf,
1136    },
1137}
1138
1139impl FromStr for WasmPath {
1140    type Err = eyre::Error;
1141
1142    /// manifest_path :: package
1143    fn from_str(s: &str) -> Result<Self, Self::Err> {
1144        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1145            let split = s.split("::").collect::<Vec<_>>();
1146            if split.len() == 2 {
1147                let manifest_path = Utf8PathBuf::from_str(split[0])
1148                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1149                let package = split[1].to_string();
1150                return Ok(Some(WasmPath::Maybe {
1151                    manifest_path,
1152                    package,
1153                }));
1154            }
1155            Ok(None)
1156        }
1157
1158        if let Some(wasm_path) =
1159            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1160        {
1161            return Ok(wasm_path);
1162        }
1163
1164        if s.ends_with(".wasm") {
1165            let path = Utf8PathBuf::from_str(s)
1166                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1167            return WasmPath::with_wasm(path);
1168        }
1169
1170        if s.ends_with("Cargo.toml") {
1171            let manifest_path = Utf8PathBuf::from_str(s)
1172                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1173            return WasmPath::with_maybe_only_manifest(manifest_path);
1174        }
1175
1176        WasmPath::with_maybe_only_package(s.to_string())
1177            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1178    }
1179}
1180
1181impl WasmPath {
1182    /// Computes the unique short name used during module linking and identification.
1183    pub fn name(&self) -> eyre::Result<CompactString> {
1184        match self {
1185            WasmPath::Maybe { package, .. } => {
1186                // Normalize package name by replacing hyphens with underscores
1187                // This is necessary because Rust package names can have hyphens (e.g., "test-package")
1188                // but they are converted to underscores in module identifiers (e.g., "test_package")
1189                let normalized = package.replace('-', "_");
1190                Ok(normalized.to_compact_string())
1191            }
1192            WasmPath::Definitely(path)
1193            | WasmPath::Component(path)
1194            | WasmPath::Original { current: path, .. } => path
1195                .get_file_main_name()
1196                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1197        }
1198    }
1199
1200    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1201    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1202        match self {
1203            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1204            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1205        }
1206    }
1207
1208    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1209    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1210        match self {
1211            WasmPath::Maybe { manifest_path, .. } => {
1212                let cargo_metadata = {
1213                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1214                    metadata_command.manifest_path(&manifest_path);
1215                    metadata_command.exec().unwrap()
1216                };
1217                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1218            }
1219            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1220        }
1221    }
1222
1223    /// Statically assigns an unresolved target using defined package specifications.
1224    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1225        Self::Maybe {
1226            manifest_path,
1227            package,
1228        }
1229    }
1230
1231    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1232    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1233        let cargo_metadata = {
1234            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1235            metadata_command.manifest_path(&manifest_path);
1236            metadata_command.exec().unwrap()
1237        };
1238        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1239
1240        Ok(Self::Maybe {
1241            manifest_path,
1242            package: building_crate.name.to_string(),
1243        })
1244    }
1245
1246    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1247    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1248        let cargo_metadata = {
1249            let metadata_command = cargo_metadata::MetadataCommand::new();
1250            metadata_command.exec().unwrap()
1251        };
1252        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1253
1254        Ok(Self::Maybe {
1255            manifest_path: building_crate.manifest_path,
1256            package: building_crate.name.to_string(),
1257        })
1258    }
1259
1260    /// Loads an unresolved dependency using current environment cargo bounds natively.
1261    pub fn with_maybe_none() -> eyre::Result<Self> {
1262        let cargo_metadata = {
1263            let metadata_command = cargo_metadata::MetadataCommand::new();
1264            metadata_command.exec().unwrap()
1265        };
1266        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1267
1268        Ok(Self::Maybe {
1269            manifest_path: building_crate.manifest_path,
1270            package: building_crate.name.to_string(),
1271        })
1272    }
1273
1274    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1275    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1276    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1277        if path.extension() != Some("wasm") {
1278            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1279        }
1280        if !fs::metadata(&path).is_ok() {
1281            // Assume it's an original Wasm file even if it doesn't exist yet
1282            return Ok(Self::Original {
1283                current: path.clone(),
1284                original: path,
1285            });
1286        }
1287
1288        let mut file =
1289            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1290        let mut magic = [0u8; 8];
1291        file.read_exact(&mut magic)
1292            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1293        if !magic.starts_with(b"\0asm") {
1294            eyre::bail!("Wasm file does not have valid magic number: {path}");
1295        }
1296        let version = &magic[4..8];
1297        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1298        if version == [0x0D, 0x00, 0x01, 0x00] {
1299            return Ok(Self::Component(path));
1300        }
1301        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1302        if version != [0x01, 0x00, 0x00, 0x00] {
1303            eyre::bail!("Wasm file does not have valid version: {path}");
1304        }
1305
1306        Ok(Self::Original {
1307            current: path.clone(),
1308            original: path,
1309        })
1310    }
1311
1312    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1313    pub fn definitely(
1314        &mut self,
1315        threads: bool,
1316        vfs_build_opts: &args::VfsBuildOptions,
1317    ) -> eyre::Result<()> {
1318        if let WasmPath::Maybe {
1319            manifest_path,
1320            package,
1321        } = self
1322        {
1323            let cargo_metadata = {
1324                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1325                metadata_command.manifest_path(&manifest_path);
1326                metadata_command.exec().unwrap()
1327            };
1328            let building_crate =
1329                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1330            let vfs_name = building_crate.name.to_string();
1331
1332            let path = compile::build_vfs(
1333                Some(&manifest_path.to_string()),
1334                &building_crate,
1335                threads,
1336                vfs_build_opts,
1337            )
1338            .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1339            *self = WasmPath::Definitely(path);
1340        }
1341
1342        // Original variant is already resolved, no action needed.
1343
1344        Ok(())
1345    }
1346
1347    /// Returns the path to the WASM module.
1348    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1349        match self {
1350            WasmPath::Maybe { .. } => {
1351                eyre::bail!("WasmPath is not definitely set: {self:?}")
1352            }
1353            WasmPath::Definitely(p)
1354            | WasmPath::Component(p)
1355            | WasmPath::Original { current: p, .. } => Ok(p),
1356        }
1357    }
1358
1359    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1360    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1361        matches!(self, WasmPath::Original { original, .. } if original == path)
1362    }
1363
1364    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1365    /// For `Original` variants, preserves the original path tracking.
1366    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1367        match self {
1368            WasmPath::Maybe { .. } => {
1369                eyre::bail!("WasmPath is not definitely set: {path}")
1370            }
1371            WasmPath::Original { current, .. } => {
1372                // Keep the original path, only update current
1373                *current = path;
1374            }
1375            _ => {
1376                *self = WasmPath::Definitely(path);
1377            }
1378        }
1379        Ok(())
1380    }
1381}
1382
1383/// Combines prepared VFS and target modules into one core Wasm module.
1384fn count_defined_funcs(wasm_path: &camino::Utf8PathBuf) -> eyre::Result<u32> {
1385    let wasm = std::fs::read(wasm_path)?;
1386    for payload in wasmparser::Parser::new(0).parse_all(&wasm) {
1387        let payload = payload.map_err(|e| eyre::eyre!("Parse error: {}", e))?;
1388        if let wasmparser::Payload::FunctionSection(s) = payload {
1389            return Ok(s.count());
1390        }
1391    }
1392    Ok(0)
1393}
1394
1395pub fn merge(
1396    vfs: &Utf8PathBuf,
1397    wasm: &[impl AsRef<std::path::Path>],
1398    output: impl AsRef<std::path::Path>,
1399    _threads: bool,
1400    dwarf: bool,
1401) -> eyre::Result<()> {
1402    let mut inputs = Vec::with_capacity(wasm.len() + 1);
1403    inputs.push(crate::wasm_stream::merge::MergeInput {
1404        alias: UniqueName::WASIP1_ABI_MODULE.to_string(),
1405        path: vfs.as_std_path(),
1406    });
1407    for wasm in wasm {
1408        inputs.push(crate::wasm_stream::merge::MergeInput {
1409            alias: format!(
1410                "wasip1_vfs_{}",
1411                wasm.as_ref()
1412                    .get_file_main_name()
1413                    .ok_or_else(|| eyre::eyre!("Failed to get Wasm module name"))?
1414            ),
1415            path: wasm.as_ref(),
1416        });
1417    }
1418    crate::wasm_stream::merge::merge_modules(&inputs, output, dwarf)
1419}
1420
1421macro_rules! _add_generators_by_type {
1422    ($runner:expr, $($ty:ty),* $(,)?) => {
1423        $(
1424            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1425                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1426            }
1427            $runner.add_generator(<$ty>::default());
1428        )*
1429    };
1430}