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