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