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 (mut vfs_opts, target_opts) = crate::feature_extractor::extract_features(
85                        sub_matches,
86                        build_args.wasm.len(),
87                    );
88                    if build_args.own_memory
89                        && !vfs_opts
90                            .features
91                            .iter()
92                            .any(|f| f == "wasi_virt_layer/own-memory")
93                    {
94                        vfs_opts
95                            .features
96                            .push("wasi_virt_layer/own-memory".to_string());
97                    }
98                    build_args.vfs_build_opts = vfs_opts;
99                    build_args.target_vfs_build_opts = Some(target_opts);
100                }
101            }
102            "prebuild" => {
103                if let args::Command::Prebuild(ref mut prebuild_args) = parsed_args.command {
104                    let (mut vfs_opts, target_opts) = crate::feature_extractor::extract_features(
105                        sub_matches,
106                        prebuild_args.wasm.len(),
107                    );
108                    if prebuild_args.own_memory
109                        && !vfs_opts
110                            .features
111                            .iter()
112                            .any(|f| f == "wasi_virt_layer/own-memory")
113                    {
114                        vfs_opts
115                            .features
116                            .push("wasi_virt_layer/own-memory".to_string());
117                    }
118                    prebuild_args.vfs_build_opts = vfs_opts;
119                    prebuild_args.target_vfs_build_opts = Some(target_opts);
120                }
121            }
122            _ => {}
123        }
124    }
125
126    let lock_ids = get_command_lock_identifiers(&parsed_args.command);
127
128    let command_lock = if !lock_ids.is_empty() {
129        let lock = std::sync::Arc::new(std::sync::Mutex::new(Some(CommandLock::acquire(
130            &lock_ids,
131        )?)));
132        let cl_clone = lock.clone();
133        ctrlc_handler::register(move || {
134            if let Ok(mut lock) = cl_clone.lock() {
135                if let Some(l) = lock.take() {
136                    drop(l);
137                }
138            }
139        });
140        Some(lock)
141    } else {
142        None
143    };
144
145    struct MainCommandLockGuard(Option<std::sync::Arc<std::sync::Mutex<Option<CommandLock>>>>);
146    impl Drop for MainCommandLockGuard {
147        fn drop(&mut self) {
148            if let Some(ref lock_arc) = self.0 {
149                if let Ok(mut lock) = lock_arc.lock() {
150                    let _ = lock.take();
151                }
152            }
153        }
154    }
155    let _command_lock_guard = MainCommandLockGuard(command_lock);
156
157    match parsed_args.command {
158        args::Command::Build(build_args) => build(build_args),
159        args::Command::Prebuild(prebuild_args) => prebuild(prebuild_args),
160        args::Command::Postbuild(postbuild_args) => postbuild(postbuild_args),
161        args::Command::New(new_args) => new(new_args),
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::New(_) => {}
209    }
210
211    // Canonicalize all IDs if they are paths
212    ids.into_iter()
213        .map(|id| {
214            camino::Utf8PathBuf::from(&id)
215                .canonicalize_utf8()
216                .map(|p| p.to_string())
217                .unwrap_or(id)
218        })
219        .collect()
220}