Skip to main content

wasi_virt_layer_cli/
compile.rs

1use std::{
2    collections::VecDeque,
3    io::{BufRead, Write as _},
4    sync::{LazyLock, mpsc::Receiver},
5};
6
7use eyre::{Context as _, ContextCompat};
8
9use crate::{down_color, fallback_command, util::ResultUtil as _};
10
11const THREADED_VFS_MIN_STABLE: (u32, u32, u32) = (1, 100, 0);
12// nightly-2026-08-27 is built from the 2026-08-26 rustc commit snapshot.
13const THREADED_VFS_MIN_NIGHTLY_COMMIT_DATE: &str = "2026-08-26";
14
15#[derive(Debug, PartialEq, Eq)]
16struct RustcToolchainInfo {
17    release: String,
18    commit_date: Option<String>,
19}
20
21fn parse_rustc_verbose(version: &str) -> eyre::Result<RustcToolchainInfo> {
22    let mut release = None;
23    let mut commit_date = None;
24    for line in version.lines() {
25        if let Some(value) = line.strip_prefix("release: ") {
26            release = Some(value.trim().to_string());
27        } else if let Some(value) = line.strip_prefix("commit-date: ") {
28            commit_date = Some(value.trim().to_string());
29        }
30    }
31
32    Ok(RustcToolchainInfo {
33        release: release.wrap_err("rustc -Vv did not report a release")?,
34        commit_date,
35    })
36}
37
38fn parse_release_triplet(release: &str) -> Option<(u32, u32, u32)> {
39    let numeric = release.split('-').next()?;
40    let mut parts = numeric.split('.');
41    Some((
42        parts.next()?.parse().ok()?,
43        parts.next()?.parse().ok()?,
44        parts.next()?.parse().ok()?,
45    ))
46}
47
48fn supports_threaded_vfs(info: &RustcToolchainInfo) -> bool {
49    if info.release.contains("-nightly") || info.release.contains("-dev") {
50        return info.commit_date.as_deref() >= Some(THREADED_VFS_MIN_NIGHTLY_COMMIT_DATE);
51    }
52
53    parse_release_triplet(&info.release).is_some_and(|version| version >= THREADED_VFS_MIN_STABLE)
54}
55
56#[doc(hidden)]
57pub fn current_toolchain_supports_threaded_vfs() -> eyre::Result<bool> {
58    threaded_vfs_toolchain_info(false).map(|info| supports_threaded_vfs(&info))
59}
60
61fn threaded_vfs_toolchain_info(use_nightly: bool) -> eyre::Result<RustcToolchainInfo> {
62    let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
63    let mut command = std::process::Command::new(rustc);
64    if use_nightly && std::env::var_os("RUSTC").is_none() {
65        command.arg("+nightly");
66    }
67    let output = command
68        .arg("-Vv")
69        .output()
70        .wrap_err("Failed to query rustc version for threaded VFS build")?;
71    if !output.status.success() {
72        eyre::bail!("rustc -Vv failed while checking threaded VFS toolchain support");
73    }
74    parse_rustc_verbose(&String::from_utf8_lossy(&output.stdout))
75}
76
77fn ensure_threaded_vfs_toolchain(use_nightly: bool) -> eyre::Result<()> {
78    let info = threaded_vfs_toolchain_info(use_nightly)?;
79    if supports_threaded_vfs(&info) {
80        return Ok(());
81    }
82
83    let commit_date = info.commit_date.as_deref().unwrap_or("unknown date");
84    Err(eyre::eyre!(
85        "threaded VFS/reactor builds require nightly-2026-08-27 or newer, or stable Rust 1.100.0 or newer; current rustc is {} ({commit_date}). rust-lang/rust#146721 no longer requires nightly for command modules, but this toolchain does not contain the reactor fix for rust-lang/rust#146843",
86        info.release
87    ))
88}
89
90struct CustomReadIterator<const T: usize, R: BufRead> {
91    r: R,
92    chars: [char; T],
93}
94
95impl<const T: usize, R: BufRead> CustomReadIterator<T, R> {
96    fn new(r: R, chars: [char; T]) -> Self {
97        Self { r, chars }
98    }
99}
100
101impl<const T: usize, R: BufRead> Iterator for CustomReadIterator<T, R> {
102    type Item = String;
103
104    fn next(&mut self) -> Option<Self::Item> {
105        let mut buf = Vec::new();
106        loop {
107            let mut one_buffer = [0; 1];
108            let read = self.r.read(&mut one_buffer).unwrap();
109            if read == 0 {
110                return None;
111            }
112            if self.chars.contains(&(one_buffer[0] as char)) {
113                let line = String::from_utf8(buf).unwrap();
114                return Some(line);
115            } else {
116                buf.push(one_buffer[0]);
117            }
118        }
119    }
120}
121
122/// Compiles the VFS module from the specified manifest and crate.
123pub fn build_vfs(
124    manifest_path: Option<&String>,
125    building_crate: &cargo_metadata::Package,
126    threads: bool,
127    vfs_build_opts: &crate::args::VfsBuildOptions,
128) -> eyre::Result<camino::Utf8PathBuf> {
129    if threads {
130        ensure_threaded_vfs_toolchain(vfs_build_opts.unwind)?;
131    }
132
133    let mut ret = None;
134
135    let mut command_base = if vfs_build_opts.unwind {
136        // The cargo executable may be a wrapper that does not understand
137        // rustup's `+toolchain` syntax, so invoke rustup explicitly.
138        std::process::Command::new("rustup")
139    } else {
140        std::process::Command::new("cargo")
141    };
142
143    let existing_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
144    let mut new_rustflags = format!("{existing_rustflags} -C link-arg=--allow-undefined");
145    if vfs_build_opts.unwind {
146        new_rustflags =
147            format!("{new_rustflags} -Cpanic=unwind -Cllvm-args=-wasm-use-legacy-eh=false");
148    }
149    command_base.env("RUSTFLAGS", new_rustflags.trim());
150
151    let features = vfs_build_opts.features.join(",");
152    let command = command_base.args({
153        let mut args = vec![
154            "build",
155            "--target",
156            if threads {
157                "wasm32-wasip1-threads"
158            } else {
159                "wasm32-wasip1"
160            },
161            "--message-format=json-render-diagnostics",
162            "--color",
163            "always",
164        ];
165        args.push("--release");
166
167        if !vfs_build_opts.features.is_empty() {
168            args.push("--features");
169            args.push(&features);
170        }
171
172        if vfs_build_opts.no_default_features > 0 {
173            args.push("--no-default-features");
174        }
175        if vfs_build_opts.unwind {
176            args.insert(0, "cargo");
177            args.insert(0, "nightly");
178            args.insert(0, "run");
179
180            // https://github.com/rust-lang/rust/pull/151309
181            // args.insert(0, "+nightly-2025-12-20");
182        }
183
184        if vfs_build_opts.unwind {
185            args.push("-Zbuild-std=std,panic_unwind");
186        }
187
188        args.push("--package");
189        args.push(&building_crate.name);
190        if let Some(ref manifest_path) = manifest_path {
191            args.push("--manifest-path");
192            args.push(&manifest_path);
193        }
194        args
195    });
196
197    let mut command = command
198        .stdout(std::process::Stdio::piped())
199        .stderr(std::process::Stdio::piped())
200        .spawn()
201        .wrap_err("Failed to spawn cargo build process")?;
202
203    // Capture the output
204    let reader = std::io::BufReader::new(
205        command
206            .stdout
207            .take()
208            .wrap_err_with(|| eyre::eyre!("Failed to capture stdout"))?,
209    );
210
211    // Compiling etc.
212    let err_reader = std::io::BufReader::new(
213        command
214            .stderr
215            .take()
216            .wrap_err_with(|| eyre::eyre!("Failed to capture stderr"))?,
217    );
218
219    let mut before_len = 0;
220    let term = console::Term::stdout();
221
222    let mut last_lines = VecDeque::with_capacity(3);
223
224    let (msg_sender, msg_receiver) = std::sync::mpsc::channel();
225    let (parse_sender, parse_receiver) = std::sync::mpsc::channel();
226
227    let msg_thread = std::thread::spawn(move || -> Result<(), eyre::Report> {
228        for line in CustomReadIterator::new(err_reader, ['\n', '\r']) {
229            msg_sender
230                .send(line)
231                .wrap_err_with(|| eyre::eyre!("Failed to send error message"))?;
232        }
233
234        Ok(())
235    });
236
237    let parse_thread = std::thread::spawn(move || -> Result<(), eyre::Report> {
238        for message in cargo_metadata::Message::parse_stream(reader) {
239            let message = message.wrap_err("Failed to parse cargo metadata message")?;
240
241            parse_sender
242                .send(message)
243                .wrap_err("Failed to send parse message")?;
244        }
245
246        Ok(())
247    });
248
249    let mut before_msgs: Vec<String> = Vec::new();
250
251    fn process_msg(
252        msg_receiver: &Receiver<String>,
253        last_lines: &mut VecDeque<String>,
254        before_msgs: &mut Vec<String>,
255        before_len: &mut usize,
256        term: &console::Term,
257    ) -> Result<(), eyre::Report> {
258        let mut is_change = false;
259        'inner: loop {
260            if let Some(line) = msg_receiver.try_recv().ok() {
261                fn check_finish_or_compiling(line: &str) -> eyre::Result<bool> {
262                    static NON_ANSI: LazyLock<regex::Regex> =
263                        LazyLock::new(|| regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap());
264
265                    let line = NON_ANSI.replace_all(line, "");
266
267                    if line.contains("Finished") || line.contains("Compiling") {
268                        let index = line
269                            .find("Finished")
270                            .or_else(|| line.find("Compiling"))
271                            .wrap_err("Failed to find 'Finished' or 'Compiling' in line")?;
272
273                        let line = &line[..index];
274
275                        Ok(line.as_bytes().iter().all(|&b| b == b' '))
276                    } else {
277                        return Ok(false);
278                    }
279                }
280
281                if check_finish_or_compiling(&line)? {
282                    // Skip lines with carriage return
283                    if line.contains("\r") {
284                        last_lines.pop_back();
285                        last_lines.push_back(line.to_string());
286                    } else {
287                        last_lines.push_back(line.to_string());
288                        if last_lines.len() > 3 {
289                            last_lines.pop_front();
290                        }
291                    }
292                } else {
293                    before_msgs.push(line.to_string());
294                }
295                is_change = true;
296            } else {
297                break 'inner;
298            }
299        }
300
301        if is_change || !before_msgs.is_empty() {
302            term.clear_last_lines(*before_len)
303                .wrap_err("Failed to clear last lines")?;
304
305            for msg in before_msgs.iter() {
306                term.write_line(msg).wrap_err("Failed to write message")?;
307            }
308            before_msgs.clear();
309
310            *before_len = last_lines.len();
311            for line in last_lines.iter() {
312                term.write_line(&down_color::reduce_saturation(line, 0.5))
313                    .wrap_err("Failed to write line")?;
314            }
315            term.flush().wrap_err("Failed to flush terminal")?;
316        }
317
318        Ok(())
319    }
320
321    let finished = 'outer: loop {
322        process_msg(
323            &msg_receiver,
324            &mut last_lines,
325            &mut before_msgs,
326            &mut before_len,
327            &term,
328        )?;
329
330        if let Some(status) = command.try_wait().wrap_err("Failed to try wait")? {
331            if !status.success() {
332                // Drain any remaining messages
333                std::thread::sleep(std::time::Duration::from_millis(100));
334                process_msg(
335                    &msg_receiver,
336                    &mut last_lines,
337                    &mut before_msgs,
338                    &mut before_len,
339                    &term,
340                )?;
341                while let Some(message) = parse_receiver.try_recv().ok() {
342                    if let cargo_metadata::Message::BuildFinished(finished) = message {
343                        if !finished.success {
344                            return Err(eyre::eyre!(
345                                "Build failed with errors. Check the output above."
346                            ));
347                        }
348                    }
349                }
350                return Err(eyre::eyre!("Cargo build failed with exit code: {status}"));
351            }
352        }
353
354        'inner: loop {
355            if let Some(message) = parse_receiver.try_recv().ok() {
356                match message {
357                    cargo_metadata::Message::CompilerArtifact(artifact) => {
358                        if building_crate.id == artifact.package_id {
359                            // let mut file = std::fs::OpenOptions::new()
360                            //     .append(true)
361                            //     .create(true)
362                            //     .open("output_artifact.txt")
363                            //     .unwrap();
364                            // file.write_all(format!("{:?}", artifact).as_bytes())
365                            //     .unwrap();
366                            // file.write_all(b"\n").unwrap();
367
368                            if let Some(wasm) = artifact
369                                .filenames
370                                .iter()
371                                .filter(|f| f.extension() == Some("wasm"))
372                                .next()
373                                .cloned()
374                            {
375                                ret = Some(wasm);
376                            }
377                        }
378                    }
379                    cargo_metadata::Message::CompilerMessage(msg) => {
380                        if let Some(ref rendered) = msg.message.rendered {
381                            before_msgs.push(rendered.to_string());
382                        }
383                    }
384                    cargo_metadata::Message::BuildFinished(finished) => {
385                        // Handle the build finished message
386                        // println!("Build Finished: {:?}", finished);
387
388                        if !finished.success {
389                            return Err(eyre::eyre!(
390                                "Build failed with errors. Check the output above."
391                            ));
392                        }
393
394                        break 'outer finished;
395                    }
396                    _ => {}
397                }
398            } else {
399                break 'inner;
400            }
401        }
402
403        std::thread::sleep(std::time::Duration::from_millis(100));
404    };
405
406    msg_thread
407        .join()
408        .map_err(|e| eyre::eyre!("Failed to join message thread: {:?}", e))?
409        .wrap_err("Message thread failed")?;
410    parse_thread
411        .join()
412        .map_err(|e| eyre::eyre!("Failed to join parse thread: {:?}", e))?
413        .wrap_err("Parse thread failed")?;
414    command
415        .wait()
416        .map_err(|e| eyre::eyre!("Failed to wait for command: {:?}", e))?;
417
418    process_msg(
419        &msg_receiver,
420        &mut last_lines,
421        &mut before_msgs,
422        &mut before_len,
423        &term,
424    )?;
425
426    print!("\x1b[39m");
427
428    if finished.success {
429        println!("Build succeeded!");
430    } else {
431        println!("Build failed!");
432    }
433
434    Ok(ret.wrap_err(
435        r#"
436Failed to find Wasm file on build artifact. If you set `
437[lib]
438crate-type = ["cdylib"]
439` on Cargo.toml.
440"#
441        .trim(),
442    )?)
443}
444
445/// Resolves and returns the target package being built from cargo metadata.
446pub fn get_building_crate(
447    metadata: &cargo_metadata::Metadata,
448    package: &Option<String>,
449) -> color_eyre::Result<cargo_metadata::Package> {
450    let building_crate = {
451        let packages = metadata.packages.clone();
452
453        if let Some(package_name) = package {
454            packages
455                .iter()
456                .filter(|package| *package.name == *package_name)
457                .cloned()
458                .collect::<Vec<_>>()
459        } else {
460            let workspace = metadata.workspace_members.clone();
461            let workspace_default_packages = metadata.workspace_default_packages();
462
463            if workspace_default_packages.is_empty() {
464                packages
465                    .iter()
466                    .filter(|package| {
467                        workspace
468                            .iter()
469                            .any(|workspace_package| package.id == *workspace_package)
470                    })
471                    .cloned()
472                    .collect::<Vec<_>>()
473            } else {
474                packages
475                    .iter()
476                    .filter(|package| {
477                        workspace_default_packages
478                            .iter()
479                            .any(|workspace_package| package.id == workspace_package.id)
480                    })
481                    .cloned()
482                    .collect::<Vec<_>>()
483            }
484        }
485    }
486    .into_iter()
487    .next()
488    .wrap_err("Failed to find building crate")?;
489
490    Ok(building_crate)
491}
492
493/// Optimizes a WebAssembly module using the `wasm-opt` utility.
494pub fn optimize_wasm(
495    wasm_path: &camino::Utf8PathBuf,
496    add_args: &[&str],
497    require_update: bool,
498    dwarf: bool,
499) -> eyre::Result<camino::Utf8PathBuf> {
500    // if dwarf {
501    //     return Ok(wasm_path.clone());
502    // }
503
504    let mut before_path = wasm_path.clone();
505
506    let mut first = true;
507
508    loop {
509        let output_path = before_path.with_extension("opt.wasm");
510        if output_path.exists() {
511            std::fs::remove_file(&output_path)
512                .wrap_err("Failed to remove existing optimized WASM file")?;
513        }
514
515        let mut cmd = fallback_command::get_fallback_command("wasm-opt");
516
517        // Binaryen's no-inline marker is invocation-local. Reapply it after
518        // every pass that might reindex/strip names, before any optimization.
519        let protected =
520            crate::wasm_stream::passes::reactor_opt::optimizer_input(&std::fs::read(wasm_path)?)?;
521        let mut protected_file = None;
522        if let Some((bytes, name)) = &protected {
523            let mut file = tempfile::NamedTempFile::new()?;
524            file.write_all(bytes)?;
525            cmd.arg(format!("--no-inline={name}"));
526            protected_file = Some(file);
527        }
528
529        if dwarf {
530            cmd.arg("--debuginfo");
531        }
532
533        const OPTS: &[&str] = &["-O", "-O0", "-O1", "-O2", "-O3", "-O4", "-Oz", "-Os"];
534
535        cmd.args(add_args.iter().filter(|&&arg| !OPTS.contains(&arg)));
536
537        cmd.args(add_args.iter().filter(|&&arg| OPTS.contains(&arg)));
538
539        if add_args.iter().all(|&arg| !OPTS.contains(&arg)) {
540            cmd.arg("-Oz");
541        }
542
543        cmd.args([
544            "--enable-threads",
545            "--enable-bulk-memory",
546            "--enable-reference-types",
547            "--enable-simd",
548            "--enable-exception-handling",
549            "--enable-shared-everything",
550            "--enable-multivalue",
551            "--enable-multimemory",
552            "--enable-gc",
553        ]);
554
555        if let Some(file) = &protected_file {
556            cmd.arg(
557                file.path()
558                    .to_str()
559                    .ok_or_else(|| eyre::eyre!("non-UTF8 optimizer temporary path"))?,
560            );
561        } else {
562            cmd.arg(wasm_path.as_str());
563        }
564
565        cmd.args(["--output", output_path.as_str()]);
566        let command = cmd.spawn().wrap_err("Failed to spawn wasm-opt process")?;
567
568        let output = command
569            .wait_with_output()
570            .wrap_err("Failed to wait for wasm-opt process")?;
571
572        if !output.success {
573            let out = String::from_utf8_lossy(&output.stdout);
574            let err = String::from_utf8_lossy(&output.stderr);
575            eyre::bail!("wasm-opt failed: {err}\nstdout: {out}");
576        }
577
578        let before_size = std::fs::metadata(&before_path)
579            .map(|meta| meta.len())
580            .unwrap_or(0);
581        let after_size = std::fs::metadata(&output_path)
582            .map(|meta| meta.len())
583            .unwrap_or(0);
584
585        if before_size <= after_size {
586            if first {
587                if !require_update {
588                    std::fs::remove_file(&output_path)
589                        .wrap_err("Failed to remove existing optimized WASM file")?;
590                    std::fs::copy(&before_path, &output_path)
591                        .wrap_err("Failed to copy original WASM file")?;
592                }
593                before_path = output_path.clone();
594            } else {
595                // remove
596                std::fs::remove_file(&output_path)
597                    .wrap_err("Failed to remove optimized WASM file")?;
598            }
599
600            break;
601        }
602
603        first = false;
604
605        before_path = output_path.clone();
606    }
607
608    Ok(before_path)
609}
610
611/// Converts a WebAssembly module into a WebAssembly Component.
612pub fn wasm_to_component(
613    wasm_path: &camino::Utf8PathBuf,
614    _wasm_names: &[impl AsRef<str>],
615) -> eyre::Result<camino::Utf8PathBuf> {
616    let output_path = wasm_path.with_extension("component.wasm");
617    if output_path.exists() {
618        std::fs::remove_file(&output_path)?;
619    }
620
621    // https://github.com/bytecodealliance/wasm-tools/blob/main/src/bin/wasm-tools/component.rs#L259
622    let wasm = std::fs::read(wasm_path)?;
623
624    let mut encoder = wit_component::ComponentEncoder::default()
625        .validate(false)
626        .reject_legacy_names(false);
627
628    encoder = encoder
629        .module(&wasm)
630        .to_eyre()
631        .wrap_err_with(|| eyre::eyre!("failed to add module"))?;
632
633    encoder = encoder.realloc_via_memory_grow(true);
634
635    let bytes = encoder
636        .encode()
637        .to_eyre()
638        .wrap_err_with(|| eyre::eyre!("failed to encode a component"))?;
639
640    let mut file = std::fs::OpenOptions::new()
641        .write(true)
642        .create(true)
643        .truncate(true)
644        .open(&output_path)?;
645    file.write_all(&bytes)?;
646    file.sync_data()?;
647
648    Ok(output_path)
649}
650
651#[cfg(test)]
652mod toolchain_tests {
653    use super::*;
654
655    fn info(release: &str, commit_date: Option<&str>) -> RustcToolchainInfo {
656        RustcToolchainInfo {
657            release: release.to_string(),
658            commit_date: commit_date.map(str::to_string),
659        }
660    }
661
662    #[test]
663    fn parses_rustc_verbose_output() {
664        let parsed = parse_rustc_verbose(
665            "rustc 1.100.0-nightly\ncommit-date: 2026-08-26\nrelease: 1.100.0-nightly\n",
666        )
667        .unwrap();
668        assert_eq!(parsed, info("1.100.0-nightly", Some("2026-08-26")));
669    }
670
671    #[test]
672    fn stable_threaded_vfs_requires_1_100() {
673        assert!(!supports_threaded_vfs(&info("1.99.0", Some("2026-09-01"))));
674        assert!(supports_threaded_vfs(&info("1.100.0", Some("2026-10-01"))));
675        assert!(supports_threaded_vfs(&info(
676            "1.101.0-beta.1",
677            Some("2026-11-01")
678        )));
679    }
680
681    #[test]
682    fn nightly_threaded_vfs_uses_wasi_sdk_34_boundary() {
683        assert!(!supports_threaded_vfs(&info(
684            "1.100.0-nightly",
685            Some("2026-08-25")
686        )));
687        assert!(supports_threaded_vfs(&info(
688            "1.100.0-nightly",
689            Some("2026-08-26")
690        )));
691        assert!(supports_threaded_vfs(&info(
692            "1.100.0-nightly",
693            Some("2026-08-27")
694        )));
695    }
696
697    #[test]
698    fn nightly_without_commit_date_is_rejected() {
699        assert!(!supports_threaded_vfs(&info("1.100.0-nightly", None)));
700    }
701}