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/// 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    let parsed_args = args::Cli::parse_from(&args_vec);
81
82    let lock_ids = get_command_lock_identifiers(&parsed_args.command);
83
84    let command_lock = if !lock_ids.is_empty() {
85        let lock = std::sync::Arc::new(std::sync::Mutex::new(Some(CommandLock::acquire(&lock_ids)?)));
86        let cl_clone = lock.clone();
87        ctrlc_handler::register(move || {
88            if let Ok(mut lock) = cl_clone.lock() {
89                if let Some(l) = lock.take() {
90                    drop(l);
91                }
92            }
93        });
94        Some(lock)
95    } else {
96        None
97    };
98
99    struct MainCommandLockGuard(Option<std::sync::Arc<std::sync::Mutex<Option<CommandLock>>>>);
100    impl Drop for MainCommandLockGuard {
101        fn drop(&mut self) {
102            if let Some(ref lock_arc) = self.0 {
103                if let Ok(mut lock) = lock_arc.lock() {
104                    let _ = lock.take();
105                }
106            }
107        }
108    }
109    let _command_lock_guard = MainCommandLockGuard(command_lock);
110
111    match parsed_args.command {
112        args::Command::Build(build_args) => build(build_args),
113        args::Command::Prebuild(prebuild_args) => prebuild(prebuild_args),
114        args::Command::Postbuild(postbuild_args) => postbuild(postbuild_args),
115        args::Command::New(new_args) => new(new_args),
116        args::Command::PrepareTarget(prepare_target_args) => {
117            let output = prepare_target_args.output.unwrap_or_else(|| {
118                prepare_target_args
119                    .target_wasm
120                    .with_extension("prepared.wasm")
121            });
122            let args = commands::prepare_target::PrepareTargetHandler {
123                target_wasm: prepare_target_args.target_wasm,
124                output,
125                keep_artifacts: prepare_target_args.keep_artifacts,
126            };
127            prepare_target(args)
128        }
129    }
130}
131
132fn get_command_lock_identifiers(command: &args::Command) -> Vec<String> {
133    let mut ids = Vec::new();
134
135    fn get_workspace_root(manifest_path: Option<&camino::Utf8PathBuf>) -> String {
136        let mut cmd = cargo_metadata::MetadataCommand::new();
137        cmd.no_deps(); // Faster, only need workspace root
138        if let Some(path) = manifest_path {
139            cmd.manifest_path(path);
140        }
141        if let Ok(metadata) = cmd.exec() {
142            return metadata.workspace_root.to_string();
143        }
144
145        // Fallback: look for Cargo.toml upwards
146        let mut curr = if let Some(path) = manifest_path {
147            path.parent().map(|p| p.to_path_buf().into_std_path_buf())
148        } else {
149            std::env::current_dir().ok()
150        };
151
152        while let Some(path) = curr {
153            if path.join("Cargo.toml").exists() {
154                return path.to_string_lossy().to_string();
155            }
156            curr = path.parent().map(|p| p.to_path_buf());
157        }
158        std::env::current_dir()
159            .map(|p| p.to_string_lossy().to_string())
160            .unwrap_or_default()
161    }
162
163    match command {
164        args::Command::Build(args) => {
165            ids.push(get_workspace_root(args.manifest_path.as_ref()));
166            ids.push(args.out_dir.to_string());
167        }
168        args::Command::Prebuild(args) => {
169            ids.push(get_workspace_root(args.manifest_path.as_ref()));
170            ids.push(args.out_dir.to_string());
171        }
172        args::Command::Postbuild(args) => {
173            ids.push(args.out_dir.to_string());
174        }
175        args::Command::PrepareTarget(args) => {
176            let output = args.output.clone().unwrap_or_else(|| {
177                args.target_wasm.with_extension("prepared.wasm")
178            });
179            if let Some(parent) = output.parent() {
180                ids.push(parent.to_string());
181            }
182        }
183        args::Command::New(_) => {}
184    }
185
186    // Canonicalize all IDs if they are paths
187    ids.into_iter()
188        .map(|id| {
189            camino::Utf8PathBuf::from(&id)
190                .canonicalize_utf8()
191                .map(|p| p.to_string())
192                .unwrap_or(id)
193        })
194        .collect()
195}