wasi_virt_layer_cli/
fallback_command.rs1use std::{
2 fs::File,
3 io::{Read as _, Seek as _, Write as _},
4};
5
6use eyre::Context as _;
7use fs2::FileExt as _;
8use tempfile::Builder as TempFileBuilder;
9
10pub(crate) const COMMAND_ALTERNATE_ENV_VAR: &str = "WASI_VIRT_LAYER_FALLBACK_ALTERNATE_COMMAND";
11
12#[allow(unused)]
13pub(crate) fn wasm_opt(args: &[String]) -> i32 {
14 #[cfg(feature = "fallback")]
15 {
16 if args
17 .iter()
18 .any(|arg| arg.starts_with("--no-inline=__wvl_reactor_initialize"))
19 {
20 eprintln!(
24 "threaded reactor optimization requires native wasm-opt with --no-inline support; install wasm-opt or use --dev"
25 );
26 return 1;
27 }
28
29 if args.iter().any(|arg| arg == "--version") {
30 println!("wasm-opt fallback");
31 return 0;
32 }
33
34 if args.iter().any(|arg| {
35 matches!(
36 arg.as_str(),
37 "--enable-shared-everything" | "--enable-multimemory"
38 )
39 }) {
40 if let Some(output_index) = args.iter().position(|arg| arg == "--output")
41 && let Some(input) = args[..output_index]
42 .iter()
43 .rev()
44 .find(|arg| !arg.starts_with('-'))
45 && let Some(output) = args.get(output_index + 1)
46 {
47 return match std::fs::copy(input, output) {
48 Ok(_) => 0,
49 Err(err) => {
50 eprintln!("wasm-opt fallback failed: {err}");
51 1
52 }
53 };
54 }
55 }
56
57 let mut command = wasm_opt::integration::Command::new("wasm-opt");
58 command.args(args.iter().skip(1));
59
60 match wasm_opt::integration::run_from_command_args(command) {
61 Ok(()) => 0,
62 Err(err) => {
63 eprintln!("wasm-opt fallback failed: {err}");
64 1
65 }
66 }
67 }
68 #[cfg(not(feature = "fallback"))]
69 {
70 eprintln!("wasm-opt fallback is not enabled");
71 1
72 }
73}
74
75fn fake_fallback(args: &[String]) -> i32 {
76 unimplemented!("This is a fake fallback function. It should never be called. Args: {args:?}");
77}
78
79pub fn get_fallback_command(
81 bin: impl AsRef<str>,
82) -> FallbackCommand<impl FnOnce(&[String]) -> i32 + Send + 'static> {
83 match bin.as_ref() {
84 "wasm-opt" => FallbackCommand::new("wasm-opt", fake_fallback),
85 _ => panic!("Unsupported fallback command specified: {}", bin.as_ref()),
86 }
87}
88
89pub struct FallbackCommand<F>
91where
92 F: FnOnce(&[String]) -> i32 + Send + 'static,
93{
94 pub bin: String,
96 pub args: Vec<String>,
98 pub func: Option<F>,
100}
101
102const DISABLE_FALLBACK: bool = false;
103
104pub struct CommandLock {
106 locks: Vec<(File, String)>,
107}
108
109impl<F> FallbackCommand<F>
110where
111 F: FnOnce(&[String]) -> i32 + Send + 'static,
112{
113 pub fn new(bin: impl AsRef<str>, func: F) -> Self {
115 Self {
116 bin: bin.as_ref().to_string(),
117 args: Vec::new(),
118 func: Some(func),
119 }
120 }
121
122 pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
124 self.args.push(arg.as_ref().to_string());
125 self
126 }
127
128 pub fn args<I, S>(&mut self, args: I) -> &mut Self
130 where
131 I: IntoIterator<Item = S>,
132 S: AsRef<str>,
133 {
134 for arg in args {
135 self.arg(arg.as_ref());
136 }
137 self
138 }
139
140 pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
142 let mut cmd = std::process::Command::new(&self.bin);
143 let setter = |cmd: &mut std::process::Command| {
144 cmd.args(&self.args);
145 let piped_out = std::process::Stdio::piped();
146 let piped_err = std::process::Stdio::piped();
147 cmd.stdout(piped_out);
148 cmd.stderr(piped_err);
149 };
150 setter(&mut cmd);
151 match cmd.spawn() {
152 Ok(child) => Ok(FallbackChild::new_process(child)),
153 Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
154 let _ = self.func.take();
155 Err(e)
156 }
157 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
158 let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
191 setter(&mut cmd);
192 cmd.env(COMMAND_ALTERNATE_ENV_VAR, &self.bin);
193 let child = cmd.spawn()?;
194 Ok(FallbackChild::new_process(child))
195 }
196 Err(e) => Err(e),
197 }
198 }
199}
200
201pub enum FallbackChild {
203 Process(std::process::Child),
205 Thread(std::thread::JoinHandle<FallbackOutput>),
207}
208
209impl FallbackChild {
210 fn new_process(child: std::process::Child) -> Self {
211 FallbackChild::Process(child)
212 }
213
214 #[allow(unused)]
215 fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
216 FallbackChild::Thread(handle)
217 }
218
219 pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
221 match self {
222 FallbackChild::Process(child) => {
223 let output = child.wait_with_output()?;
224 Ok(FallbackOutput {
225 stdout: output.stdout,
226 stderr: output.stderr,
227 success: output.status.success(),
228 })
229 }
230 FallbackChild::Thread(handle) => {
231 let out = handle.join().expect("Thread panicked");
232 Ok(out)
233 }
234 }
235 }
236}
237
238pub struct FallbackOutput {
240 pub stdout: Vec<u8>,
242 pub stderr: Vec<u8>,
244 pub success: bool,
246}
247
248impl CommandLock {
249 pub fn acquire(ids: &[String]) -> eyre::Result<Self> {
251 let mut sorted_ids = ids.to_vec();
252 sorted_ids.sort();
253 sorted_ids.dedup();
254
255 let temp_dir = std::env::temp_dir().join(env!("CARGO_PKG_NAME"));
257 std::fs::create_dir_all(&temp_dir).wrap_err("Failed to create temp lock directory")?;
258
259 let master_path = temp_dir.join("master.lock");
261 let master_file = File::options()
262 .read(true)
263 .write(true)
264 .create(true)
265 .open(&master_path)
266 .wrap_err_with(|| {
267 format!("Failed to open master lock file: {}", master_path.display())
268 })?;
269
270 master_file
271 .lock_exclusive()
272 .wrap_err("Failed to acquire master lock")?;
273
274 let mut locks = Vec::new();
275
276 for id in sorted_ids {
278 let hash = {
279 use std::hash::{Hash, Hasher};
280 let mut hasher = std::collections::hash_map::DefaultHasher::new();
281 id.hash(&mut hasher);
282 format!("{:x}", hasher.finish())
283 };
284
285 let lock_path = get_temp_lock_filepath(&hash);
286 let lock_file = File::options()
287 .read(true)
288 .write(true)
289 .create(true)
290 .open(&lock_path)
291 .wrap_err_with(|| format!("Failed to open lock file: {lock_path}"))?;
292
293 if let Err(_) = lock_file.try_lock_exclusive() {
294 let mut pid_str = String::new();
295 let mut file = &lock_file;
296 let _ = file.read_to_string(&mut pid_str);
297 let pid_info = if pid_str.is_empty() {
298 String::new()
299 } else {
300 format!(" (held by PID {})", pid_str.trim())
301 };
302
303 eprintln!("Waiting for command lock for {} {}...", id, pid_info);
304
305 lock_file
309 .lock_exclusive()
310 .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
311 }
312
313 let mut file = &lock_file;
315 let _ = file.set_len(0);
316 let _ = file.seek(std::io::SeekFrom::Start(0));
317 let _ = write!(file, "{}", std::process::id());
318 let _ = file.flush();
319
320 locks.push((lock_file, lock_path));
321 }
322
323 let _ = master_file.unlock();
325
326 Ok(Self { locks })
327 }
328}
329
330impl Drop for CommandLock {
331 fn drop(&mut self) {
332 for (file, _) in &mut self.locks {
333 let _ = file.unlock();
334 }
335 }
336}
337
338fn get_temp_filepath() -> String {
339 let mut builder = TempFileBuilder::new();
340 let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
341 builder.prefix(&prefix);
342 builder.suffix(".log");
343
344 let builder = builder.tempfile_in(std::env::temp_dir());
345
346 let file = builder.expect("Failed to create temp log file");
347 let (_file, path) = file.keep().expect("Failed to persist temp log file");
348
349 path.to_string_lossy().into_owned()
350}
351
352fn get_temp_lock_filepath(hash: &str) -> String {
353 std::env::temp_dir()
354 .join(env!("CARGO_PKG_NAME"))
355 .join(format!("command_{}.lock", hash))
356 .to_string_lossy()
357 .into_owned()
358}
359
360pub fn check_gag() -> bool {
362 pub fn check_gag() -> Option<()> {
363 let gag = gag::Redirect::stdout(
364 std::fs::OpenOptions::new()
365 .truncate(true)
366 .read(true)
367 .create(true)
368 .write(true)
369 .open(get_temp_filepath())
370 .ok()?,
371 )
372 .ok()?;
373
374 const WHITE_SPACE: &str = " \t\n\r";
375
376 print!("{WHITE_SPACE}");
377 std::io::Write::flush(&mut std::io::stdout()).ok()?;
378
379 let mut stdout = gag.into_inner();
380 let mut buf = String::new();
381 stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
382 stdout.read_to_string(&mut buf).ok()?;
383
384 Some(if buf.contains(WHITE_SPACE) {
385 ()
386 } else {
387 return None;
388 })
389 }
390
391 check_gag().is_some()
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
399
400 #[ignore = "self-call fallback cannot execute an arbitrary test closure"]
401 #[test]
402 fn test_fallback_command() {
405 if DISABLE_FALLBACK {
406 return;
407 }
408
409 let _lock = MUTEX.lock().unwrap();
410 if !check_gag() {
411 return;
412 }
413
414 let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
415 println!("Fallback function called with args: {:?}", args);
416 0
417 });
418 cmd.arg("arg1").arg("arg2");
419
420 let child = cmd.spawn().expect("Failed to spawn command");
421 let output = child.wait_with_output().expect("Failed to get output");
422
423 assert!(output.success);
424 let stdout_str = String::from_utf8_lossy(&output.stdout);
425 assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
426
427 drop(_lock);
428 }
429}