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