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