Skip to main content

wasi_virt_layer_cli/
lib.rs

1#![warn(missing_docs)]
2//! CLI tool for creating and inspecting WASI virtualized binaries.
3//!
4//! Provides commands and generator internals `wasi_virt_layer`.
5
6use crate::{
7    commands::{build::build, new::new, postbuild::postbuild, prebuild::prebuild},
8    fallback_command::CommandLock,
9};
10
11/// WASI ABI transformation and generation constants.
12pub mod abi;
13/// CLI argument parsing structures and definitions.
14pub mod args;
15/// Handlers for various CLI subcommands.
16pub mod commands;
17/// Compilation routines for Wasm virtual filesystems.
18pub mod compile;
19/// Checks and manages features required in Cargo configs.
20pub mod config_checker;
21/// Signal handler for graceful termination (e.g., Ctrl-C).
22pub mod ctrlc_handler;
23/// Helper logic to lower text colors and apply them.
24pub mod down_color;
25/// Contains fallback execution processes (managed via locks).
26pub mod fallback_command; // fallback logic guarded by DISABLE_FALLBACK
27/// Extracts and associates features with their target Wasm modules based on command line order.
28pub mod feature_extractor;
29/// Generate TypeScript helper code for VFS modules.
30pub mod gen_ts_helper;
31/// Internal generators for modifying and stitching Wasm structures.
32#[allow(missing_docs)]
33pub mod generator;
34/// Instruction scanning and rewriting utilities for Walrus IR.
35
36/// Utilities for running integration tests against Wasm runtimes.
37pub mod test_run;
38/// Utilities for generating globally unique IDs/names within Wasm modules.
39pub mod unique_name;
40/// General utility functions for CLI logic and AST operations.
41pub mod util;
42/// Streaming Wasm module modification engine.
43#[allow(missing_docs)]
44pub mod wasm_stream;
45
46/// Central execution entrypoint for the CLI logic
47pub fn main(args: impl IntoIterator<Item = impl Into<String>>) -> eyre::Result<()> {
48    let args_vec: Vec<String> = args.into_iter().map(Into::into).collect();
49
50    if let Some(bin) = std::env::var(fallback_command::COMMAND_ALTERNATE_ENV_VAR).ok() {
51        match bin.as_str() {
52            "wasm-opt" => {
53                return match fallback_command::wasm_opt(&args_vec) {
54                    0 => Ok(()),
55                    code => Err(eyre::eyre!("wasm-opt failed with exit code {code}")),
56                };
57            }
58            _ => {
59                // For custom fallbacks (like in tests), we might need to handle them.
60                // However, the self-call fallback doesn't support closures.
61                // If this is reached, it means an unknown fallback was requested.
62                // We'll just exit with an error to avoid deadlock/unexpected behavior.
63                return Err(eyre::eyre!("Unsupported fallback command specified: {bin}"));
64            }
65        }
66    }
67
68    ctrlc_handler::init();
69
70    env_logger::Builder::new()
71        .filter_level(log::LevelFilter::Info)
72        .init();
73    color_eyre::install()?;
74
75    use clap::{CommandFactory, FromArgMatches};
76    let cmd = args::Cli::command();
77    let matches = cmd.get_matches_from(&args_vec);
78    let mut parsed_args = args::Cli::from_arg_matches(&matches)?;
79
80    if let Some((subcmd, sub_matches)) = matches.subcommand() {
81        match subcmd {
82            "build" => {
83                if let args::Command::Build(ref mut build_args) = parsed_args.command {
84                    let (vfs_opts, target_opts) = crate::feature_extractor::extract_features(
85                        sub_matches,
86                        build_args.wasm.len(),
87                    );
88                    build_args.vfs_build_opts = vfs_opts;
89                    build_args.target_vfs_build_opts = Some(target_opts);
90                }
91            }
92            "prebuild" => {
93                if let args::Command::Prebuild(ref mut prebuild_args) = parsed_args.command {
94                    let (vfs_opts, target_opts) = crate::feature_extractor::extract_features(
95                        sub_matches,
96                        prebuild_args.wasm.len(),
97                    );
98                    prebuild_args.vfs_build_opts = vfs_opts;
99                    prebuild_args.target_vfs_build_opts = Some(target_opts);
100                }
101            }
102            _ => {}
103        }
104    }
105
106    let lock_ids = get_command_lock_identifiers(&parsed_args.command);
107
108    let command_lock = if !lock_ids.is_empty() {
109        let lock = std::sync::Arc::new(std::sync::Mutex::new(Some(CommandLock::acquire(
110            &lock_ids,
111        )?)));
112        let cl_clone = lock.clone();
113        ctrlc_handler::register(move || {
114            if let Ok(mut lock) = cl_clone.lock() {
115                if let Some(l) = lock.take() {
116                    drop(l);
117                }
118            }
119        });
120        Some(lock)
121    } else {
122        None
123    };
124
125    struct MainCommandLockGuard(Option<std::sync::Arc<std::sync::Mutex<Option<CommandLock>>>>);
126    impl Drop for MainCommandLockGuard {
127        fn drop(&mut self) {
128            if let Some(ref lock_arc) = self.0 {
129                if let Ok(mut lock) = lock_arc.lock() {
130                    let _ = lock.take();
131                }
132            }
133        }
134    }
135    let _command_lock_guard = MainCommandLockGuard(command_lock);
136
137    match parsed_args.command {
138        args::Command::Build(build_args) => build(build_args),
139        args::Command::Prebuild(prebuild_args) => prebuild(prebuild_args),
140        args::Command::Postbuild(postbuild_args) => postbuild(postbuild_args),
141        args::Command::New(new_args) => new(new_args),
142    }
143}
144
145fn get_command_lock_identifiers(command: &args::Command) -> Vec<String> {
146    let mut ids = Vec::new();
147
148    fn get_workspace_root(manifest_path: Option<&camino::Utf8PathBuf>) -> String {
149        let mut cmd = cargo_metadata::MetadataCommand::new();
150        cmd.no_deps(); // Faster, only need workspace root
151        if let Some(path) = manifest_path {
152            cmd.manifest_path(path);
153        }
154        if let Ok(metadata) = cmd.exec() {
155            return metadata.workspace_root.to_string();
156        }
157
158        // Fallback: look for Cargo.toml upwards
159        let mut curr = if let Some(path) = manifest_path {
160            path.parent().map(|p| p.to_path_buf().into_std_path_buf())
161        } else {
162            std::env::current_dir().ok()
163        };
164
165        while let Some(path) = curr {
166            if path.join("Cargo.toml").exists() {
167                return path.to_string_lossy().to_string();
168            }
169            curr = path.parent().map(|p| p.to_path_buf());
170        }
171        std::env::current_dir()
172            .map(|p| p.to_string_lossy().to_string())
173            .unwrap_or_default()
174    }
175
176    match command {
177        args::Command::Build(args) => {
178            ids.push(get_workspace_root(args.manifest_path.as_ref()));
179            ids.push(args.out_dir.to_string());
180        }
181        args::Command::Prebuild(args) => {
182            ids.push(get_workspace_root(args.manifest_path.as_ref()));
183            ids.push(args.out_dir.to_string());
184        }
185        args::Command::Postbuild(args) => {
186            ids.push(args.out_dir.to_string());
187        }
188        args::Command::New(_) => {}
189    }
190
191    // Canonicalize all IDs if they are paths
192    ids.into_iter()
193        .map(|id| {
194            camino::Utf8PathBuf::from(&id)
195                .canonicalize_utf8()
196                .map(|p| p.to_string())
197                .unwrap_or(id)
198        })
199        .collect()
200}