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