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