detect_wasi/
lib.rs

1use std::{
2    fs::File,
3    io::{Result, Write},
4    process::Command,
5};
6#[cfg(unix)]
7use std::{fs::Permissions, os::unix::fs::PermissionsExt};
8
9use tempfile::tempdir;
10
11const WASI_PROGRAM: &[u8] = include_bytes!("miniwasi.wasm");
12
13/// Detect the ability to run WASI
14///
15/// This attempts to run a small embedded WASI program, and returns true if no errors happened.
16/// Errors returned by the `Result` are I/O errors from the establishment of the context, not
17/// errors from the run attempt.
18///
19/// On Linux, you can configure your system to run WASI programs using a binfmt directive. Under
20/// systemd, write the below to `/etc/binfmt.d/wasi.conf`, with `/usr/bin/wasmtime` optionally
21/// replaced with the path to your WASI runtime of choice:
22///
23/// ```plain
24/// :wasi:M::\x00asm::/usr/bin/wasmtime:
25/// ```
26pub fn detect_wasi_runability() -> Result<bool> {
27    let progdir = tempdir()?;
28    let prog = progdir.path().join("miniwasi.wasm");
29
30    {
31        let mut progfile = File::create(&prog)?;
32        progfile.write_all(WASI_PROGRAM)?;
33
34        #[cfg(unix)]
35        progfile.set_permissions(Permissions::from_mode(0o777))?;
36    }
37
38    match Command::new(prog).output() {
39        Ok(out) => Ok(out.status.success() && out.stdout.is_empty() && out.stderr.is_empty()),
40        Err(_) => Ok(false),
41    }
42}