Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

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