use std::{
fs::File,
io::{Read as _, Seek as _},
path::Path,
};
use eyre::Context as _;
use fs2::FileExt as _;
use tempfile::Builder as TempFileBuilder;
pub(crate) const COMMAND_ALTERNATE_ENV_VAR: &str = "WASI_VIRT_LAYER_FALLBACK_ALTERNATE_COMMAND";
#[allow(unused)]
pub(crate) fn wasm_merge(args: &[String]) -> i32 {
#[cfg(feature = "fallback")]
{
wasm_merge_sys::run_wasm_merge(args)
}
#[cfg(not(feature = "fallback"))]
{
eprintln!("wasm-merge fallback is not enabled");
1
}
}
#[allow(unused)]
pub(crate) fn wasm_opt(args: &[String]) -> i32 {
#[cfg(feature = "fallback")]
{
wasm_opt_sys::run_wasm_opt(args)
}
#[cfg(not(feature = "fallback"))]
{
eprintln!("wasm-opt fallback is not enabled");
1
}
}
fn fake_fallback(args: &[String]) -> i32 {
unimplemented!("This is a fake fallback function. It should never be called. Args: {args:?}");
}
pub fn get_fallback_command(bin: impl AsRef<str>) -> FallbackCommand<impl FnOnce(&[String]) -> i32 + Send + 'static> {
match bin.as_ref() {
"wasm-merge" => FallbackCommand::new("wasm-merge", fake_fallback),
"wasm-opt" => FallbackCommand::new("wasm-opt", fake_fallback),
_ => panic!("Unsupported fallback command specified: {}", bin.as_ref()),
}
}
pub struct FallbackCommand<F>
where
F: FnOnce(&[String]) -> i32 + Send + 'static,
{
pub bin: String,
pub args: Vec<String>,
pub func: Option<F>,
}
const DISABLE_FALLBACK: bool = false;
pub struct CommandLock(File);
impl<F> FallbackCommand<F>
where
F: FnOnce(&[String]) -> i32 + Send + 'static,
{
pub fn new(bin: impl AsRef<str>, func: F) -> Self {
Self {
bin: bin.as_ref().to_string(),
args: Vec::new(),
func: Some(func),
}
}
pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
self.args.push(arg.as_ref().to_string());
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for arg in args {
self.arg(arg.as_ref());
}
self
}
pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
let mut cmd = std::process::Command::new(&self.bin);
let setter = |cmd: &mut std::process::Command| {
cmd.args(&self.args);
let piped_out = std::process::Stdio::piped();
let piped_err = std::process::Stdio::piped();
cmd.stdout(piped_out);
cmd.stderr(piped_err);
};
setter(&mut cmd);
match cmd.spawn() {
Ok(child) => Ok(FallbackChild::new_process(child)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
let _ = self.func.take();
Err(e)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
setter(&mut cmd);
cmd.env(COMMAND_ALTERNATE_ENV_VAR, &self.bin);
let child = cmd.spawn()?;
Ok(FallbackChild::new_process(child))
}
Err(e) => Err(e),
}
}
}
pub enum FallbackChild {
Process(std::process::Child),
Thread(std::thread::JoinHandle<FallbackOutput>),
}
impl FallbackChild {
fn new_process(child: std::process::Child) -> Self {
FallbackChild::Process(child)
}
#[allow(unused)]
fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
FallbackChild::Thread(handle)
}
pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
match self {
FallbackChild::Process(child) => {
let output = child.wait_with_output()?;
Ok(FallbackOutput {
stdout: output.stdout,
stderr: output.stderr,
success: output.status.success(),
})
}
FallbackChild::Thread(handle) => {
let out = handle.join().expect("Thread panicked");
Ok(out)
}
}
}
}
pub struct FallbackOutput {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub success: bool,
}
impl CommandLock {
pub fn acquire() -> eyre::Result<Self> {
let lock_path = get_temp_lock_filepath();
if let Some(parent) = Path::new(&lock_path).parent() {
std::fs::create_dir_all(parent).wrap_err_with(|| {
format!("Failed to create temp lock dir: {}", parent.display())
})?;
}
let lock_file = File::create(&lock_path)
.wrap_err_with(|| format!("Failed to create lock file: {lock_path}"))?;
lock_file
.lock_exclusive()
.wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
Ok(Self(lock_file))
}
}
impl Drop for CommandLock {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
fn get_temp_filepath() -> String {
let mut builder = TempFileBuilder::new();
let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
builder.prefix(&prefix);
builder.suffix(".log");
#[cfg(windows)]
let builder = builder.tempfile_in(dirs::data_local_dir().unwrap().join("Temp"));
#[cfg(unix)]
let builder = builder.tempfile_in("/tmp");
let file = builder.expect("Failed to create temp log file");
let (_file, path) = file.keep().expect("Failed to persist temp log file");
path.to_string_lossy().into_owned()
}
fn get_temp_lock_filepath() -> String {
#[cfg(windows)]
return dirs::data_local_dir()
.unwrap()
.join("Temp")
.join(env!("CARGO_PKG_NAME"))
.join("command.lock")
.to_string_lossy()
.into();
#[cfg(unix)]
return Path::new("/tmp")
.join(env!("CARGO_PKG_NAME"))
.join("command.lock")
.to_string_lossy()
.into_owned();
}
pub fn check_gag() -> bool {
pub fn check_gag() -> Option<()> {
let gag = gag::Redirect::stdout(
std::fs::OpenOptions::new()
.truncate(true)
.read(true)
.create(true)
.write(true)
.open(get_temp_filepath())
.ok()?,
)
.ok()?;
const WHITE_SPACE: &str = " \t\n\r";
print!("{WHITE_SPACE}");
std::io::Write::flush(&mut std::io::stdout()).ok()?;
let mut stdout = gag.into_inner();
let mut buf = String::new();
stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
stdout.read_to_string(&mut buf).ok()?;
Some(if buf.contains(WHITE_SPACE) {
()
} else {
return None;
})
}
check_gag().is_some()
}
#[cfg(test)]
mod tests {
use super::*;
static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn test_fallback_command() {
if DISABLE_FALLBACK {
return;
}
let _lock = MUTEX.lock().unwrap();
if !check_gag() {
return;
}
let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
println!("Fallback function called with args: {:?}", args);
0
});
cmd.arg("arg1").arg("arg2");
let child = cmd.spawn().expect("Failed to spawn command");
let output = child.wait_with_output().expect("Failed to get output");
assert!(output.success);
let stdout_str = String::from_utf8_lossy(&output.stdout);
assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
drop(_lock);
}
#[cfg(feature = "fallback")]
#[test]
fn test_fallback_wasm_merge() {
let _lock = MUTEX.lock().unwrap();
if !check_gag() {
return;
}
let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
wasm_merge_sys::run_wasm_merge(&args)
});
cmd.arg("--help");
let child = cmd.spawn().expect("Failed to spawn command");
let output = child.wait_with_output().expect("Failed to get output");
assert!(output.success);
let stdout_str = String::from_utf8_lossy(&output.stdout);
panic!("Output: {}", stdout_str);
drop(_lock);
}
}