You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

259 lines
7.8 KiB

use anyhow::{bail, Result};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Output};
use tempfile::NamedTempFile;
// Run the wasmtime CLI with the provided args and return the `Output`.
fn run_wasmtime_for_output(args: &[&str]) -> Result<Output> {
let runner = std::env::vars()
.filter(|(k, _v)| k.starts_with("CARGO_TARGET") && k.ends_with("RUNNER"))
.next();
let mut me = std::env::current_exe()?;
me.pop(); // chop off the file name
me.pop(); // chop off `deps`
me.push("wasmtime");
// If we're running tests with a "runner" then we might be doing something
// like cross-emulation, so spin up the emulator rather than the tests
// itself, which may not be natively executable.
let mut cmd = if let Some((_, runner)) = runner {
let mut parts = runner.split_whitespace();
let mut cmd = Command::new(parts.next().unwrap());
for arg in parts {
cmd.arg(arg);
}
cmd.arg(&me);
cmd
} else {
Command::new(&me)
};
cmd.args(args).output().map_err(Into::into)
}
// Run the wasmtime CLI with the provided args and, if it succeeds, return
// the standard output in a `String`.
fn run_wasmtime(args: &[&str]) -> Result<String> {
let output = run_wasmtime_for_output(args)?;
if !output.status.success() {
bail!(
"Failed to execute wasmtime with: {:?}\n{}",
args,
String::from_utf8_lossy(&output.stderr)
);
}
Ok(String::from_utf8(output.stdout).unwrap())
}
fn build_wasm(wat_path: impl AsRef<Path>) -> Result<NamedTempFile> {
let mut wasm_file = NamedTempFile::new()?;
let wasm = wat::parse_file(wat_path)?;
wasm_file.write(&wasm)?;
Ok(wasm_file)
}
// Very basic use case: compile binary wasm file and run specific function with arguments.
#[test]
fn run_wasmtime_simple() -> Result<()> {
let wasm = build_wasm("tests/wasm/simple.wat")?;
run_wasmtime(&[
"run",
wasm.path().to_str().unwrap(),
"--invoke",
"simple",
"--disable-cache",
"4",
])?;
Ok(())
}
// Wasmtime shakk when not enough arguments were provided.
#[test]
fn run_wasmtime_simple_fail_no_args() -> Result<()> {
let wasm = build_wasm("tests/wasm/simple.wat")?;
assert!(
run_wasmtime(&[
"run",
wasm.path().to_str().unwrap(),
"--disable-cache",
"--invoke",
"simple",
])
.is_err(),
"shall fail"
);
Ok(())
}
// Running simple wat
#[test]
fn run_wasmtime_simple_wat() -> Result<()> {
let wasm = build_wasm("tests/wasm/simple.wat")?;
run_wasmtime(&[
"run",
wasm.path().to_str().unwrap(),
"--invoke",
"simple",
"--disable-cache",
"4",
])?;
Ok(())
}
// Running a wat that traps.
#[test]
fn run_wasmtime_unreachable_wat() -> Result<()> {
let wasm = build_wasm("tests/wasm/unreachable.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
assert_ne!(output.stderr, b"");
assert_eq!(output.stdout, b"");
assert!(!output.status.success());
let code = output
.status
.code()
.expect("wasmtime process should exit normally");
// Test for the specific error code Wasmtime uses to indicate a trap return.
#[cfg(unix)]
assert_eq!(code, 128 + libc::SIGABRT);
#[cfg(windows)]
assert_eq!(code, 3);
Ok(())
}
// Run a simple WASI hello world, snapshot0 edition.
#[test]
fn hello_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/wasm/hello_wasi_snapshot0.wat")?;
let stdout = run_wasmtime(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
assert_eq!(stdout, "Hello, world!\n");
Ok(())
}
// Run a simple WASI hello world, snapshot1 edition.
#[test]
fn hello_wasi_snapshot1() -> Result<()> {
let wasm = build_wasm("tests/wasm/hello_wasi_snapshot1.wat")?;
let stdout = run_wasmtime(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
assert_eq!(stdout, "Hello, world!\n");
Ok(())
}
Implement interrupting wasm code, reimplement stack overflow (#1490) * Implement interrupting wasm code, reimplement stack overflow This commit is a relatively large change for wasmtime with two main goals: * Primarily this enables interrupting executing wasm code with a trap, preventing infinite loops in wasm code. Note that resumption of the wasm code is not a goal of this commit. * Additionally this commit reimplements how we handle stack overflow to ensure that host functions always have a reasonable amount of stack to run on. This fixes an issue where we might longjmp out of a host function, skipping destructors. Lots of various odds and ends end up falling out in this commit once the two goals above were implemented. The strategy for implementing this was also lifted from Spidermonkey and existing functionality inside of Cranelift. I&#39;ve tried to write up thorough documentation of how this all works in `crates/environ/src/cranelift.rs` where gnarly-ish bits are. A brief summary of how this works is that each function and each loop header now checks to see if they&#39;re interrupted. Interrupts and the stack overflow check are actually folded into one now, where function headers check to see if they&#39;ve run out of stack and the sentinel value used to indicate an interrupt, checked in loop headers, tricks functions into thinking they&#39;re out of stack. An interrupt is basically just writing a value to a location which is read by JIT code. When interrupts are delivered and what triggers them has been left up to embedders of the `wasmtime` crate. The `wasmtime::Store` type has a method to acquire an `InterruptHandle`, where `InterruptHandle` is a `Send` and `Sync` type which can travel to other threads (or perhaps even a signal handler) to get notified from. It&#39;s intended that this provides a good degree of flexibility when interrupting wasm code. Note though that this does have a large caveat where interrupts don&#39;t work when you&#39;re interrupting host code, so if you&#39;ve got a host import blocking for a long time an interrupt won&#39;t actually be received until the wasm starts running again. Some fallout included from this change is: * Unix signal handlers are no longer registered with `SA_ONSTACK`. Instead they run on the native stack the thread was already using. This is possible since stack overflow isn&#39;t handled by hitting the guard page, but rather it&#39;s explicitly checked for in wasm now. Native stack overflow will continue to abort the process as usual. * Unix sigaltstack management is now no longer necessary since we don&#39;t use it any more. * Windows no longer has any need to reset guard pages since we no longer try to recover from faults on guard pages. * On all targets probestack intrinsics are disabled since we use a different mechanism for catching stack overflow. * The C API has been updated with interrupts handles. An example has also been added which shows off how to interrupt a module. Closes #139 Closes #860 Closes #900 * Update comment about magical interrupt value * Store stack limit as a global value, not a closure * Run rustfmt * Handle review comments * Add a comment about SA_ONSTACK * Use `usize` for type of `INTERRUPTED` * Parse human-readable durations * Bring back sigaltstack handling Allows libstd to print out stack overflow on failure still. * Add parsing and emission of stack limit-via-preamble * Fix new example for new apis * Fix host segfault test in release mode * Fix new doc example
5 years ago
#[test]
fn timeout_in_start() -> Result<()> {
let wasm = build_wasm("tests/wasm/iloop-start.wat")?;
let output = run_wasmtime_for_output(&[
"run",
wasm.path().to_str().unwrap(),
"--wasm-timeout",
"1ms",
"--disable-cache",
])?;
assert!(!output.status.success());
assert_eq!(output.stdout, b"");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("wasm trap: interrupt"),
"bad stderr: {}",
stderr
);
Ok(())
}
#[test]
fn timeout_in_invoke() -> Result<()> {
let wasm = build_wasm("tests/wasm/iloop-invoke.wat")?;
let output = run_wasmtime_for_output(&[
"run",
wasm.path().to_str().unwrap(),
"--wasm-timeout",
"1ms",
"--disable-cache",
])?;
assert!(!output.status.success());
assert_eq!(output.stdout, b"");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("wasm trap: interrupt"),
"bad stderr: {}",
stderr
);
Ok(())
}
// Exit with a valid non-zero exit code, snapshot0 edition.
#[test]
fn exit2_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit2_wasi_snapshot0.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
assert_eq!(output.status.code().unwrap(), 2);
Ok(())
}
// Exit with a valid non-zero exit code, snapshot1 edition.
#[test]
fn exit2_wasi_snapshot1() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit2_wasi_snapshot1.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
assert_eq!(output.status.code().unwrap(), 2);
Ok(())
}
// Exit with a valid non-zero exit code, snapshot0 edition.
#[test]
fn exit125_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit125_wasi_snapshot0.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 1);
} else {
assert_eq!(output.status.code().unwrap(), 125);
}
Ok(())
}
// Exit with a valid non-zero exit code, snapshot1 edition.
#[test]
fn exit125_wasi_snapshot1() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit125_wasi_snapshot1.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 1);
} else {
assert_eq!(output.status.code().unwrap(), 125);
}
Ok(())
}
// Exit with an invalid non-zero exit code, snapshot0 edition.
#[test]
fn exit126_wasi_snapshot0() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit126_wasi_snapshot0.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 3);
} else {
assert_eq!(output.status.code().unwrap(), 128 + libc::SIGABRT);
}
assert!(output.stdout.is_empty());
assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
Ok(())
}
// Exit with an invalid non-zero exit code, snapshot1 edition.
#[test]
fn exit126_wasi_snapshot1() -> Result<()> {
let wasm = build_wasm("tests/wasm/exit126_wasi_snapshot1.wat")?;
let output = run_wasmtime_for_output(&[wasm.path().to_str().unwrap(), "--disable-cache"])?;
if cfg!(windows) {
assert_eq!(output.status.code().unwrap(), 3);
} else {
assert_eq!(output.status.code().unwrap(), 128 + libc::SIGABRT);
}
assert!(output.stdout.is_empty());
assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
Ok(())
}