Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

158 KB
Raw Blame
#![cfg(not(miri))]

use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::{Command, ExitStatus, Output, Stdio};
use tempfile::{NamedTempFile, TempDir};
use wasmtime::{Result, bail};

pub fn wasmtime(args: &[&str]) -> Result<Command> {
    let mut cmd = get_wasmtime_command()?;
    cmd.args(args);
    Ok(cmd)
}

/// Get the Wasmtime CLI as a [Command].
pub fn get_wasmtime_command() -> Result<Command> {
    let mut cmd = wasmtime_test_util::command(get_wasmtime_path());

    // Disable the on-by-default CLI cache since most of these small tests don't
    // really benefit, the cache has historically been a bit buggy with
    // non-release builds, and we'd otherwise just be polluting it.
    cmd.env("WASMTIME_CODEGEN_CACHE", "n");

    Ok(cmd)
}

fn get_wasmtime_path() -> &'static str {
    env!("CARGO_BIN_EXE_wasmtime")
}

// Run the wasmtime CLI with the provided args and, if it succeeds, return
// the standard output in a `String`.
pub fn run_wasmtime(args: &[&str]) -> Result<String> {
    run_cmd(&mut wasmtime(args)?)
}

// Run the wasmtime CLI with the provided args and, if it succeeds, return
// the standard output in a `String`.
pub fn run_cmd(cmd: &mut Command) -> Result<String> {
    let output = cmd.output()?;
    if !output.status.success() {
        bail!(
            "Failed to execute {cmd:?}\nstatus: {}\n{}",
            output.status,
            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<()> {
    run_wasmtime(&[
        "run",
        "--invoke",
        "simple",
        "tests/all/cli_tests/simple.wat",
        "4",
    ])?;
    Ok(())
}

// Wasmtime shall fail when not enough arguments were provided.
#[test]
fn run_wasmtime_simple_fail_no_args() -> Result<()> {
    assert!(
        run_wasmtime(&[
            "run",
            "--invoke",
            "simple",
            "tests/all/cli_tests/simple.wat"
        ])
        .is_err(),
        "shall fail"
    );
    Ok(())
}

#[test]
fn run_coredump_smoketest() -> Result<()> {
    let coredump_file = NamedTempFile::new()?;
    let coredump_arg = format!("-Dcoredump={}", coredump_file.path().display());
    let err = run_wasmtime(&[
        "run",
        "--invoke",
        "a",
        &coredump_arg,
        "tests/all/cli_tests/coredump_smoketest.wat",
    ])
    .unwrap_err();
    assert!(err.to_string().contains(&format!(
        "core dumped at {}",
        coredump_file.path().display()
    )));
    Ok(())
}

#[test]
fn run_coredump_during_instantiation() -> Result<()> {
    let coredump_file = NamedTempFile::new()?;
    let coredump_arg = format!("-Dcoredump={}", coredump_file.path().display());
    let err = run_wasmtime(&[
        "run",
        &coredump_arg,
        "tests/all/cli_tests/coredump_start_trap.wat",
    ])
    .unwrap_err();
    assert!(err.to_string().contains(&format!(
        "core dumped at {}",
        coredump_file.path().display()
    )));
    Ok(())
}

// Running simple wat
#[test]
fn run_wasmtime_simple_wat() -> Result<()> {
    run_wasmtime(&[
        "run",
        "--invoke",
        "simple",
        "tests/all/cli_tests/simple.wat",
        "4",
    ])?;
    assert_eq!(
        run_wasmtime(&[
            "run",
            "--invoke",
            "get_f32",
            "tests/all/cli_tests/simple.wat",
        ])?,
        "100\n"
    );
    assert_eq!(
        run_wasmtime(&[
            "run",
            "--invoke",
            "get_f64",
            "tests/all/cli_tests/simple.wat",
        ])?,
        "100\n"
    );
    Ok(())
}

// Running a wat that traps.
#[test]
fn run_wasmtime_unreachable_wat() -> Result<()> {
    let output = wasmtime(&["tests/all/cli_tests/unreachable.wat"])?.output()?;

    assert_ne!(output.stderr, b"");
    assert_eq!(output.stdout, b"");

    assert_trap_code(&output.status);
    Ok(())
}

fn assert_trap_code(status: &ExitStatus) {
    let code = 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);
}

// Run a simple WASI hello world, snapshot0 edition.
#[test]
fn hello_wasi_snapshot0() -> Result<()> {
    let output = wasmtime(&["tests/all/cli_tests/hello_wasi_snapshot0.wat"])?.output()?;
    assert!(!output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stderr)
            .contains("unknown import: `wasi_unstable::proc_exit`")
    );

    let stdout = run_wasmtime(&["-Spreview0", "tests/all/cli_tests/hello_wasi_snapshot0.wat"])?;
    assert_eq!(stdout, "Hello, world!\n");
    Ok(())
}

// Run a simple WASI hello world, snapshot1 edition.
#[test]
fn hello_wasi_snapshot1() -> Result<()> {
    let stdout = run_wasmtime(&["tests/all/cli_tests/hello_wasi_snapshot1.wat"])?;
    assert_eq!(stdout, "Hello, world!\n");
    Ok(())
}

#[test]
fn timeout_in_start() -> Result<()> {
    let output = wasmtime(&[
        "run",
        "-Wtimeout=1ms",
        "tests/all/cli_tests/iloop-start.wat",
    ])?
    .output()?;
    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 output = wasmtime(&[
        "run",
        "-Wtimeout=1ms",
        "tests/all/cli_tests/iloop-invoke.wat",
    ])?
    .output()?;
    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 output =
        wasmtime(&["-Spreview0", "tests/all/cli_tests/exit2_wasi_snapshot0.wat"])?.output()?;
    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 output = wasmtime(&["tests/all/cli_tests/exit2_wasi_snapshot1.wat"])?.output()?;
    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 output = wasmtime(&[
        "-Spreview0",
        "tests/all/cli_tests/exit125_wasi_snapshot0.wat",
    ])?
    .output()?;
    dbg!(&output);
    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 output = wasmtime(&["tests/all/cli_tests/exit125_wasi_snapshot1.wat"])?.output()?;
    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 output = wasmtime(&[
        "-Spreview0",
        "tests/all/cli_tests/exit126_wasi_snapshot0.wat",
    ])?
    .output()?;
    assert_eq!(output.status.code().unwrap(), 1);
    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 output = wasmtime(&["tests/all/cli_tests/exit126_wasi_snapshot1.wat"])?.output()?;
    assert_eq!(output.status.code().unwrap(), 1);
    assert!(output.stdout.is_empty());
    assert!(String::from_utf8_lossy(&output.stderr).contains("invalid exit status"));
    Ok(())
}

// Run a minimal command program.
#[test]
fn minimal_command() -> Result<()> {
    let stdout = run_wasmtime(&["tests/all/cli_tests/minimal-command.wat"])?;
    assert_eq!(stdout, "");
    Ok(())
}

// Run a minimal reactor program.
#[test]
fn minimal_reactor() -> Result<()> {
    let stdout = run_wasmtime(&["tests/all/cli_tests/minimal-reactor.wat"])?;
    assert_eq!(stdout, "");
    Ok(())
}

// Attempt to call invoke on a command.
#[test]
fn command_invoke() -> Result<()> {
    run_wasmtime(&[
        "run",
        "--invoke",
        "_start",
        "tests/all/cli_tests/minimal-command.wat",
    ])?;
    Ok(())
}

// Attempt to call invoke on a command.
#[test]
fn reactor_invoke() -> Result<()> {
    run_wasmtime(&[
        "run",
        "--invoke",
        "_initialize",
        "tests/all/cli_tests/minimal-reactor.wat",
    ])?;
    Ok(())
}

// Run the greeter test, which runs a preloaded reactor and a command.
#[test]
fn greeter() -> Result<()> {
    let stdout = run_wasmtime(&[
        "run",
        "--preload",
        "reactor=tests/all/cli_tests/greeter_reactor.wat",
        "tests/all/cli_tests/greeter_command.wat",
    ])?;
    assert_eq!(
        stdout,
        "Hello _initialize\nHello _start\nHello greet\nHello done\n"
    );
    Ok(())
}

// Run the greeter test, but this time preload a command.
#[test]
fn greeter_preload_command() -> Result<()> {
    let stdout = run_wasmtime(&[
        "run",
        "--preload",
        "reactor=tests/all/cli_tests/hello_wasi_snapshot1.wat",
        "tests/all/cli_tests/greeter_reactor.wat",
    ])?;
    assert_eq!(stdout, "Hello _initialize\n");
    Ok(())
}

// Run the greeter test, which runs a preloaded reactor and a command.
#[test]
fn greeter_preload_callable_command() -> Result<()> {
    let stdout = run_wasmtime(&[
        "run",
        "--preload",
        "reactor=tests/all/cli_tests/greeter_callable_command.wat",
        "tests/all/cli_tests/greeter_command.wat",
    ])?;
    assert_eq!(stdout, "Hello _start\nHello callable greet\nHello done\n");
    Ok(())
}

// Ensure successful WASI exit call with FPR saving frames on stack for Windows x64
// See https://github.com/bytecodealliance/wasmtime/issues/1967
#[test]
fn exit_with_saved_fprs() -> Result<()> {
    let stdout = run_wasmtime(&["tests/all/cli_tests/exit_with_saved_fprs.wat"])?;
    assert!(stdout.is_empty());
    Ok(())
}

#[test]
fn run_cwasm() -> Result<()> {
    let td = TempDir::new()?;
    let cwasm = td.path().join("foo.cwasm");
    let stdout = run_wasmtime(&[
        "compile",
        "tests/all/cli_tests/simple.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?;
    assert_eq!(stdout, "");
    let stdout = run_wasmtime(&["run", "--allow-precompiled", cwasm.to_str().unwrap()])?;
    assert_eq!(stdout, "");
    Ok(())
}

#[cfg(unix)]
#[test]
fn hello_wasi_snapshot0_from_stdin() -> Result<()> {
    let stdout = run_cmd(
        wasmtime(&["-Spreview0", "-"])?
            .stdin(File::open("tests/all/cli_tests/hello_wasi_snapshot0.wat")?),
    )?;
    assert_eq!(stdout, "Hello, world!\n");
    Ok(())
}

#[test]
fn specify_env() -> Result<()> {
    // By default no env is inherited
    let output = run_cmd(
        wasmtime(&["run", "tests/all/cli_tests/print_env.wat"])?
            .env("THIS_WILL_NOT", "show up in the output"),
    )?;
    assert_eq!(output, "");

    // Specify a single env var
    let output = run_wasmtime(&[
        "run",
        "--env",
        "FOO=bar",
        "tests/all/cli_tests/print_env.wat",
    ])?;
    assert_eq!(output, "FOO=bar\n");

    // Inherit a single env var
    let output = run_cmd(
        wasmtime(&["run", "--env", "FOO", "tests/all/cli_tests/print_env.wat"])?.env("FOO", "bar"),
    )?;
    assert_eq!(output, "FOO=bar\n");

    // Inherit a nonexistent env var
    run_wasmtime(&[
        "run",
        "--env",
        "SURELY_THIS_ENV_VAR_DOES_NOT_EXIST_ANYWHERE_RIGHT",
        "tests/all/cli_tests/print_env.wat",
    ])?;

    // Inherit all env vars
    let output = run_cmd(
        wasmtime(&["run", "-Sinherit-env", "tests/all/cli_tests/print_env.wat"])?.env("FOO", "bar"),
    )?;
    assert!(output.contains("FOO=bar"), "bad output: {output}");

    Ok(())
}

#[cfg(unix)]
#[test]
fn run_cwasm_from_stdin() -> Result<()> {
    use std::process::Stdio;

    let td = TempDir::new()?;
    let cwasm = td.path().join("foo.cwasm");
    let stdout = run_wasmtime(&[
        "compile",
        "tests/all/cli_tests/simple.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?;
    assert_eq!(stdout, "");

    // If stdin is literally the file itself then that should work
    let args: &[&str] = &["run", "--allow-precompiled", "-"];
    run_cmd(wasmtime(args)?.stdin(File::open(&cwasm)?))?;

    // If stdin is a pipe, that should also work
    let input = std::fs::read(&cwasm)?;
    let mut child = wasmtime(args)?
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut stdin = child.stdin.take().unwrap();
    let t = std::thread::spawn(move || {
        let _ = stdin.write_all(&input);
    });
    let output = child.wait_with_output()?;
    assert!(output.status.success());
    t.join().unwrap();
    Ok(())
}

#[test]
fn wasm_flags() -> Result<()> {
    // Any argument after the wasm module should be interpreted as for the
    // command itself
    let stdout = run_wasmtime(&[
        "run",
        "--",
        "tests/all/cli_tests/print-arguments.wat",
        "--argument",
        "-for",
        "the",
        "command",
    ])?;
    assert_eq!(
        stdout,
        "\
            print-arguments.wat\n\
            --argument\n\
            -for\n\
            the\n\
            command\n\
        "
    );
    let stdout = run_wasmtime(&["run", "--", "tests/all/cli_tests/print-arguments.wat", "-"])?;
    assert_eq!(
        stdout,
        "\
            print-arguments.wat\n\
            -\n\
        "
    );
    let stdout = run_wasmtime(&["run", "--", "tests/all/cli_tests/print-arguments.wat", "--"])?;
    assert_eq!(
        stdout,
        "\
            print-arguments.wat\n\
            --\n\
        "
    );
    let stdout = run_wasmtime(&[
        "run",
        "--",
        "tests/all/cli_tests/print-arguments.wat",
        "--",
        "--",
        "-a",
        "b",
    ])?;
    assert_eq!(
        stdout,
        "\
            print-arguments.wat\n\
            --\n\
            --\n\
            -a\n\
            b\n\
        "
    );
    Ok(())
}

#[test]
fn name_same_as_builtin_command() -> Result<()> {
    // a bare subcommand shouldn't run successfully
    let output = get_wasmtime_command()?
        .current_dir("tests/all/cli_tests")
        .arg("run")
        .output()?;
    assert!(!output.status.success());

    // a `--` prefix should let everything else get interpreted as a wasm
    // module and arguments, even if the module has a name like `run`
    run_cmd(wasmtime(&["--", "run"])?.current_dir("tests/all/cli_tests"))?;

    // Passing options before the subcommand should work and doesn't require
    // `--` to disambiguate
    run_cmd(wasmtime(&["-Wcomponent-model", "run"])?.current_dir("tests/all/cli_tests"))?;
    Ok(())
}

#[test]
#[cfg(unix)]
fn run_just_stdin_argument() -> Result<()> {
    run_cmd(wasmtime(&["-"])?.stdin(File::open("tests/all/cli_tests/simple.wat")?))?;
    Ok(())
}

#[test]
fn wasm_flags_without_subcommand() -> Result<()> {
    let output = run_cmd(
        wasmtime(&["print-arguments.wat", "-foo", "bar"])?.current_dir("tests/all/cli_tests/"),
    )?;
    assert_eq!(
        output,
        "\
            print-arguments.wat\n\
            -foo\n\
            bar\n\
        "
    );
    Ok(())
}

#[test]
fn wasi_misaligned_pointer() -> Result<()> {
    let output = get_wasmtime_command()?
        .arg("./tests/all/cli_tests/wasi_misaligned_pointer.wat")
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Pointer not aligned"),
        "bad stderr: {stderr}",
    );
    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn hello_with_preview2() -> Result<()> {
    let stdout = run_wasmtime(&["-Spreview2", "tests/all/cli_tests/hello_wasi_snapshot1.wat"])?;
    assert_eq!(stdout, "Hello, world!\n");
    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn component_missing_feature() -> Result<()> {
    let path = "tests/all/cli_tests/empty-component.wat";
    let wasm = build_wasm(path)?;
    let output = get_wasmtime_command()?
        .arg("-Wcomponent-model=n")
        .arg(wasm.path())
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cannot execute a component without `--wasm component-model`"),
        "bad stderr: {stderr}"
    );

    // also tests with raw *.wat input
    let output = get_wasmtime_command()?
        .arg("-Wcomponent-model=n")
        .arg(path)
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cannot execute a component without `--wasm component-model`"),
        "bad stderr: {stderr}"
    );

    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn component_enabled_by_default() -> Result<()> {
    let path = "tests/all/cli_tests/component-basic.wat";
    let wasm = build_wasm(path)?;
    run_wasmtime(&[wasm.path().to_str().unwrap()])?;

    // also tests with raw *.wat input
    run_wasmtime(&[path])?;

    Ok(())
}

#[test]
fn component_invoke_multiple_run_exports() -> Result<()> {
    let path = "tests/all/cli_tests/component-multiple-runs.wat";

    // demonstrate run --invoke can give a useful error message when
    // there are multiple interfaces that export the function name specified
    let output = get_wasmtime_command()?
        .arg("run")
        .arg("-Wcomponent-model")
        .arg("--invoke")
        .arg("run()")
        .arg(path)
        .output()?;
    assert!(
        !output.status.success(),
        "should fail because run() is ambigious for this component"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("Multiple instances contained funcs named `run`, retry with a more specific name: `wasi:cli/[email protected]`, `some:other/one.run`"));

    // test program cli run gives `ok`:
    let stdout = run_wasmtime(&[
        "run",
        "-Wcomponent-model",
        "--invoke",
        "wasi:cli/[email protected]()",
        path,
    ])?;
    assert_eq!(stdout, "ok\n");

    // test program other run gives `err`:
    let stdout = run_wasmtime(&[
        "run",
        "-Wcomponent-model",
        "--invoke",
        "some:other/one.run()",
        path,
    ])?;
    assert_eq!(stdout, "err\n");

    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn component_invoke_map() -> Result<()> {
    let path = "tests/all/cli_tests/component-map.wat";
    let invoke =
        |call: &str| run_wasmtime(&["run", "-Wcomponent-model-map", "--invoke", call, path]);

    // Map arguments are parsed and map results are printed in WAVE, which
    // merges duplicate keys.
    assert_eq!(invoke("echo({})")?, "{}\n");
    assert_eq!(invoke("echo({3: 4, 1: 2, 3: 5,})")?, "{3: 5, 1: 2}\n");
    assert_eq!(invoke("duplicates()")?, "{1: 30, 2: 20}\n");

    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn component_unknown_imports_default() -> Result<()> {
    let path = "tests/all/cli_tests/component-unknown-imports.wat";

    // Every type that has a default comes back with it.
    let stdout = run_wasmtime(&[
        "run",
        "-Wunknown-imports-default",
        "--invoke",
        "defaults()",
        path,
    ])?;
    assert_eq!(
        stdout,
        "(0, 0, \"\", false, '\\u{0}', [], none, ok(0), {a: 0, b: \"\"}, x(0), {}, e1)\n"
    );

    // Resources need handling that a return value does not show: a `borrow`
    // argument must be dropped by the stub, and an `own` argument consumed.
    run_wasmtime(&["run", "-Wunknown-imports-default", path])?;

    // Without the flag the component cannot even be instantiated.
    let output = get_wasmtime_command()?.arg("run").arg(path).output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("a matching implementation was not found in the linker"),
        "bad stderr: {stderr}"
    );

    // `unknown-imports-trap` still traps rather than returning defaults.
    let output = get_wasmtime_command()?
        .arg("run")
        .arg("-Wunknown-imports-trap")
        .arg(path)
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unknown import: `unknown:pkg/iface#make` has not been defined"),
        "bad stderr: {stderr}"
    );

    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model-async"), ignore)]
fn component_unknown_imports_default_async() -> Result<()> {
    let path = "tests/all/cli_tests/component-unknown-imports-async.wat";

    // Async imports are stubbed out, so the component instantiates, but `f`
    // returns a `future`, which has no default value.
    let output = get_wasmtime_command()?
        .args([
            "run",
            "-Wcomponent-model-async",
            "-Wunknown-imports-default",
        ])
        .arg(path)
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unknown import: `f` has no default value")
            && stderr.contains("no default value exists for type `future`"),
        "bad stderr: {stderr}"
    );

    Ok(())
}

// If the text format is invalid then the filename should be mentioned in the
// error message.
#[test]
fn bad_text_syntax() -> Result<()> {
    let output = get_wasmtime_command()?
        .arg("tests/all/cli_tests/bad-syntax.wat")
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--> tests/all/cli_tests/bad-syntax.wat"),
        "bad stderr: {stderr}"
    );
    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn run_basic_component() -> Result<()> {
    let path = "tests/all/cli_tests/component-basic.wat";
    let wasm = build_wasm(path)?;

    // Run both the `*.wasm` binary and the text format
    run_wasmtime(&["-Wcomponent-model", wasm.path().to_str().unwrap()])?;
    run_wasmtime(&["-Wcomponent-model", path])?;

    Ok(())
}

#[test]
#[cfg_attr(not(feature = "component-model"), ignore)]
fn run_precompiled_component() -> Result<()> {
    let td = TempDir::new()?;
    let cwasm = td.path().join("component-basic.cwasm");
    let stdout = run_wasmtime(&[
        "compile",
        "tests/all/cli_tests/component-basic.wat",
        "-o",
        cwasm.to_str().unwrap(),
        "-Wcomponent-model",
    ])?;
    assert_eq!(stdout, "");
    let stdout = run_wasmtime(&[
        "run",
        "-Wcomponent-model",
        "--allow-precompiled",
        cwasm.to_str().unwrap(),
    ])?;
    assert_eq!(stdout, "");

    Ok(())
}

// Disable test on s390x because the large allocation may actually succeed;
// the whole 64-bit address space is available on this platform.
#[test]
#[cfg(not(target_arch = "s390x"))]
fn memory_growth_failure() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "run",
            "-Wmemory64",
            "-Wtrap-on-grow-failure",
            "tests/all/cli_tests/memory-grow-failure.wat",
        ])
        .output()?;
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("forcing a memory growth failure to be a trap"),
        "bad stderr: {stderr}"
    );
    assert!(!output.status.success());
    Ok(())
}

#[test]
fn table_growth_failure() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "run",
            "-Wtrap-on-grow-failure",
            "tests/all/cli_tests/table-grow-failure.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("forcing trap when growing table"),
        "bad stderr: {stderr}"
    );
    Ok(())
}

#[test]
fn table_growth_failure2() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "run",
            "-Wtrap-on-grow-failure",
            "tests/all/cli_tests/table-grow-failure2.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    let expected = if cfg!(target_pointer_width = "32") {
        "overflow calculating new table size"
    } else {
        "forcing trap when growing table to 4294967296 elements"
    };
    assert!(stderr.contains(expected), "bad stderr: {stderr}");
    Ok(())
}

#[test]
fn option_group_help() -> Result<()> {
    run_wasmtime(&["run", "-Whelp"])?;
    run_wasmtime(&["run", "-O", "help"])?;
    run_wasmtime(&["run", "--codegen", "help"])?;
    run_wasmtime(&["run", "--debug=help"])?;
    run_wasmtime(&["run", "-Shelp"])?;
    run_wasmtime(&["run", "-Whelp-long"])?;
    Ok(())
}

#[test]
fn option_group_comma_separated() -> Result<()> {
    run_wasmtime(&[
        "run",
        "-Wrelaxed-simd,simd",
        "tests/all/cli_tests/simple.wat",
    ])?;
    Ok(())
}

#[test]
fn option_group_boolean_parsing() -> Result<()> {
    run_wasmtime(&["run", "-Wrelaxed-simd", "tests/all/cli_tests/simple.wat"])?;
    run_wasmtime(&["run", "-Wrelaxed-simd=n", "tests/all/cli_tests/simple.wat"])?;
    run_wasmtime(&["run", "-Wrelaxed-simd=y", "tests/all/cli_tests/simple.wat"])?;
    run_wasmtime(&["run", "-Wrelaxed-simd=no", "tests/all/cli_tests/simple.wat"])?;
    run_wasmtime(&[
        "run",
        "-Wrelaxed-simd=yes",
        "tests/all/cli_tests/simple.wat",
    ])?;
    run_wasmtime(&[
        "run",
        "-Wrelaxed-simd=true",
        "tests/all/cli_tests/simple.wat",
    ])?;
    run_wasmtime(&[
        "run",
        "-Wrelaxed-simd=false",
        "tests/all/cli_tests/simple.wat",
    ])?;
    Ok(())
}

#[test]
fn preview2_stdin() -> Result<()> {
    let test = "tests/all/cli_tests/count-stdin.wat";
    let cmd = || -> Result<_> {
        let mut cmd = get_wasmtime_command()?;
        cmd.arg("--invoke=count").arg("-Spreview2").arg(test);
        Ok(cmd)
    };

    // read empty pipe is ok
    let stdout = run_cmd(&mut cmd()?)?;
    assert_eq!(stdout, "0\n");

    // read itself is ok
    let file = File::open(test)?;
    let size = file.metadata()?.len();
    let output = run_cmd(cmd()?.stdin(File::open(test)?))?;
    assert_eq!(output, format!("{size}\n"));

    // read piped input ok is ok
    let mut child = cmd()?
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut stdin = child.stdin.take().unwrap();
    std::thread::spawn(move || {
        stdin.write_all(b"hello").unwrap();
    });
    let output = child.wait_with_output()?;
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout), "5\n");

    let count_up_to = |n: usize| -> Result<_> {
        let mut child = get_wasmtime_command()?
            .arg("--invoke=count-up-to")
            .arg("-Spreview2")
            .arg(test)
            .arg(n.to_string())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        let mut stdin = child.stdin.take().unwrap();
        let t = std::thread::spawn(move || {
            let mut written = 0;
            let bytes = [0; 64 * 1024];
            loop {
                written += match stdin.write(&bytes) {
                    Ok(n) => n,
                    Err(_) => break written,
                };
            }
        });
        let output = child.wait_with_output()?;
        assert!(output.status.success());
        let written = t.join().unwrap();
        let read = String::from_utf8_lossy(&output.stdout)
            .trim()
            .parse::<usize>()
            .unwrap();
        // The test reads in 1000 byte chunks so make sure that it doesn't read
        // more than 1000 bytes than requested.
        assert!(read < n + 1000, "test read too much {read}");
        Ok(written)
    };

    // wasmtime shouldn't eat information that the guest never actually tried to
    // read.
    //
    // NB: this may be a bit flaky. Exactly how much we wrote in the above
    // helper thread depends on how much the OS buffers for us. For now give
    // some some slop and assume that OSes are unlikely to buffer more than
    // that.
    //
    // Note that 256 * 1024 is _one_ byte too small on Asahi Linux (possibly
    // related to 16K page sizes?), hence the `+ 1` here:
    let slop = 256 * 1024 + 1;
    for amt in [0, 100, 100_000] {
        let written = count_up_to(amt)?;
        assert!(written < slop + amt, "wrote too much {written}");
    }
    Ok(())
}

#[test]
fn float_args() -> Result<()> {
    let result = run_wasmtime(&[
        "--invoke",
        "echo_f32",
        "tests/all/cli_tests/simple.wat",
        "1.0",
    ])?;
    assert_eq!(result, "1\n");
    let result = run_wasmtime(&[
        "--invoke",
        "echo_f64",
        "tests/all/cli_tests/simple.wat",
        "1.1",
    ])?;
    assert_eq!(result, "1.1\n");
    Ok(())
}

#[test]
fn mpk_without_pooling() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "run",
            "-O",
            "memory-protection-keys=y",
            "--invoke",
            "echo_f32",
            "tests/all/cli_tests/simple.wat",
            "1.0",
        ])
        .output()?;
    assert!(!output.status.success());
    Ok(())
}

// Very basic use case: compile binary wasm file and run specific function with arguments.
#[test]
fn increase_stack_size() -> Result<()> {
    run_wasmtime(&[
        "run",
        "--invoke",
        "simple",
        &format!("-Wmax-wasm-stack={}", 5 << 20),
        "tests/all/cli_tests/simple.wat",
        "4",
    ])?;
    Ok(())
}

mod test_programs {
    use super::{get_wasmtime_command, run_wasmtime};
    use http_body_util::BodyExt;
    use hyper::header::HeaderValue;
    use std::io::{self, BufRead, BufReader, Read, Write};
    use std::iter;
    use std::net::SocketAddr;
    use std::process::{Child, Command, Stdio};
    use std::thread::{self, JoinHandle};
    use std::time::Duration;
    use test_programs_artifacts::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpStream;
    use wasmtime::{Result, bail, error::Context as _, format_err};

    macro_rules! assert_test_exists {
        ($name:ident) => {
            #[expect(unused_imports, reason = "just here to assert the test is here")]
            use self::$name as _;
        };
    }
    foreach_cli!(assert_test_exists);

    #[test]
    fn p2_cli_hello_stdout() -> Result<()> {
        run_wasmtime(&["run", "-Wcomponent-model", P2_CLI_HELLO_STDOUT_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_args() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            P2_CLI_ARGS_COMPONENT,
            "hello",
            "this",
            "",
            "is an argument",
            "with 🚩 emoji",
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_initial_cwd() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            "-Scwd=/sandbox",
            P2_CLI_INITIAL_CWD_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_stdin_empty() -> Result<()> {
        let mut child = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_STDIN_EMPTY_COMPONENT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::piped())
            .spawn()?;
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"not to be read")
            .unwrap();
        let output = child.wait_with_output()?;
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        assert!(output.status.success());
        Ok(())
    }

    #[test]
    fn p2_cli_stdin() -> Result<()> {
        let mut child = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_STDIN_COMPONENT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::piped())
            .spawn()?;
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"So rested he by the Tumtum tree")
            .unwrap();
        let output = child.wait_with_output()?;
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        assert!(output.status.success());
        Ok(())
    }

    #[test]
    fn p2_cli_splice_stdin() -> Result<()> {
        let mut child = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_SPLICE_STDIN_COMPONENT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::piped())
            .spawn()?;
        let msg = "So rested he by the Tumtum tree";
        child
            .stdin
            .take()
            .unwrap()
            .write_all(msg.as_bytes())
            .unwrap();
        let output = child.wait_with_output()?;
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        if !stderr.is_empty() {
            eprintln!("{stderr}");
        }

        assert_eq!(
            format!(
                "before splice\n{msg}\ncompleted splicing {} bytes\n",
                msg.as_bytes().len()
            ),
            stdout
        );
        Ok(())
    }

    #[test]
    fn p2_cli_stdout_epipe() -> Result<()> {
        let mut child = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_STDOUT_EPIPE_COMPONENT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .spawn()?;

        // Read a small amount from stdout then drop it to close the pipe,
        // which should cause the guest to receive StreamError::Closed (EPIPE).
        let mut stdout = child.stdout.take().unwrap();
        let mut buf = [0u8; 64];
        let _ = stdout.read(&mut buf)?;
        drop(stdout);

        let output = child.wait_with_output()?;
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            output.status.success(),
            "guest should exit successfully after receiving Closed, stderr: {stderr}"
        );
        assert!(
            stderr.contains("got expected StreamError::Closed"),
            "guest should have reported StreamError::Closed, stderr: {stderr}"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn p2_cli_stdin_eisdir() -> Result<()> {
        let dir = tempfile::tempdir()?;
        // Open the directory and transfer the fd to Stdio for use as stdin.
        let dir_file = std::fs::File::open(dir.path())?;
        let stdin_stdio: Stdio = dir_file.into();

        let child = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_STDIN_EISDIR_COMPONENT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(stdin_stdio)
            .spawn()?;

        let output = child.wait_with_output()?;
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            output.status.success(),
            "guest should exit successfully after receiving IsDirectory, stderr: {stderr}"
        );
        assert!(
            stderr.contains("got expected ErrorCode::IsDirectory"),
            "guest should have reported ErrorCode::IsDirectory, stderr: {stderr}"
        );
        Ok(())
    }

    // EISDIR is a Unix-specific concept; on Windows opening a directory for
    // reading behaves differently, so this test only runs on Unix.
    #[cfg(not(unix))]
    #[test]
    fn p2_cli_stdin_eisdir() -> Result<()> {
        Ok(())
    }

    #[test]
    fn p2_cli_env() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            "--env=frabjous=day",
            "--env=callooh=callay",
            P2_CLI_ENV_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_file_read() -> Result<()> {
        let dir = tempfile::tempdir()?;

        std::fs::write(dir.path().join("bar.txt"), b"And stood awhile in thought")?;

        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            &format!("--dir={}::/", dir.path().to_str().unwrap()),
            P2_CLI_FILE_READ_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_file_append() -> Result<()> {
        let dir = tempfile::tempdir()?;

        std::fs::File::create(dir.path().join("bar.txt"))?
            .write_all(b"'Twas brillig, and the slithy toves.\n")?;

        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            &format!("--dir={}::/", dir.path().to_str().unwrap()),
            P2_CLI_FILE_APPEND_COMPONENT,
        ])?;

        let contents = std::fs::read(dir.path().join("bar.txt"))?;
        assert_eq!(
            std::str::from_utf8(&contents).unwrap(),
            "'Twas brillig, and the slithy toves.\n\
                   Did gyre and gimble in the wabe;\n\
                   All mimsy were the borogoves,\n\
                   And the mome raths outgrabe.\n"
        );
        Ok(())
    }

    #[test]
    fn p2_cli_file_dir_sync() -> Result<()> {
        let dir = tempfile::tempdir()?;

        std::fs::File::create(dir.path().join("bar.txt"))?
            .write_all(b"'Twas brillig, and the slithy toves.\n")?;

        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            &format!("--dir={}::/", dir.path().to_str().unwrap()),
            P2_CLI_FILE_DIR_SYNC_COMPONENT,
        ])?;

        Ok(())
    }

    #[test]
    fn p2_cli_exit_success() -> Result<()> {
        run_wasmtime(&["run", "-Wcomponent-model", P2_CLI_EXIT_SUCCESS_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_exit_default() -> Result<()> {
        run_wasmtime(&["run", "-Wcomponent-model", P2_CLI_EXIT_DEFAULT_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_exit_failure() -> Result<()> {
        let output = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_EXIT_FAILURE_COMPONENT])
            .output()?;
        assert!(!output.status.success());
        assert_eq!(output.status.code(), Some(1));
        Ok(())
    }

    #[test]
    fn p2_cli_exit_with_code() -> Result<()> {
        let output = get_wasmtime_command()?
            .args(&[
                "run",
                "-Wcomponent-model",
                "-Scli-exit-with-code",
                P2_CLI_EXIT_WITH_CODE_COMPONENT,
            ])
            .output()?;
        assert!(!output.status.success());
        assert_eq!(output.status.code(), Some(42));
        Ok(())
    }

    #[test]
    fn p2_cli_exit_panic() -> Result<()> {
        let output = get_wasmtime_command()?
            .args(&["run", "-Wcomponent-model", P2_CLI_EXIT_PANIC_COMPONENT])
            .output()?;
        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("Curiouser and curiouser!"));
        Ok(())
    }

    #[test]
    fn p2_cli_directory_list() -> Result<()> {
        let dir = tempfile::tempdir()?;

        std::fs::File::create(dir.path().join("foo.txt"))?;
        std::fs::File::create(dir.path().join("bar.txt"))?;
        std::fs::File::create(dir.path().join("baz.txt"))?;
        std::fs::create_dir(dir.path().join("sub"))?;
        std::fs::File::create(dir.path().join("sub").join("wow.txt"))?;
        std::fs::File::create(dir.path().join("sub").join("yay.txt"))?;

        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            &format!("--dir={}::/", dir.path().to_str().unwrap()),
            P2_CLI_DIRECTORY_LIST_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_default_clocks() -> Result<()> {
        run_wasmtime(&["run", "-Wcomponent-model", P2_CLI_DEFAULT_CLOCKS_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_export_cabi_realloc() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            P2_CLI_EXPORT_CABI_REALLOC_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn run_wasi_http_component() -> Result<()> {
        let stdout = super::run_wasmtime(&[
            "-Wcomponent-model",
            "-Scli,http,preview2",
            P2_HTTP_OUTBOUND_REQUEST_RESPONSE_BUILD_COMPONENT,
        ])?;
        println!("{stdout}");
        assert!(stdout.starts_with("Called _start\n"));
        assert!(stdout.ends_with("Done\n"));
        Ok(())
    }

    // Test to ensure that prints in the guest aren't buffered on the host by
    // accident. The test here will print something without a newline and then
    // wait for input on stdin, and the test here is to ensure that the
    // character shows up here even as the guest is waiting on input via stdin.
    #[test]
    fn p2_cli_stdio_write_flushes() -> Result<()> {
        fn run(args: &[&str]) -> Result<()> {
            println!("running {args:?}");
            let mut child = get_wasmtime_command()?
                .args(args)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()?;
            let mut stdout = child.stdout.take().unwrap();
            let mut buf = [0; 10];
            match stdout.read(&mut buf) {
                Ok(2) => assert_eq!(&buf[..2], b"> "),
                e => panic!("unexpected read result {e:?}"),
            }
            drop(stdout);
            drop(child.stdin.take().unwrap());
            let status = child.wait()?;
            assert!(status.success());
            Ok(())
        }

        run(&["run", "-Spreview2=y", P2_CLI_STDIO_WRITE_FLUSHES])?;
        run(&[
            "run",
            "-Wcomponent-model",
            P2_CLI_STDIO_WRITE_FLUSHES_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_no_tcp() -> Result<()> {
        super::run_wasmtime(&[
            "-Wcomponent-model",
            // Turn on network but turn off TCP
            "-Sinherit-network,tcp=no",
            P2_CLI_NO_TCP_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_no_udp() -> Result<()> {
        super::run_wasmtime(&[
            "-Wcomponent-model",
            // Turn on network but turn off UDP
            "-Sinherit-network,udp=no",
            P2_CLI_NO_UDP_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_no_ip_name_lookup() -> Result<()> {
        super::run_wasmtime(&[
            "-Wcomponent-model",
            // Turn on network but ensure name lookup is disabled
            "-Sinherit-network,allow-ip-name-lookup=no",
            P2_CLI_NO_IP_NAME_LOOKUP_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_sleep() -> Result<()> {
        run_wasmtime(&["run", P2_CLI_SLEEP])?;
        run_wasmtime(&["run", P2_CLI_SLEEP_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_sleep_forever() -> Result<()> {
        for timeout in [
            // Tests still pass when we race with going to sleep.
            "-Wtimeout=1ns",
            // Tests pass when we wait till the Wasm has (likely) gone to sleep.
            "-Wtimeout=250ms",
        ] {
            let e = run_wasmtime(&["run", timeout, P2_CLI_SLEEP_FOREVER]).unwrap_err();
            let e = e.to_string();
            println!("Got error: {e}");
            assert!(e.contains("interrupt"));

            let e = run_wasmtime(&["run", timeout, P2_CLI_SLEEP_FOREVER_COMPONENT]).unwrap_err();
            let e = e.to_string();
            println!("Got error: {e}");
            assert!(e.contains("interrupt"));
        }

        Ok(())
    }

    /// Helper structure to manage an invocation of `wasmtime serve`
    struct WasmtimeServe {
        child: Option<Child>,
        stdout: Option<JoinHandle<io::Result<Vec<u8>>>>,
        stderr: Option<JoinHandle<io::Result<Vec<u8>>>>,
        addr: Vec<SocketAddr>,
        shutdown_addr: SocketAddr,
    }

    impl WasmtimeServe {
        /// Creates a new server which will serve the wasm component pointed to
        /// by `wasm`.
        ///
        /// A `configure` callback is provided to specify how `wasmtime serve`
        /// will be invoked and configure arguments such as headers.
        fn new(wasm: &str, configure: impl FnOnce(&mut Command)) -> Result<WasmtimeServe> {
            // Spawn `wasmtime serve` on port 0 which will randomly assign it a
            // port.
            let mut cmd = super::get_wasmtime_command()?;
            cmd.arg("serve").arg("--addr=127.0.0.1:0").arg(wasm);
            configure(&mut cmd);
            Self::spawn(&mut cmd, 1)
        }

        fn spawn(cmd: &mut Command, expected_addresses: usize) -> Result<WasmtimeServe> {
            cmd.arg("--shutdown-addr=127.0.0.1:0");
            cmd.stdin(Stdio::null());
            cmd.stdout(Stdio::piped());
            cmd.stderr(Stdio::piped());
            let mut child = cmd.spawn()?;

            // Read the first few lines of stderr which will say which address
            // it's listening on. The first line is the shutdown line (with
            // `--shutdown-addr`) and the second is what `--addr` was bound to.
            // This is done to figure out what `:0` was bound to in the child
            // process.
            let mut line = String::new();
            let mut stderr = BufReader::new(child.stderr.take().unwrap());
            let mut read_addr_from_line = |prefix: &str| -> Result<SocketAddr> {
                stderr.read_line(&mut line)?;

                if !line.starts_with(prefix) {
                    bail!("input line `{line}` didn't start with `{prefix}`");
                }
                match line.find("127.0.0.1").and_then(|addr_start| {
                    let addr = &line[addr_start..];
                    let addr_end = addr.find("/")?;
                    addr[..addr_end].parse().ok()
                }) {
                    Some(addr) => {
                        line.truncate(0);
                        Ok(addr)
                    }
                    None => bail!("failed to address from: {line}"),
                }
            };

            let shutdown_addr = read_addr_from_line("Listening for shutdown");
            let mut addr = Vec::with_capacity(expected_addresses);
            let mut addr_error = None;
            for _ in 0..expected_addresses {
                match read_addr_from_line("Serving HTTP on") {
                    Ok(a) => addr.push(a),
                    Err(e) => {
                        addr_error = Some(e);
                        break;
                    }
                };
            }

            let (shutdown_addr, addr) = match (shutdown_addr, addr_error) {
                (Ok(a), None) => (a, addr),
                // If either failed kill the child and otherwise try to shepherd
                // along any contextual information we have.
                (Err(a), _) | (_, Some(a)) => {
                    child.kill()?;
                    child.wait()?;
                    stderr.read_to_string(&mut line)?;
                    return Err(a.context(line));
                }
            };
            let mut stdout = child.stdout.take().unwrap();
            Ok(WasmtimeServe {
                stdout: Some(thread::spawn(move || {
                    let mut dst = Vec::new();
                    stdout.read_to_end(&mut dst).map(|_| dst)
                })),

                stderr: Some(thread::spawn(move || {
                    let mut dst = Vec::new();
                    stderr.read_to_end(&mut dst).map(|_| dst)
                })),

                child: Some(child),
                addr,
                shutdown_addr,
            })
        }

        fn first_addr(&self) -> &SocketAddr {
            &self.addr[0]
        }

        /// Completes this server gracefully by printing the output on failure.
        fn finish(mut self) -> Result<(String, String)> {
            self._finish()
        }

        fn wait(mut self) -> Result<(String, String)> {
            let child = self.child.take().unwrap();
            self._wait_with_output(child)
        }

        fn _finish(&mut self) -> Result<(String, String)> {
            let mut child = self.child.take().unwrap();

            // If the child process has already exited, then great! Otherwise
            // the server is still running and it shouldn't be possible to exit
            // until a shutdown signal is sent, so do that here. Make a TCP
            // connection to the shutdown port which is used as a shutdown
            // signal.
            if child.try_wait()?.is_none() {
                std::net::TcpStream::connect(&self.shutdown_addr)
                    .context("failed to initiate graceful shutdown")?;
            }

            // Regardless of whether we just shut the server down or whether it
            // was already shut down (e.g. panicked or similar), wait for the
            // result here. The result should succeed (e.g. 0 exit status), and
            // if it did then the stdout/stderr are the caller's problem.
            self._wait_with_output(child)
        }

        fn _wait_with_output(&mut self, child: Child) -> Result<(String, String)> {
            let mut output = child.wait_with_output()?;
            output.stdout = self.stdout.take().unwrap().join().unwrap()?;
            output.stderr = self.stderr.take().unwrap().join().unwrap()?;
            if !output.status.success() {
                bail!("child failed {output:?}");
            }

            Ok((
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            ))
        }

        /// Send a request to this server and wait for the response.
        async fn send_request(&self, req: http::Request<String>) -> Result<http::Response<String>> {
            let (mut send, conn_task) = self.start_requests().await?;

            let response = Self::send_request_with(&mut send, req).await?;
            drop(send);

            conn_task.await??;

            Ok(response)
        }

        async fn send_request_with(
            send: &mut hyper::client::conn::http1::SendRequest<String>,
            req: http::Request<String>,
        ) -> Result<http::Response<String>> {
            // RFC 9112 section 3.2: a client sends `Host` in every HTTP/1.1
            // request, absolute-form included, so fill it in from the target.
            let has_host = req.headers().contains_key(http::header::HOST);
            let authority = req.uri().authority().cloned();
            let req = match (has_host, authority) {
                (false, Some(authority)) => {
                    let mut req = req;
                    let value = http::header::HeaderValue::from_str(authority.as_str())
                        .context("failed to make Host header value")?;
                    req.headers_mut().insert(http::header::HOST, value);
                    req
                }
                _ => req,
            };
            let response = send
                .send_request(req)
                .await
                .context("error sending request")?;

            let (parts, body) = response.into_parts();

            let body = body.collect().await.context("failed to read body")?;
            assert!(body.trailers().is_none());
            let body = std::str::from_utf8(&body.to_bytes())?.to_string();

            Ok(http::Response::from_parts(parts, body))
        }

        async fn start_requests(
            &self,
        ) -> Result<(
            hyper::client::conn::http1::SendRequest<String>,
            tokio::task::JoinHandle<hyper::Result<()>>,
        )> {
            self.start_requests_at(0).await
        }

        async fn start_requests_at(
            &self,
            address: usize,
        ) -> Result<(
            hyper::client::conn::http1::SendRequest<String>,
            tokio::task::JoinHandle<hyper::Result<()>>,
        )> {
            let tcp = TcpStream::connect(&self.addr[address])
                .await
                .context("failed to connect")?;
            let tcp = wasmtime_wasi_http::io::TokioIo::new(tcp);
            let (send, conn) = hyper::client::conn::http1::handshake(tcp)
                .await
                .context("failed http handshake")?;
            Ok((send, tokio::task::spawn(conn)))
        }
    }

    // Don't leave child processes running by accident so kill the child process
    // if our server goes away.
    impl Drop for WasmtimeServe {
        fn drop(&mut self) {
            match &mut self.child {
                Some(child) => match child.kill() {
                    Ok(()) => {}
                    Err(e) => {
                        eprintln!("failed to kill child process {e}");
                        return;
                    }
                },
                None => return,
            }
            match self._finish() {
                Ok((stdout, stderr)) => {
                    if !stdout.is_empty() {
                        println!("server stdout:\n{stdout}");
                    }
                    if !stderr.is_empty() {
                        println!("server stderr:\n{stderr}");
                    }
                }
                Err(e) => println!("failed to wait for child or read stdio: {e}"),
            }
        }
    }

    #[tokio::test]
    async fn p2_cli_serve_echo_env() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| {
            cmd.arg("--env=FOO=bar");
            cmd.arg("--env=BAR");
            cmd.arg("-Scli");
            cmd.env_remove("BAR");
        })?;

        let foo_env = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "FOO")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(foo_env.status().is_success());
        assert!(foo_env.body().is_empty());
        let headers = foo_env.headers();
        assert_eq!(headers.get("env"), Some(&HeaderValue::from_static("bar")));

        let bar_env = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "BAR")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(bar_env.status().is_success());
        assert!(bar_env.body().is_empty());
        let headers = bar_env.headers();
        assert_eq!(headers.get("env"), None);

        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_header_replaces_request_header() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| {
            cmd.arg("--env=FOO=bar");
            cmd.arg("--env=BAR=baz");
            cmd.arg("--header=env: FOO");
            cmd.arg("--header=env: BAR");
            cmd.arg("--header=expect-env-count: 2");
            cmd.arg("-Scli");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "BAR")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());
        assert!(resp.body().is_empty());
        assert_eq!(
            resp.headers().get("env"),
            Some(&HeaderValue::from_static("bar"))
        );

        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_header_file() -> Result<()> {
        let td = tempfile::TempDir::new()?;
        let headers_path = td.path().join("headers.txt");
        std::fs::write(&headers_path, "env: FOO\n\nunused: value\n")?;

        let server = WasmtimeServe::new(P2_CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| {
            cmd.arg("--env=FOO=bar");
            cmd.arg(format!("--header=@{}", headers_path.display()));
            cmd.arg("-Scli");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());
        assert!(resp.body().is_empty());
        assert_eq!(
            resp.headers().get("env"),
            Some(&HeaderValue::from_static("bar"))
        );

        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_outgoing_body_config() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| {
            cmd.arg("-Scli");
            cmd.arg("-Shttp-outgoing-body-buffer-chunks=2");
            cmd.arg("-Shttp-outgoing-body-chunk-size=1024");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "FOO")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());

        server.finish()?;
        Ok(())
    }

    #[test]
    fn p2_cli_reject_zero_outgoing_body_options() -> Result<()> {
        // The outgoing body writer requires at least one buffered chunk and a
        // non-zero write budget, so a zero here is a configuration error.
        for option in [
            "-Shttp-outgoing-body-buffer-chunks=0",
            "-Shttp-outgoing-body-chunk-size=0",
        ] {
            let err = run_wasmtime(&[
                "run",
                "-Shttp=y",
                option,
                P2_CLI_RUN_OUTGOING_BODY_CHUNK_SIZE_COMPONENT,
            ])
            .unwrap_err();
            let err = format!("{err:?}");
            assert!(
                err.contains("value must be non-zero"),
                "expected `{option}` to be rejected, got: {err}"
            );
        }

        Ok(())
    }

    #[test]
    fn p2_cli_serve_reject_zero_concurrency() -> Result<()> {
        // Both limits are handed to a semaphore, so a zero leaves the server
        // listening but never serving anything.
        let component = P2_CLI_SERVE_HELLO_WORLD_COMPONENT;
        let too_large = format!("={}", usize::MAX);
        for option in [
            "--max-concurrent-requests=0".to_string(),
            "--max-concurrent-connections=0".to_string(),
            format!("--max-concurrent-requests{too_large}"),
            format!("--max-concurrent-connections{too_large}"),
        ] {
            let mut cmd = super::get_wasmtime_command()?;
            cmd.args(["serve", "-Scli", option.as_str(), component])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped());
            let mut child = cmd.spawn()?;
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            while child.try_wait()?.is_none() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "`{option}` was accepted and the server kept running"
                );
                thread::sleep(Duration::from_millis(100));
            }
            let output = child.wait_with_output()?;
            assert!(!output.status.success(), "`{option}` was accepted");
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                stderr.contains("invalid value"),
                "expected `{option}` to be rejected, got: {stderr}"
            );
        }

        Ok(())
    }

    #[test]
    fn p2_cli_zero_idle_timeouts_still_accepted() -> Result<()> {
        // Only `-W timeout` and `--post-return-timeout` reject zero.
        let component = P2_CLI_SERVE_HELLO_WORLD_COMPONENT;
        for option in ["--idle-process-timeout=0", "--idle-instance-timeout=0"] {
            let mut cmd = super::get_wasmtime_command()?;
            cmd.args(["serve", "-Scli", option, "--addr", "127.0.0.1:0", component])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped());
            let mut child = cmd.spawn()?;
            thread::sleep(Duration::from_millis(800));
            assert!(
                child.try_wait()?.is_none(),
                "`{option}` should still be accepted"
            );
            child.kill()?;
            child.wait()?;
        }

        Ok(())
    }

    #[test]
    fn p2_cli_reject_zero_timeouts() -> Result<()> {
        // A zero timeout makes the epoch thread spin at 100% CPU.
        let component = P2_CLI_SERVE_HELLO_WORLD_COMPONENT;
        for args in [
            &["serve", "-Scli", "-W", "timeout=0", component][..],
            &["serve", "-Scli", "--post-return-timeout", "0", component][..],
        ] {
            let mut cmd = super::get_wasmtime_command()?;
            cmd.args(args)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::piped());
            let mut child = cmd.spawn()?;
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            while child.try_wait()?.is_none() {
                assert!(
                    std::time::Instant::now() < deadline,
                    "zero timeout was accepted and the server kept running"
                );
                thread::sleep(Duration::from_millis(100));
            }
            let output = child.wait_with_output()?;
            assert!(!output.status.success(), "zero timeout was accepted");
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                stderr.contains("duration must not be zero"),
                "expected zero timeout to be rejected, got: {stderr}"
            );
        }

        Ok(())
    }

    #[test]
    fn p2_cli_run_outgoing_body_chunk_size() -> Result<()> {
        // Without the option an outgoing body keeps its 1 MiB default budget.
        let stdout = run_wasmtime(&[
            "run",
            "-Shttp=y",
            P2_CLI_RUN_OUTGOING_BODY_CHUNK_SIZE_COMPONENT,
        ])?;
        assert_eq!(stdout.trim(), "1048576");

        // `-Shttp-outgoing-body-chunk-size` is what changes that budget, and
        // `wasmtime run` has to honour it just like `wasmtime serve` does.
        let stdout = run_wasmtime(&[
            "run",
            "-Shttp=y",
            "-Shttp-outgoing-body-chunk-size=1024",
            P2_CLI_RUN_OUTGOING_BODY_CHUNK_SIZE_COMPONENT,
        ])?;
        assert_eq!(stdout.trim(), "1024");

        Ok(())
    }

    #[tokio::test]
    #[ignore] // TODO: printing stderr in the child and killing the child at the
    // end of this test race so the stderr may be present or not. Need
    // to implement a more graceful shutdown routine for `wasmtime
    // serve`.
    async fn p2_cli_serve_respect_pooling_options() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| {
            cmd.arg("-Opooling-total-memories=0").arg("-Scli");
        })?;

        let result = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "FOO")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await;
        assert!(result.is_err());
        let (_, stderr) = server.finish()?;
        assert!(
            stderr.contains("maximum concurrent memory limit of 0 reached"),
            "bad stderr: {stderr}",
        );
        Ok(())
    }

    #[test]
    fn p2_cli_large_env() -> Result<()> {
        for wasm in [P2_CLI_LARGE_ENV, P2_CLI_LARGE_ENV_COMPONENT] {
            println!("run {wasm:?}");
            let mut cmd = super::wasmtime(&["run", "-Sinherit-env", wasm])?;

            for i in 0..512 {
                let var = format!("KEY{i}");
                let val = (0..1024).map(|_| 'x').collect::<String>();
                cmd.env(&var, &val);
            }
            super::run_cmd(&mut cmd)?;
        }
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_only_one_process_allowed() -> Result<()> {
        let wasm = P2_CLI_SERVE_ECHO_ENV_COMPONENT;
        let server = WasmtimeServe::new(wasm, |cmd| {
            cmd.arg("-Scli");
        })?;

        let err = WasmtimeServe::spawn(
            super::get_wasmtime_command()?
                .arg("serve")
                .arg("-Scli")
                .arg(format!("--addr={}", server.first_addr()))
                .arg(wasm),
            1,
        )
        .err()
        .expect("server spawn should have failed but it succeeded");
        drop(server);

        let err = format!("{err:?}");
        println!("{err}");
        assert!(err.contains("os error"));
        Ok(())
    }

    // Technically this test is a little racy. This binds port 0 to acquire a
    // random port, issues a single request to this port, but then kills this
    // server while the request is still processing. The port is then rebound
    // in the next process while it technically could be stolen by another
    // process.
    #[tokio::test]
    async fn p2_cli_serve_quick_rebind_allowed() -> Result<()> {
        let wasm = P2_CLI_SERVE_ECHO_ENV_COMPONENT;
        let server = WasmtimeServe::new(wasm, |cmd| {
            cmd.arg("-Scli");
        })?;
        let addr = *server.first_addr();

        // Start up a `send` and `conn_task` which represents a connection to
        // this server.
        let (mut send, conn_task) = server.start_requests().await?;
        let _ = send
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .header("env", "FOO")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await;

        // ... once a response has been received (or at least the status
        // code/headers) then kill the server. THis is done while `conn_task`
        // and `send` are still alive so we're guaranteed that the other side
        // got a request (we got a response) and our connection is still open.
        //
        // This forces the address/port into the `TIME_WAIT` state. The rebind
        // below in the next process will fail if `SO_REUSEADDR` isn't set.
        drop(server);
        drop(send);
        let _ = conn_task.await;

        // If this is successfully bound then we'll create `WasmtimeServe`
        // which reads off the first line of output to know which address was
        // bound.
        let _server2 = WasmtimeServe::spawn(
            super::get_wasmtime_command()?
                .arg("serve")
                .arg("-Scli")
                .arg(format!("--addr={addr}"))
                .arg(wasm),
            1,
        )?;

        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_write_too_much() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_WRITE_TOO_MUCH_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(!resp.status().is_success());

        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_with_print() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_WITH_PRINT_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;

        for _ in 0..2 {
            let resp = server
                .send_request(
                    hyper::Request::builder()
                        .uri("http://localhost/")
                        .body(String::new())
                        .context("failed to make request")?,
                )
                .await?;
            assert!(resp.status().is_success());
        }

        let (out, err) = server.finish()?;
        assert_eq!(
            out,
            "\
stdout [0] :: this is half a print to stdout
stdout [0] :: \n\
stdout [0] :: after empty
stdout [1] :: this is half a print to stdout
stdout [1] :: \n\
stdout [1] :: after empty
"
        );
        assert!(
            err.contains(
                "\
stderr [0] :: this is half a print to stderr
stderr [0] :: \n\
stderr [0] :: after empty
stderr [0] :: start a print 1234
stderr [1] :: this is half a print to stderr
stderr [1] :: \n\
stderr [1] :: after empty
stderr [1] :: start a print 1234
"
            ),
            "bad stderr: {err}"
        );

        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_with_print_no_prefix() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_WITH_PRINT_COMPONENT, |cmd| {
            cmd.arg("-Scli");
            cmd.arg("--no-logging-prefix");
        })?;

        for _ in 0..2 {
            let resp = server
                .send_request(
                    hyper::Request::builder()
                        .uri("http://localhost/")
                        .body(String::new())
                        .context("failed to make request")?,
                )
                .await?;
            assert!(resp.status().is_success());
        }

        let (out, err) = server.finish()?;
        assert_eq!(
            out,
            "\
this is half a print to stdout
\n\
after empty
this is half a print to stdout
\n\
after empty
"
        );
        assert!(
            err.contains(
                "\
this is half a print to stderr
\n\
after empty
start a print 1234
this is half a print to stderr
\n\
after empty
start a print 1234
"
            ),
            "bad stderr {err}",
        );

        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_authority_and_scheme() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_AUTHORITY_AND_SCHEME_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("/")
                    .header("Host", "localhost")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .method("CONNECT")
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());

        Ok(())
    }

    /// Write a raw HTTP request to a serve instance and read the whole response.
    async fn serve_raw_request(server: &WasmtimeServe, request: &[u8]) -> Result<Vec<u8>> {
        let mut stream = TcpStream::connect(server.first_addr()).await?;
        stream.write_all(request).await?;
        let mut response = Vec::new();
        tokio::time::timeout(Duration::from_secs(10), stream.read_to_end(&mut response))
            .await
            .expect("timed out waiting for a response")?;
        Ok(response)
    }

    /// Send the RFC 9112 section 3.2 request table to `server`: one request with
    /// a valid `Host` and the requests that must be rejected with a 400.
    async fn test_rfc_9112_sec_3_2(server: &WasmtimeServe) -> Result<()> {
        let cases: &[(&str, &[u8], &[u8])] = &[
            (
                "valid host",
                b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 200",
            ),
            (
                "two hosts",
                b"GET / HTTP/1.1\r\nHost: a.example\r\nHost: b.example\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "non-ascii host",
                b"GET / HTTP/1.1\r\nHost: \x80\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "host with userinfo",
                b"GET / HTTP/1.1\r\nHost: [email protected]\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "no host",
                b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "absolute-form without host",
                b"GET http://localhost/ HTTP/1.1\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "absolute-form",
                b"GET http://localhost/ HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 200",
            ),
            (
                "host with bad port",
                b"GET / HTTP/1.1\r\nHost: example.com:abc\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "host with empty port",
                b"GET / HTTP/1.1\r\nHost: example.com:\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "host with out of range port",
                b"GET / HTTP/1.1\r\nHost: example.com:65536\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "host with empty host",
                b"GET / HTTP/1.1\r\nHost: :8080\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
            (
                "host with port",
                b"GET / HTTP/1.1\r\nHost: example.com:8080\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 200",
            ),
            (
                "host with ipv6",
                b"GET / HTTP/1.1\r\nHost: [::1]\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 200",
            ),
            (
                "absolute-form with userinfo",
                b"GET http://user@localhost/ HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
                b"HTTP/1.1 400",
            ),
        ];
        for (name, request, expected) in cases {
            let response = serve_raw_request(server, request).await?;
            assert!(
                response.starts_with(expected),
                "{name}: expected {:?}, got {:?}",
                String::from_utf8_lossy(expected),
                String::from_utf8_lossy(&response),
            );
        }

        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_rfc_9112_sec_3_2() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;
        test_rfc_9112_sec_3_2(&server).await?;
        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_rfc_9112_sec_3_2() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
        })?;
        test_rfc_9112_sec_3_2(&server).await?;
        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_missing_authority() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;

        // hyper's client always synthesizes a `Host` header for HTTP/1.1
        // requests, so write this request out by hand in order to leave both
        // the URI authority and the `Host` header off.  There is nothing to
        // serve such a request with: it is rejected while it is being turned
        // into a guest request, before the guest runs at all, so the status
        // code comes from the error rather than from a guest response.
        let mut stream = TcpStream::connect(server.first_addr()).await?;
        stream.write_all(b"GET / HTTP/1.1\r\n\r\n").await?;
        // The connection is kept alive, so read until the body has arrived
        // rather than until EOF.
        let mut response = Vec::new();
        let mut buf = [0; 512];
        while !response.ends_with(b"</html>") && response.len() < 8192 {
            let n = tokio::time::timeout(Duration::from_secs(10), stream.read(&mut buf))
                .await
                .expect("timed out waiting for a response")?;
            if n == 0 {
                break;
            }
            response.extend_from_slice(&buf[..n]);
        }
        let response = String::from_utf8(response)?;
        assert!(
            response.starts_with("HTTP/1.1 400"),
            "unexpected response: {response:?}",
        );
        assert!(
            response.contains("<h1>400 Bad Request</h1>"),
            "unexpected response: {response:?}",
        );
        drop(stream);

        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p3_cli_serve_authority_and_scheme() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_AUTHORITY_AND_SCHEME_COMPONENT, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("/")
                    .header("Host", "localhost")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());

        // The scheme is that of the connection, not of an absolute-form
        // request target.
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("https://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());

        Ok(())
    }

    // A body can fail to parse after the guest read part of it.
    // `future-trailers` must report an error, not a successful body.
    #[tokio::test]
    async fn p2_cli_serve_trailers_result() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_TRAILERS_RESULT_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;

        async fn request(server: &WasmtimeServe, raw: &[u8]) -> Result<String> {
            let mut stream = TcpStream::connect(server.first_addr()).await?;
            stream.write_all(raw).await?;
            let mut response = Vec::new();
            let mut buf = [0; 1024];
            loop {
                let n = tokio::time::timeout(Duration::from_secs(10), stream.read(&mut buf))
                    .await
                    .expect("timed out waiting for a response")?;
                if n == 0 {
                    break;
                }
                response.extend_from_slice(&buf[..n]);
            }
            String::from_utf8(response).map_err(Into::into)
        }

        let malformed: &[(&str, &[u8])] = &[
            (
                "empty trailer name",
                b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n: v\r\n\r\n",
            ),
            (
                "trailer without a colon",
                b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nBadTrailer\r\n\r\n",
            ),
            (
                "trailer with a NUL",
                b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-T: a\x00b\r\n\r\n",
            ),
            (
                "extra zero chunk",
                b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n0\r\n\r\n",
            ),
        ];
        for (name, raw) in malformed {
            let response = request(&server, raw).await?;
            assert!(
                response.contains("trailers=error-code=ErrorCode::HttpProtocolError"),
                "{name}: {response:?}",
            );
        }

        // A well-formed body still reports success: once without trailers and
        // once with a single trailer.
        let response = request(
            &server,
            b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n",
        )
        .await?;
        assert!(response.contains("trailers=none"), "{response:?}");

        let response = request(
            &server,
            b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-T: v\r\n\r\n",
        )
        .await?;
        assert!(response.contains("trailers=field-count=1"), "{response:?}");

        server.finish()?;
        Ok(())
    }

    #[test]
    fn p2_cli_argv0() -> Result<()> {
        run_wasmtime(&["run", "--argv0=a", P2_CLI_ARGV0, "a"])?;
        run_wasmtime(&["run", "--argv0=b", P2_CLI_ARGV0_COMPONENT, "b"])?;
        run_wasmtime(&["run", "--argv0=foo.wasm", P2_CLI_ARGV0, "foo.wasm"])?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_config() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_CONFIG_COMPONENT, |cmd| {
            cmd.arg("-Scli");
            cmd.arg("-Sconfig");
            cmd.arg("-Sconfig-var=hello=world");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());
        assert_eq!(resp.body(), "world");
        Ok(())
    }

    #[test]
    fn p2_cli_config() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Sconfig",
            "-Sconfig-var=hello=world",
            CONFIG_GET_COMPONENT,
        ])?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_keyvalue() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_KEYVALUE_COMPONENT, |cmd| {
            cmd.arg("-Scli");
            cmd.arg("-Skeyvalue");
            cmd.arg("-Skeyvalue-in-memory-data=hello=world");
        })?;

        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());
        assert_eq!(resp.body(), "world");
        Ok(())
    }

    #[test]
    fn p2_cli_keyvalue() -> Result<()> {
        run_wasmtime(&[
            "run",
            "-Skeyvalue",
            "-Skeyvalue-in-memory-data=atomics_key=5",
            KEYVALUE_MAIN_COMPONENT,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_multiple_preopens() -> Result<()> {
        run_wasmtime(&[
            "run",
            "--dir=/::/a",
            "--dir=/::/b",
            "--dir=/::/c",
            P2_CLI_MULTIPLE_PREOPENS_COMPONENT,
        ])?;
        Ok(())
    }

    async fn p2_cli_serve_guest_never_invoked_set(wasm: &str) -> Result<()> {
        let server = WasmtimeServe::new(wasm, |cmd| {
            cmd.arg("-Scli");
        })?;

        for _ in 0..2 {
            let res = server
                .send_request(
                    hyper::Request::builder()
                        .uri("http://localhost/")
                        .body(String::new())
                        .context("failed to make request")?,
                )
                .await
                .expect("got response from wasmtime");
            assert_eq!(res.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
        }

        let (stdout, stderr) = server.finish()?;
        println!("stdout: {stdout}");
        println!("stderr: {stderr}");
        assert!(stderr.contains("guest never invoked `response-outparam::set` method"));
        assert!(!stderr.contains("panicked"));
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_return_before_set() -> Result<()> {
        p2_cli_serve_guest_never_invoked_set(P2_CLI_SERVE_RETURN_BEFORE_SET_COMPONENT).await
    }

    #[tokio::test]
    async fn p2_cli_serve_trap_before_set() -> Result<()> {
        p2_cli_serve_guest_never_invoked_set(P2_CLI_SERVE_TRAP_BEFORE_SET_COMPONENT).await
    }

    #[tokio::test]
    async fn serve_coredump_smoketest() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let core = dir.path().join("core");
        let server = WasmtimeServe::new(P2_CLI_SERVE_TRAP_BEFORE_SET_COMPONENT, |cmd| {
            cmd.arg("-Scli")
                .arg(format!("-Dcoredump={}", core.display()));
        })?;
        let res = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert_eq!(res.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
        let (_stdout, stderr) = server.finish()?;
        let dumped = std::fs::read(&core)?;
        let head = dumped.get(..16).unwrap_or(&dumped);
        println!(
            "observed guest={} path={} len={} magic={:02x?} head16={:02x?}",
            P2_CLI_SERVE_TRAP_BEFORE_SET_COMPONENT,
            core.display(),
            dumped.len(),
            dumped.get(..4).unwrap_or(&[]),
            head,
        );
        assert!(core.exists(), "coredump file was not written: {stderr}");
        assert!(stderr.contains(&format!("core dumped at {}", core.display())));
        assert_eq!(dumped.get(..4), Some(&[0x00, 0x61, 0x73, 0x6d][..]));
        assert_eq!(dumped.get(12..16), Some(&b"core"[..]));
        Ok(())
    }

    #[test]
    fn p3_cli_hello_stdout() -> Result<()> {
        let output = run_wasmtime(&[
            "run",
            "-Wcomponent-model-async",
            "-Sp3",
            P3_CLI_HELLO_STDOUT_COMPONENT,
        ]);
        if cfg!(feature = "component-model-async") {
            let output = output?;
            assert_eq!(output, "hello, world\n");
        } else {
            assert!(output.is_err());
        }
        Ok(())
    }

    #[test]
    fn p2_cli_hello_stdout_invoke() -> Result<()> {
        println!("{P2_CLI_HELLO_STDOUT_COMPONENT}");
        let output = run_wasmtime(&[
            "run",
            "-Wcomponent-model",
            "--invoke",
            "run()",
            P2_CLI_HELLO_STDOUT_COMPONENT,
        ])?;
        // First this component prints "hello, world", then the invoke
        // result is printed as "ok".
        assert_eq!(output, "hello, world\nok\n");
        Ok(())
    }

    #[test]
    fn p3_cli_hello_stdout_post_return() -> Result<()> {
        let output = run_wasmtime(&[
            "run",
            "-Wcomponent-model-async",
            "-Sp3",
            P3_CLI_HELLO_STDOUT_POST_RETURN_COMPONENT,
        ]);
        if cfg!(feature = "component-model-async") {
            let output = output?;
            assert_eq!(output, "hello, world\n");
        } else {
            assert!(output.is_err());
        }
        Ok(())
    }

    #[test]
    fn p3_cli_hello_stdout_post_return_invoke() -> Result<()> {
        let output = run_wasmtime(&[
            "run",
            "-Wcomponent-model-async",
            "-Sp3",
            "--invoke",
            "run()",
            P3_CLI_HELLO_STDOUT_POST_RETURN_COMPONENT,
        ]);
        if cfg!(feature = "component-model-async") {
            let output = output?;
            assert_eq!(output, "hello, world\nok\n");
        } else {
            assert!(output.is_err());
        }
        Ok(())
    }

    #[test]
    fn p2_random_limits() -> Result<()> {
        println!("{P2_RANDOM_COMPONENT}");

        // By default, p2_random.rs fits within the random limits - always
        // asks for 256 bytes.
        let output = run_wasmtime(&["run", P2_RANDOM_COMPONENT])?;
        assert_eq!(output, "");

        // Lowering limit to 255 bytes should produce a trap in the first
        // call, which goes by way of the wasip1 adapter:
        let output = run_wasmtime(&["run", "-Smax-random-size=255", P2_RANDOM_COMPONENT])
            .err()
            .ok_or_else(|| format_err!("execution with max-random-size=255 should trap"))?;
        let output = format!("{output:?}");
        assert!(
            output.contains("lib_generated::random_get"),
            "expected error stack frames to contain 'wasip1::lib_generated::random_get'. Got:\n{output}"
        );
        assert!(
            output.contains("requested len 256 exceeds limit 255"),
            "expected error stack frames to contain 'requested len 256 exceeds limit 255'. Got:\n{output}"
        );

        // Lowering limit to 255 bytes and setting environment variable for
        // the first call to only request 255 bytes should be OK, and then the
        // program produce a trap in the second call, which calls the wasip2
        // random import directly:
        let output = run_wasmtime(&[
            "run",
            "-Smax-random-size=255",
            "--env",
            "TEST_P1_RANDOM_LEN=255",
            P2_RANDOM_COMPONENT,
        ])
        .err()
        .ok_or_else(|| format_err!("execution with max-random-size=255 should trap"))?;
        let output = format!("{output:?}");
        assert!(
            output.contains("random::random::get_random_bytes"),
            "expected error stack frames to contain 'wasi::random::random::get_random_bytes'. Got:\n{output}"
        );
        assert!(
            output.contains("requested len 256 exceeds limit 255"),
            "expected error stack frames to contain 'requested len 256 exceeds limit 255'. Got:\n{output}"
        );

        // Lowering limit to 255 bytes and setting environment variable for
        // the first and second calls to be at the limit should produce a trap
        // in the third call, which calls the wasip2 insecure random import:
        let output = run_wasmtime(&[
            "run",
            "-Smax-random-size=255",
            "--env",
            "TEST_P1_RANDOM_LEN=255",
            "--env",
            "TEST_P2_RANDOM_LEN=255",
            P2_RANDOM_COMPONENT,
        ])
        .err()
        .ok_or_else(|| format_err!("execution with max-random-size=255 should trap"))?;
        let output = format!("{output:?}");
        assert!(
            output.contains("random::insecure::get_insecure_random_bytes"),
            "expected error stack frames to contain 'wasi::random::insecure::get_insecure_random_bytes'. Got:\n{output}"
        );
        assert!(
            output.contains("requested len 256 exceeds limit 255"),
            "expected error stack frames to contain 'requested len 256 exceeds limit 255'. Got:\n{output}"
        );

        // Lowering limit to 255 bytes and setting environment variable for
        // the first and second calls to be under the limit should trap in the
        // third call, which calls the wasip2 insecure random import:
        let output = run_wasmtime(&[
            "run",
            "-Smax-random-size=255",
            "--env",
            "TEST_P1_RANDOM_LEN=255",
            "--env",
            "TEST_P2_RANDOM_LEN=255",
            "--env",
            "TEST_P2_INSECURE_RANDOM_LEN=255",
            P2_RANDOM_COMPONENT,
        ])
        .context("setting all calls to be equal to the limit should pass")?;
        assert_eq!(output, "");

        Ok(())
    }

    #[test]
    fn p2_cli_http_headers() -> Result<()> {
        let td = tempfile::TempDir::new()?;
        let cwasm = td.path().join("http_headers.cwasm");
        let cwasm = cwasm.to_str().unwrap();
        run_wasmtime(&["compile", P2_CLI_HTTP_HEADERS_COMPONENT, "-o", cwasm])?;
        // p2 traps on too-many-fields/size-too-big, so expect error messages.
        for test in ["append", "append-empty", "append-same", "append-same-empty"] {
            let err = run_wasmtime(&[
                "run",
                "-Shttp,p3",
                "-Smax-http-fields-size=1048576",
                "--allow-precompiled",
                cwasm,
                &format!("p2-{test}"),
            ])
            .unwrap_err();
            assert!(
                err.to_string()
                    .contains("total size of fields exceeds limit")
                    || err.to_string().contains("too many fields in the field map"),
                "bad error message: {err:?}"
            );

            // gated by default too
            let err = run_wasmtime(&[
                "run",
                "-Shttp,p3",
                "--allow-precompiled",
                cwasm,
                &format!("p2-{test}"),
            ])
            .unwrap_err();
            assert!(
                err.to_string()
                    .contains("total size of fields exceeds limit"),
                "bad error message: {err:?}"
            );
        }

        // With an extremely large limit Wasmtime still shouldn't panic (p2).
        let err = run_wasmtime(&[
            "run",
            "-Shttp,p3",
            &format!("-Smax-http-fields-size={}", 1 << 30),
            "--allow-precompiled",
            cwasm,
            "p2-append",
        ])
        .unwrap_err();
        assert!(
            err.to_string().contains("too many fields in the field map"),
            "bad error message: {err:?}"
        );

        // p3 returns an error code instead of trapping, so the guest
        // program exits successfully after receiving the error.
        for test in ["append", "append-empty", "append-same", "append-same-empty"] {
            let output = run_wasmtime(&[
                "run",
                "-Shttp,p3",
                "-Smax-http-fields-size=1048576",
                "--allow-precompiled",
                cwasm,
                &format!("p3-{test}"),
            ])?;
            assert!(
                output.contains("error received"),
                "p3-{test}: guest should have received an error"
            );

            // gated by default too
            let output = run_wasmtime(&[
                "run",
                "-Shttp,p3",
                "--allow-precompiled",
                cwasm,
                &format!("p3-{test}"),
            ])?;
            assert!(
                output.contains("error received"),
                "p3-{test} (default limit): guest should have received an error"
            );
        }

        // With an extremely large limit Wasmtime still shouldn't panic (p3).
        let output = run_wasmtime(&[
            "run",
            "-Shttp,p3",
            &format!("-Smax-http-fields-size={}", 1 << 30),
            "--allow-precompiled",
            cwasm,
            "p3-append",
        ])?;
        assert!(
            output.contains("error received"),
            "p3-append (large limit): guest should have received an error"
        );
        Ok(())
    }

    #[test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    fn p2_cli_invoke_async() -> Result<()> {
        let output = run_wasmtime(&[
            "run",
            "-Wcomponent-model-async",
            "--invoke",
            "echo(\"hello?\")",
            P2_CLI_INVOKE_ASYNC_COMPONENT,
        ])?;
        assert_eq!(output, "\"hello?\"\n");
        Ok(())
    }

    fn run_much_stdout(component: &str, extra_flags: &[&str]) -> Result<()> {
        let total_write_size = 1 << 18;
        let expected = iter::repeat('a').take(total_write_size).collect::<String>();

        for i in 10..15 {
            let string = iter::repeat('a').take(1 << i).collect::<String>();
            let times = (total_write_size >> i).to_string();
            println!("writing {} bytes {times} times", string.len());

            let mut args = Vec::new();
            args.push("run");
            args.extend_from_slice(extra_flags);
            args.push(component);
            args.push(&string);
            args.push(&times);
            let output = run_wasmtime(&args)?;
            println!(
                "expected {} bytes, got {} bytes",
                expected.len(),
                output.len()
            );
            assert!(output == expected);
        }

        Ok(())
    }

    #[test]
    fn p1_cli_much_stdout() -> Result<()> {
        run_much_stdout(P1_CLI_MUCH_STDOUT_COMPONENT, &[])
    }

    #[test]
    fn p2_cli_much_stdout() -> Result<()> {
        run_much_stdout(P2_CLI_MUCH_STDOUT_COMPONENT, &[])
    }

    #[test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    fn p3_cli_much_stdout() -> Result<()> {
        run_much_stdout(
            P3_CLI_MUCH_STDOUT_COMPONENT,
            &["-Wcomponent-model-async", "-Sp3"],
        )
    }

    #[test]
    fn p2_cli_max_resources() -> Result<()> {
        let err = run_wasmtime(&["run", "-Smax-resources=50", P2_CLI_MAX_RESOURCES_COMPONENT])
            .unwrap_err();
        assert!(
            err.to_string().contains("resource table has no free keys"),
            "bad error message: {err}"
        );
        run_wasmtime(&["run", "-Smax-resources=200", P2_CLI_MAX_RESOURCES_COMPONENT])?;
        Ok(())
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_hello_world() -> Result<()> {
        cli_serve_hello_world(P3_CLI_SERVE_HELLO_WORLD_COMPONENT, 1, 1, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
        })
        .await
    }

    #[derive(Clone)]
    struct TokioExecutor;

    impl<F> hyper::rt::Executor<F> for TokioExecutor
    where
        F: std::future::Future + Send + 'static,
        F::Output: Send + 'static,
    {
        fn execute(&self, fut: F) {
            tokio::task::spawn(fut);
        }
    }

    /// The client speaks HTTP/2 with prior knowledge, so this only passes if
    /// `serve` accepts h2c connections as well as HTTP/1.1 ones.
    #[tokio::test]
    async fn p2_cli_serve_hello_world_http2() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;

        let tcp = TcpStream::connect(server.first_addr()).await?;
        let (mut send, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor)
            .handshake(wasmtime_wasi_http::io::TokioIo::new(tcp))
            .await
            .context("failed http2 handshake")?;
        let conn_task = tokio::task::spawn(conn);

        let response = send
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await
            .context("error sending request")?;
        assert!(response.status().is_success());

        let body = response
            .into_body()
            .collect()
            .await
            .context("failed to read body")?;
        assert_eq!(std::str::from_utf8(&body.to_bytes())?, "Hello, WASI!");

        drop(send);
        conn_task.await??;

        server.finish()?;
        Ok(())
    }

    async fn h2_request_status(uri: &str, hosts: &[&str]) -> Result<u16> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })?;
        let tcp = TcpStream::connect(server.first_addr()).await?;
        let (mut send, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor)
            .handshake(wasmtime_wasi_http::io::TokioIo::new(tcp))
            .await
            .context("failed http2 handshake")?;
        let mut conn_task = tokio::task::spawn(conn);
        let mut request = hyper::Request::builder()
            .uri(uri)
            .body(String::new())
            .context("failed to make request")?;
        for host in hosts {
            request.headers_mut().append("host", host.parse()?);
        }
        let status = send
            .send_request(request)
            .await
            .context("error sending request")?
            .status()
            .as_u16();
        drop(send);
        if tokio::time::timeout(Duration::from_secs(5), &mut conn_task)
            .await
            .is_err()
        {
            conn_task.abort();
        }
        server.finish()?;
        Ok(status)
    }

    #[tokio::test]
    async fn p2_cli_serve_host_validation_http2() -> Result<()> {
        assert_eq!(h2_request_status("http://a.example/", &[]).await?, 200);
        assert_eq!(
            h2_request_status("http://a.example/", &["a.example", "a.example"]).await?,
            400
        );
        assert_eq!(
            h2_request_status("http://a.example/", &["[email protected]"]).await?,
            400
        );
        assert_eq!(
            h2_request_status("http://a.example/", &["a.example"]).await?,
            200
        );
        assert_eq!(
            h2_request_status("http://a.example/", &["b.example"]).await?,
            400
        );
        assert_eq!(h2_request_status("http://[email protected]/", &[]).await?, 400);
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_hello_world() -> Result<()> {
        cli_serve_hello_world(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, 1, 1, |cmd| {
            cmd.arg("-Scli");
        })
        .await
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_trap_mid_body() -> Result<()> {
        cli_serve_trap_mid_body(P3_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
        })
        .await
    }

    #[tokio::test]
    async fn p2_cli_serve_trap_mid_body() -> Result<()> {
        cli_serve_trap_mid_body(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli");
        })
        .await
    }

    /// A guest trapping while streaming a chunked response body must not
    /// produce a response that looks complete to the client.
    async fn cli_serve_trap_mid_body(
        component: &str,
        configure: impl FnOnce(&mut Command),
    ) -> Result<()> {
        let server = WasmtimeServe::new(component, configure)?;
        let result = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/trap")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await;
        assert!(
            result.is_err(),
            "truncated body looked complete: {result:?}"
        );
        let (_, stderr) = server.finish()?;
        assert!(stderr.contains("unreachable"), "{stderr}");
        Ok(())
    }

    const CONNECTION_COUNT_MANY: usize = 20;
    const REQUESTS_PER_CONNECTION_MANY: usize = 5;

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_hello_world_many() -> Result<()> {
        cli_serve_hello_world(
            P3_CLI_SERVE_HELLO_WORLD_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Wcomponent-model-async");
                cmd.arg("-Sp3,cli");
            },
        )
        .await
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_hello_world_many_no_reuse() -> Result<()> {
        cli_serve_hello_world(
            P3_CLI_SERVE_HELLO_WORLD_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Wcomponent-model-async");
                cmd.arg("-Sp3,cli");
                cmd.arg("--max-instance-reuse-count=1");
            },
        )
        .await
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_hello_world_many_no_concurrent_reuse() -> Result<()> {
        cli_serve_hello_world(
            P3_CLI_SERVE_HELLO_WORLD_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Wcomponent-model-async");
                cmd.arg("-Sp3,cli");
                cmd.arg("--max-instance-concurrent-reuse-count=1");
            },
        )
        .await
    }

    #[tokio::test]
    async fn p2_cli_serve_hello_world_many() -> Result<()> {
        cli_serve_hello_world(
            P2_CLI_SERVE_HELLO_WORLD_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Scli");
            },
        )
        .await
    }

    #[tokio::test]
    async fn p2_cli_serve_hello_world_many_with_reuse() -> Result<()> {
        cli_serve_hello_world(
            P2_CLI_SERVE_HELLO_WORLD_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Scli");
                cmd.arg("--max-instance-reuse-count=128");
            },
        )
        .await
    }

    #[cfg(unix)]
    #[test]
    fn serve_reject_addr_with_systemd_listenfd() -> Result<()> {
        // `--systemd-listenfd` takes the sockets from the environment; an
        // explicit `--addr` used to be accepted and silently ignored.
        let mut cmd = super::get_wasmtime_command()?;
        cmd.args([
            "serve",
            "-Scli",
            "--systemd-listenfd",
            "--addr",
            "127.0.0.1:0",
            P2_CLI_SERVE_HELLO_WORLD_COMPONENT,
        ])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped());
        let mut child = cmd.spawn()?;
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        while child.try_wait()?.is_none() {
            assert!(
                std::time::Instant::now() < deadline,
                "--addr with --systemd-listenfd was accepted and the server kept running"
            );
            thread::sleep(Duration::from_millis(100));
        }
        let output = child.wait_with_output()?;
        assert!(
            !output.status.success(),
            "--addr with --systemd-listenfd was accepted"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("cannot be used with")
                && stderr.contains("--addr")
                && stderr.contains("--systemd-listenfd"),
            "unexpected stderr: {stderr}"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn serve_inherit() -> Result<()> {
        use std::mem::ManuallyDrop;
        use std::net::TcpListener;
        use std::os::fd::{FromRawFd, OwnedFd};
        use std::os::unix::net::UnixListener;
        use std::os::unix::process::CommandExt;
        use tokio::net::UnixStream;

        // We can't easily inherit file descriptors to emulators like QEMU, so skip this test for
        // cross-compiled setups.
        if wasmtime_test_util::cargo_test_runner().is_some() {
            return Ok(());
        }

        // These sockets are required to be inherited to the child process as
        // fds 3 and 4, which is done with `dup2` below. If either socket
        // already lives at fd 3 or 4, however, then the `dup2` calls can
        // clobber one another (e.g. if the unix socket is fd 3 then the first
        // `dup2` closes it) or be a noop leaving a CLOEXEC fd in place. Tests
        // run in parallel so fds 3/4 may be freed by another thread at any
        // time, so unconditionally move both sockets to fds >= 5 to avoid
        // this.
        let tcp_socket = TcpListener::from(rustix::io::fcntl_dupfd_cloexec(
            TcpListener::bind("localhost:0")?,
            5,
        )?);
        tcp_socket.set_nonblocking(true)?;

        let addr = tcp_socket.local_addr()?;
        let (unix_socket, unix_path) = tempfile::Builder::new()
            .make(|path| UnixListener::bind(path))?
            .into_parts();
        let unix_socket = UnixListener::from(rustix::io::fcntl_dupfd_cloexec(unix_socket, 5)?);

        // Using a shell script as a launcher since that uses exec, allowing us to provide the
        // LISTEN_PID variable.
        let mut cmd = Command::new("sh");
        cmd.arg("-c")
            .arg(r#"export LISTEN_FDS=2 LISTEN_PID=$$; exec "$@""#)
            .arg("sh")
            .arg(super::get_wasmtime_path())
            .arg("serve")
            .arg("-Scli")
            .arg("--systemd-listenfd")
            .arg(P2_CLI_SERVE_HELLO_WORLD_COMPONENT)
            .env("WASMTIME_CODEGEN_CACHE", "n");

        unsafe {
            cmd.pre_exec(move || {
                let mut target_3 = ManuallyDrop::new(OwnedFd::from_raw_fd(3));
                let mut target_4 = ManuallyDrop::new(OwnedFd::from_raw_fd(4));
                rustix::io::dup2(&tcp_socket, &mut target_3)?;
                rustix::io::dup2(&unix_socket, &mut target_4)?;
                Ok(())
            });
        }

        let mut server = WasmtimeServe::spawn(&mut cmd, 0)?;
        server.addr.push(addr);
        drop(cmd);
        // Should accept http requests over the TCP socket
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

        assert!(resp.status().is_success());
        assert_eq!(resp.body(), "Hello, WASI!");

        // As well as over the unix socket
        {
            let unix = wasmtime_wasi_http::io::TokioIo::new(
                UnixStream::connect(&unix_path).await.with_context(|| {
                    format!(
                        "failed to connect to unix socket at {}",
                        unix_path.display()
                    )
                })?,
            );
            let (mut send, conn) = hyper::client::conn::http1::handshake(unix)
                .await
                .context("failed http handshake")?;
            let conn_task = tokio::task::spawn(conn);

            let resp = WasmtimeServe::send_request_with(
                &mut send,
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

            assert!(resp.status().is_success());
            assert_eq!(resp.body(), "Hello, WASI!");

            drop(send);
            conn_task.await??;
        }

        let (_, stderr) = server.finish()?;
        assert!(stderr.contains("Serving HTTP on inherited socket"));
        drop(unix_path);

        Ok(())
    }

    #[tokio::test]
    async fn serve_multiple_addresses() -> Result<()> {
        let server = WasmtimeServe::spawn(
            super::get_wasmtime_command()?
                .arg("serve")
                .arg("-Scli")
                .arg("--addr=127.0.0.1:0")
                .arg("--addr=127.0.0.1:0")
                .arg(P2_CLI_SERVE_HELLO_WORLD_COMPONENT),
            2,
        )?;
        assert_eq!(server.addr.len(), 2);
        assert_ne!(server.addr[0], server.addr[1]);

        // Should accept http requests on each address.
        for i in 0..server.addr.len() {
            let (mut send, conn_task) = server.start_requests_at(i).await?;
            let resp = WasmtimeServe::send_request_with(
                &mut send,
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;

            assert!(resp.status().is_success());
            assert_eq!(resp.body(), "Hello, WASI!");

            drop(send);
            conn_task.await??;
        }

        server.finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn serve_idle_process_timeout() -> Result<()> {
        let server = WasmtimeServe::new(P2_CLI_SERVE_HELLO_WORLD_COMPONENT, |cmd| {
            cmd.arg("-Scli").arg("--idle-process-timeout=100ms");
        })?;

        let request = || {
            hyper::Request::builder()
                .uri("http://localhost/")
                .body(String::new())
                .context("failed to make request")
        };

        let (mut send, conn_task) = server.start_requests().await?;
        let resp = WasmtimeServe::send_request_with(&mut send, request()?).await?;
        assert_eq!(resp.body(), "Hello, WASI!");

        // An open connection, even when idle, keeps the process alive.
        tokio::time::sleep(Duration::from_millis(150)).await;

        let resp = WasmtimeServe::send_request_with(&mut send, request()?).await?;
        assert_eq!(resp.body(), "Hello, WASI!");

        // Once the connection is closed the process exits.
        drop(send);
        conn_task.await??;
        server.wait()?;
        Ok(())
    }

    async fn cli_serve_hello_world(
        component: &str,
        connection_count: usize,
        requests_per_connection: usize,
        configure: impl FnOnce(&mut Command),
    ) -> Result<()> {
        let server = std::sync::Arc::new(WasmtimeServe::new(component, configure)?);

        let tasks = (0..connection_count).map({
            let server = server.clone();
            move |_| {
                tokio::task::spawn({
                    let server = server.clone();
                    async move {
                        let (mut send, conn_task) = server.start_requests().await?;

                        for _ in 0..requests_per_connection {
                            let result = WasmtimeServe::send_request_with(
                                &mut send,
                                hyper::Request::builder()
                                    .uri("http://localhost/")
                                    .body(String::new())
                                    .context("failed to make request")?,
                            )
                            .await?;

                            assert!(result.status().is_success());
                            assert_eq!(result.body(), "Hello, WASI!");
                        }

                        drop(send);

                        conn_task.await??;

                        wasmtime::error::Ok(())
                    }
                })
            }
        });

        for task in tasks {
            task.await??;
        }

        std::sync::Arc::into_inner(server).unwrap().finish()?;
        Ok(())
    }

    #[tokio::test]
    async fn p2_cli_serve_sleep() -> Result<()> {
        cli_serve_sleep(P2_CLI_SERVE_SLEEP_COMPONENT, 1, 1, |cmd| {
            cmd.arg("-Scli");
        })
        .await
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_sleep() -> Result<()> {
        cli_serve_sleep(P3_CLI_SERVE_SLEEP_COMPONENT, 1, 1, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
        })
        .await
    }

    #[tokio::test]
    async fn p2_cli_serve_sleep_many() -> Result<()> {
        cli_serve_sleep(
            P2_CLI_SERVE_SLEEP_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Scli");
            },
        )
        .await
    }

    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_sleep_many() -> Result<()> {
        cli_serve_sleep(
            P3_CLI_SERVE_SLEEP_COMPONENT,
            CONNECTION_COUNT_MANY,
            REQUESTS_PER_CONNECTION_MANY,
            |cmd| {
                cmd.arg("-Wcomponent-model-async");
                cmd.arg("-Sp3,cli");
            },
        )
        .await
    }

    async fn cli_serve_sleep(
        component: &str,
        connection_count: usize,
        requests_per_connection: usize,
        configure: impl FnOnce(&mut Command),
    ) -> Result<()> {
        let server = std::sync::Arc::new(WasmtimeServe::new(component, move |cmd| {
            configure(cmd);
            cmd.arg("-Wtimeout=100us");
        })?);

        let tasks = (0..connection_count).map({
            let server = server.clone();
            move |_| {
                tokio::task::spawn({
                    let server = server.clone();
                    async move {
                        let (mut send, conn_task) = server.start_requests().await?;

                        for _ in 0..requests_per_connection {
                            let result = WasmtimeServe::send_request_with(
                                &mut send,
                                hyper::Request::builder()
                                    .uri("http://localhost/")
                                    .body(String::new())
                                    .context("failed to make request")?,
                            )
                            .await?;

                            assert!(result.status().is_server_error());
                        }

                        drop(send);

                        conn_task.await??;

                        wasmtime::error::Ok(())
                    }
                })
            }
        });

        for task in tasks {
            task.await??;
        }

        let (stdout, stderr) = std::sync::Arc::into_inner(server).unwrap().finish()?;
        assert_eq!(stdout, "");
        assert!(stderr.contains("guest timed out"), "bad stderr: {stderr}");
        Ok(())
    }

    #[test]
    fn p2_cli_many_resources() -> Result<()> {
        let err = run_wasmtime(&[
            "run",
            "-Smax-resources=100",
            P2_CLI_MANY_RESOURCES_COMPONENT,
        ])
        .unwrap_err();
        assert!(
            err.to_string().contains("resource table has no free keys"),
            "bad error message: {err}"
        );
        Ok(())
    }

    #[test]
    fn p3_cli_many_tasks() -> Result<()> {
        let err = run_wasmtime(&[
            "run",
            "-Smax-resources=100",
            "-Sp3",
            "-Wcomponent-model-async",
            dbg!(P3_CLI_MANY_TASKS_COMPONENT),
        ])
        .unwrap_err();
        assert!(
            err.to_string().contains("resource table has no free keys"),
            "bad error message: {err}"
        );
        Ok(())
    }

    #[test]
    fn p1_cli_hostcall_fuel() -> Result<()> {
        let dir = tempfile::tempdir()?;
        run_wasmtime(&[
            "run",
            &format!("--dir={}::.", dir.path().to_str().unwrap()),
            "-Shostcall-fuel=1000",
            P1_CLI_HOSTCALL_FUEL,
        ])?;
        Ok(())
    }

    #[test]
    fn p2_cli_hostcall_fuel() -> Result<()> {
        enum Exit {
            Ok,
            NoFuel,
            TooManyZeroes,
            BufferTooLarge,
        }

        let dir = tempfile::tempdir()?;
        let file = dir.path().join("1mb");
        std::fs::write(&file, vec![0; 1024 * 1024])?;
        for (arg, exit) in [
            ("poll", Exit::NoFuel),
            ("read", Exit::Ok),
            ("write", Exit::NoFuel),
            ("mkdir", Exit::NoFuel),
            ("write-stream", Exit::NoFuel),
            ("write-stream-blocking", Exit::NoFuel),
            ("resolve", Exit::NoFuel),
            ("udp-send-many", Exit::NoFuel),
            ("udp-send-big", Exit::NoFuel),
            ("write-zeroes", Exit::TooManyZeroes),
            ("write-stream-buffer-too-large", Exit::BufferTooLarge),
            ("write-zeroes-buffer-too-large", Exit::BufferTooLarge),
            ("read-file-big", Exit::Ok),
            ("read-tcp-big", Exit::Ok),
        ] {
            println!("test: {arg}");
            let result = run_wasmtime(&[
                "run",
                "-Shostcall-fuel=5000",
                "-Sinherit-network",
                &format!("--dir={}::.", dir.path().to_str().unwrap()),
                P2_CLI_HOSTCALL_FUEL_COMPONENT,
                arg,
            ]);

            match exit {
                Exit::Ok => {
                    result.unwrap();
                }
                Exit::NoFuel => {
                    let err = result.unwrap_err();
                    assert!(
                        err.to_string()
                            .contains("fuel allocated for hostcalls has been exhausted"),
                        "bad error message: {err}"
                    );
                }
                Exit::TooManyZeroes => {
                    let err = result.unwrap_err();
                    assert!(
                        err.to_string()
                            .contains("cannot write more zeroes than `check_write` allows"),
                        "bad error message: {err}"
                    );
                }
                Exit::BufferTooLarge => {
                    let err = result.unwrap_err();
                    assert!(
                        err.to_string().contains("Buffer too large"),
                        "bad error message: {err}"
                    );
                }
            }
        }
        Ok(())
    }

    #[test]
    fn p3_cli_random_limits() -> Result<()> {
        let c = P3_CLI_RANDOM_LIMITS_COMPONENT;

        for rand in ["random", "insecure"] {
            run_wasmtime(&["run", "-Sp3", "-Wcomponent-model-async", c, rand, "256"])?;
            run_wasmtime(&[
                "run",
                "-Sp3",
                "-Wcomponent-model-async",
                "-Smax-random-size=255",
                c,
                rand,
                "256",
            ])?;
        }

        Ok(())
    }

    #[test]
    fn p3_cli_read_stdin() -> Result<()> {
        let mut cmd = get_wasmtime_command()?;
        let mut child = cmd
            .arg("-Sp3")
            .arg("-Wcomponent-model-async")
            .arg(P3_CLI_READ_STDIN_COMPONENT)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"hello!").unwrap();
        let output = child.wait_with_output()?;
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        assert!(output.status.success());

        Ok(())
    }

    #[test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    fn p3_cli_stdout_flush() -> Result<()> {
        let mut child = get_wasmtime_command()?
            .arg("-Sp3")
            .arg("-Wcomponent-model-async")
            .arg(P3_CLI_STDOUT_FLUSH_COMPONENT)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        let mut stdin = child.stdin.take().unwrap();
        let mut stdout = child.stdout.take().unwrap();

        let (tx, rx) = std::sync::mpsc::channel();
        let reader = thread::spawn(move || {
            let mut buf = [0u8; 5];
            let res = stdout.read_exact(&mut buf).map(|()| buf);
            let _ = tx.send(res);
        });

        let buf = match rx.recv_timeout(Duration::from_secs(100)) {
            Ok(Ok(buf)) => buf,
            Ok(Err(e)) => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(e.into());
            }
            Err(_) => {
                let _ = child.kill();
                let _ = child.wait();
                let _ = reader.join();
                panic!("guest stdout was not flushed");
            }
        };
        assert_eq!(&buf, b"READY");

        stdin.write_all(b"x")?;
        drop(stdin);

        let output = child.wait_with_output()?;
        reader.join().unwrap();
        assert!(output.status.success());

        Ok(())
    }

    #[tokio::test]
    async fn p3_cli_serve_post_return() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_POST_RETURN_COMPONENT, move |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
            cmd.arg("--max-instance-reuse-count=1");
        })?;
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());
        assert!(resp.body().is_empty());

        let (stdout, stderr) = server.finish()?;
        println!("stdout: {stdout}");
        println!("stderr: {stderr}");

        assert!(stdout.contains("please see me"));
        Ok(())
    }

    /// The streamed body outlives `-W timeout` when `--post-return-timeout`
    /// gives post-return work a longer limit.
    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_post_return_stream() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_POST_RETURN_STREAM_COMPONENT, move |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
            cmd.arg("-Wtimeout=1s");
            cmd.arg("--post-return-timeout=60s");
        })?;
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());
        assert_eq!(resp.body(), "123");

        server.finish()?;
        Ok(())
    }

    /// With only `-W timeout` set, the post-return timeout inherits it, so the
    /// ~3s body stream is cut off after ~1s.
    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_post_return_stream_default_timeout() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_POST_RETURN_STREAM_COMPONENT, move |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
            cmd.arg("-Wtimeout=1s");
        })?;
        let resp = server
            .send_request(
                hyper::Request::builder()
                    .uri("http://localhost/")
                    .body(String::new())
                    .context("failed to make request")?,
            )
            .await?;
        assert!(resp.status().is_success());
        assert!(
            resp.body().starts_with("1") && resp.body() != "123",
            "expected the post-return timeout to cut off the stream; got {:?}",
            resp.body()
        );

        let (_stdout, stderr) = server.finish()?;
        assert!(stderr.contains("guest timed out"), "stderr: {stderr}");
        Ok(())
    }

    /// With only `--post-return-timeout` set, post-return work that is blocked
    /// in a filesystem call is still cut off when the deadline elapses.
    #[cfg(unix)]
    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_post_return_blocking_open() -> Result<()> {
        use std::os::unix::ffi::OsStrExt;

        let dir = tempfile::TempDir::new()?;
        let fifo = dir.path().join("fifo");
        let path = std::ffi::CString::new(fifo.as_os_str().as_bytes())?;
        // SAFETY: `path` is a valid NUL-terminated string that outlives the call.
        if unsafe { libc::mkfifo(path.as_ptr(), 0o600) } != 0 {
            bail!("failed to create fifo: {}", io::Error::last_os_error());
        }

        let server = WasmtimeServe::new(P3_CLI_SERVE_POST_RETURN_BLOCKING_OPEN_COMPONENT, |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
            cmd.arg("--post-return-timeout=1s");
            cmd.arg(format!("--dir={}::/", dir.path().display()));
        })?;

        let request = hyper::Request::builder()
            .uri("http://localhost/")
            .body(String::new())
            .context("failed to make request")?;
        let resp = tokio::time::timeout(Duration::from_secs(30), server.send_request(request))
            .await
            .context("request did not complete within 30s")??;
        assert!(resp.status().is_success());
        assert!(
            resp.body().is_empty(),
            "expected the instance to be dropped while its open was still blocked; got {:?}",
            resp.body()
        );

        // The guest's open is still blocked on a background thread; give it a
        // writer so the server can shut down.
        thread::spawn(move || std::fs::OpenOptions::new().write(true).open(fifo));

        let (_stdout, stderr) = server.finish()?;
        assert!(stderr.contains("guest timed out"), "stderr: {stderr}");
        Ok(())
    }

    #[cfg(not(unix))]
    #[tokio::test]
    async fn p3_cli_serve_post_return_blocking_open() -> Result<()> {
        Ok(())
    }

    /// With only `--post-return-timeout` set, post-return work that never
    /// yields is still cut off when the deadline elapses.
    #[tokio::test]
    #[cfg_attr(not(feature = "component-model-async"), ignore)]
    async fn p3_cli_serve_post_return_spin() -> Result<()> {
        let server = WasmtimeServe::new(P3_CLI_SERVE_POST_RETURN_SPIN_COMPONENT, move |cmd| {
            cmd.arg("-Wcomponent-model-async");
            cmd.arg("-Sp3,cli");
            cmd.arg("--post-return-timeout=1s");
        })?;
        let request = hyper::Request::builder()
            .uri("http://localhost/")
            .body(String::new())
            .context("failed to make request")?;
        let resp = tokio::time::timeout(Duration::from_secs(30), server.send_request(request))
            .await
            .context("request did not complete within 30s")??;
        assert!(resp.status().is_success());
        assert!(resp.body().is_empty(), "got {:?}", resp.body());

        let (_stdout, stderr) = server.finish()?;
        assert!(stderr.contains("guest timed out"), "stderr: {stderr}");
        Ok(())
    }

    #[test]
    fn p3_cli_many_stream() -> Result<()> {
        run_wasmtime(&["run", "-Smax-resources=100", P3_CLI_MANY_STREAM_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p3_cli_deny_listen() -> Result<()> {
        run_wasmtime(&["run", "-Stcp", P3_CLI_DENY_LISTEN_COMPONENT])?;
        Ok(())
    }

    #[test]
    fn p2_cli_stdout_write_too_much() -> Result<()> {
        // With `-Sinherit-stdout=n` stdout is a sink, so writing past the
        // permit reported by `check-write` has to trap.
        let output = super::wasmtime(&[
            "run",
            "-Sinherit-stdout=n",
            P2_CLI_STDOUT_WRITE_TOO_MUCH_COMPONENT,
        ])?
        .output()?;
        // The stdout stream is a sink, so nothing is expected on stdout.
        assert_eq!(output.stdout, b"");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("write exceeded budget"),
            "bad stderr: {stderr}"
        );
        Ok(())
    }

    #[test]
    fn p2_cli_stdout_write_zeros_to_sink() -> Result<()> {
        for n in ["0", "100", "10000"] {
            run_wasmtime(&[
                "run",
                "-Sinherit-stdout=n",
                P2_CLI_STDOUT_WRITE_ZEROS_TO_SINK_COMPONENT,
                n,
            ])?;
        }
        let output = super::wasmtime(&[
            "run",
            "-Sinherit-stdout=n",
            P2_CLI_STDOUT_WRITE_ZEROS_TO_SINK_COMPONENT,
            "10000000000",
        ])?
        .output()?;
        assert_eq!(output.stdout, b"");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("cannot write more zeroes than `check_write` allows"),
            "bad stderr: {stderr}"
        );
        Ok(())
    }
}

#[test]
fn settings_command() -> Result<()> {
    // Skip this test on platforms that Cranelift doesn't support.
    if cranelift_native::builder().is_err() {
        return Ok(());
    }
    let output = run_wasmtime(&["settings"])?;
    assert!(output.contains("Cranelift settings for target"));
    Ok(())
}

#[cfg(target_arch = "x86_64")]
#[test]
fn profile_with_vtune() -> Result<()> {
    if !is_vtune_available() {
        println!("> `vtune` is not available on the system path; skipping test");
        return Ok(());
    }

    let mut bin = Command::new("vtune");
    bin.args(&[
        // Configure VTune...
        "-verbose",
        "-collect",
        "hotspots",
        "-user-data-dir",
        &std::env::temp_dir().to_string_lossy(),
        // ...then run Wasmtime with profiling enabled:
        get_wasmtime_path(),
        "--profile=vtune",
        "tests/all/cli_tests/simple.wat",
    ]);

    println!("> executing: {bin:?}");
    let stdout = run_cmd(&mut bin)?;

    println!("> stdout:\n{stdout}");
    assert!(stdout.contains("CPU Time"));
    Ok(())
}

#[cfg(target_arch = "x86_64")]
fn is_vtune_available() -> bool {
    Command::new("vtune").arg("-version").output().is_ok()
}

#[test]
fn profile_guest() -> Result<()> {
    let tmpdir = std::env::temp_dir();
    let dir = tmpdir.to_string_lossy();

    let stdout = run_wasmtime(&[
        &format!("--profile=guest,{dir}/out.json"),
        "--env",
        "FOO=bar",
        "tests/all/cli_tests/print_env.wat",
    ])?;

    println!("> stdout:\n{stdout}");
    let out_json = std::fs::read_to_string(format!("{dir}/out.json")).unwrap();
    println!("> out.json:\n{out_json}");
    Ok(())
}

#[test]
fn unreachable_without_wasi() -> Result<()> {
    let output = wasmtime(&["-Scli=n", "tests/all/cli_tests/unreachable.wat"])?.output()?;

    assert_ne!(output.stderr, b"");
    assert_eq!(output.stdout, b"");
    assert_trap_code(&output.status);
    Ok(())
}

#[test]
fn config_cli_flag() -> Result<()> {
    // Test some valid TOML values
    let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts();
    cfg.write_all(
        br#"
        [optimize]
        opt-level = 2
        signals-based-traps = false

        [codegen]
        collector = "null"

        [debug]
        address-map = true

        [wasm]
        max-wasm-stack = 65536

        [wasi]
        cli = true
        "#,
    )?;
    let output = run_wasmtime(&[
        "run",
        "--config",
        cfg_path.to_str().unwrap(),
        "--invoke",
        "get_f64",
        "tests/all/cli_tests/simple.wat",
    ])?;
    assert_eq!(output, "100\n");

    // Make sure CLI flags overrides TOML values
    let output = run_wasmtime(&[
        "run",
        "--config",
        cfg_path.to_str().unwrap(),
        "--invoke",
        "get_f64",
        "-W",
        "max-wasm-stack=0", // should override TOML value 65536 specified above and execution should fail
        "tests/all/cli_tests/simple.wat",
    ]);
    assert!(
        output
            .as_ref()
            .unwrap_err()
            .to_string()
            .contains("max_wasm_stack size cannot be zero"),
        "'{output:?}' did not contain expected error message",
    );

    // Test invalid TOML key
    let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts();
    cfg.write_all(
        br#"
        [optimize]
        this-key-does-not-exist = true
        "#,
    )?;
    let output = run_wasmtime(&[
        "run",
        "--config",
        cfg_path.to_str().unwrap(),
        "tests/all/cli_tests/simple.wat",
    ]);
    assert!(
        output
            .as_ref()
            .unwrap_err()
            .to_string()
            .contains("unknown field `this-key-does-not-exist`"),
        "'{output:?}' did not contain expected error message"
    );

    // Test invalid TOML table
    let (mut cfg, cfg_path) = tempfile::NamedTempFile::new()?.into_parts();
    cfg.write_all(
        br#"
        [invalid_table]
        "#,
    )?;
    let output = run_wasmtime(&[
        "run",
        "--config",
        cfg_path.to_str().unwrap(),
        "tests/all/cli_tests/simple.wat",
    ]);
    assert!(
        output
            .as_ref()
            .unwrap_err()
            .to_string()
            .contains("unknown field `invalid_table`, expected one of `optimize`, `codegen`, `debug`, `wasm`, `wasi`"),
        "'{output:?}' did not contain expected error message",
    );

    Ok(())
}

#[test]
fn invalid_subcommand() -> Result<()> {
    let output = wasmtime(&["invalid-subcommand"])?.output()?;
    dbg!(&output);
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("invalid-subcommand"));
    Ok(())
}

#[test]
fn numeric_args() -> Result<()> {
    // Test decimal i32
    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "i32_test",
        "tests/all/cli_tests/numeric_args.wat",
        "42",
    ])?;
    assert_eq!(output, "42\n");
    // Test hexadecimal i32 with lowercase prefix
    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "i32_test",
        "tests/all/cli_tests/numeric_args.wat",
        "0x2A",
    ])?;
    assert_eq!(output, "42\n");
    // Test hexadecimal i32 with uppercase prefix
    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "i32_test",
        "tests/all/cli_tests/numeric_args.wat",
        "0X2a",
    ])?;
    assert_eq!(output, "42\n");
    // Test that non-prefixed hex strings are not interpreted as hex
    let output = wasmtime(&[
        "run",
        "--invoke",
        "i32_test",
        "tests/all/cli_tests/numeric_args.wat",
        "ff",
    ])?
    .output()?;
    assert!(!output.status.success()); // Should fail as "ff" is not a valid decimal number

    // Test decimal i64
    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "i64_test",
        "tests/all/cli_tests/numeric_args.wat",
        "42",
    ])?;
    assert_eq!(output, "42\n");
    // Test hexadecimal i64
    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "i64_test",
        "tests/all/cli_tests/numeric_args.wat",
        "0x2A",
    ])?;
    assert_eq!(output, "42\n");
    Ok(())
}

#[test]
fn compilation_logs() -> Result<()> {
    let temp = tempfile::NamedTempFile::new()?;
    run_cmd(
        wasmtime(&[
            "compile",
            "-Wgc",
            "tests/all/cli_tests/issue-10353.wat",
            "--output",
            &temp.path().display().to_string(),
        ])?
        .env("WASMTIME_LOG", "trace")
        .env("RUST_BACKTRACE", "1"),
    )?;
    Ok(())
}

#[test]
fn big_table_in_pooling_allocator() -> Result<()> {
    // Works by default
    run_wasmtime(&["tests/all/cli_tests/big_table.wat"])?;

    // Does not work by default in the pooling allocator, and the error message
    // should mention something about the pooling allocator.
    let output =
        wasmtime(&["-Opooling-allocator", "tests/all/cli_tests/big_table.wat"])?.output()?;
    assert!(!output.status.success());
    println!("{}", String::from_utf8_lossy(&output.stderr));
    assert!(String::from_utf8_lossy(&output.stderr).contains("pooling allocator"));

    // Does work with `-Wmax-table-elements`
    run_wasmtime(&[
        "-Opooling-allocator",
        "-Wmax-table-elements=25000",
        "tests/all/cli_tests/big_table.wat",
    ])?;
    // Also works with `-Opooling-table-elements`
    run_wasmtime(&[
        "-Opooling-allocator",
        "-Opooling-table-elements=25000",
        "tests/all/cli_tests/big_table.wat",
    ])?;
    Ok(())
}

fn wizen(args: &[&str], wasm: impl AsRef<[u8]>) -> Result<Output> {
    let mut cmd = get_wasmtime_command()?;
    cmd.arg("wizer").args(args).arg("-");
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn()?;
    let mut stdin = child.stdin.take().unwrap();
    stdin.write_all(wasm.as_ref())?;
    drop(stdin);

    let output = child.wait_with_output()?;
    if !output.status.success() {
        println!(
            "Failed to execute wasmtime wizer with: {cmd:?}\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(output)
}

#[test]
fn wizer_no_imports_by_default() -> Result<()> {
    let result = wizen(
        &[],
        r#"(module
            (func (export "wizer-initialize"))
        )"#,
    )?;
    assert!(result.status.success());

    let result = wizen(
        &[],
        r#"(module
            (import "foo" "bar" (func))
            (func (export "wizer-initialize"))
        )"#,
    )?;
    assert!(!result.status.success());

    let result = wizen(
        &[],
        r#"(module
            (import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))
            (func (export "wizer-initialize"))
        )"#,
    )?;
    assert!(!result.status.success());

    let result = wizen(
        &["-Scli"],
        r#"(module
            (import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))
            (func (export "wizer-initialize"))
        )"#,
    )?;
    assert!(result.status.success());

    Ok(())
}

#[test]
fn wizer_components() -> Result<()> {
    let result = wizen(
        &[],
        r#"
(component
  (core module $a
    (global (mut i32) (i32.const 0))
    (func (export "init")
        i32.const 100
        global.set 0)
  )
  (core instance $a (instantiate $a))
  (func (export "wizer-initialize") (canon lift (core func $a "init")))
)
        "#,
    )?;
    assert!(result.status.success());

    let component_with_wasi = r#"
(component
  (import "wasi:cli/[email protected]" (instance
    (export "get-arguments" (func (result (list string))))
  ))
  (core module $a
    (global (mut i32) (i32.const 0))
    (func (export "init")
        i32.const 100
        global.set 0)
  )
  (core instance $a (instantiate $a))
  (func (export "wizer-initialize") (canon lift (core func $a "init")))
)
        "#;

    let result = wizen(&[], component_with_wasi)?;
    assert!(!result.status.success());
    let result = wizen(&["-Scli"], component_with_wasi)?;
    assert!(result.status.success());

    Ok(())
}

#[test]
fn wizer_components_wave() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let output = run_wasmtime(&[
        "wizer",
        "-Scli",
        "--keep-init-func=true",
        "--init-func",
        "local:local/[email protected](\"hello, world\")",
        test_programs_artifacts::WIZER_COMPONENT_INTERFACES_COMPONENT,
        "-o",
        dir.path().join("stage1.wasm").to_str().unwrap(),
    ])?;

    assert_eq!(output, "[str(\"hello, world\")]\n");

    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "local:local/[email protected]()",
        dir.path().join("stage1.wasm").to_str().unwrap(),
    ])?;

    assert_eq!(output, "[str(\"hello, world\")]\n");

    let output = run_wasmtime(&[
        "wizer",
        "-Scli",
        "--keep-init-func=true",
        "--init-func",
        "local:local/[email protected](12345)",
        dir.path().join("stage1.wasm").to_str().unwrap(),
        "-o",
        dir.path().join("stage2.wasm").to_str().unwrap(),
    ])?;
    assert_eq!(output, "[str(\"hello, world\"), int(12345)]\n");

    let output = run_wasmtime(&[
        "wizer",
        "-Scli",
        "--keep-init-func=true",
        "--init-func",
        "local:local/[email protected](\"wave is pretty cool\")",
        dir.path().join("stage2.wasm").to_str().unwrap(),
        "-o",
        dir.path().join("stage3.wasm").to_str().unwrap(),
    ])?;
    assert_eq!(
        output,
        "[str(\"hello, world\"), int(12345), str(\"wave is pretty cool\")]\n"
    );

    let output = run_wasmtime(&[
        "run",
        "--invoke",
        "local:local/[email protected]()",
        dir.path().join("stage3.wasm").to_str().unwrap(),
    ])?;

    assert_eq!(
        output,
        "[str(\"hello, world\"), int(12345), str(\"wave is pretty cool\")]\n"
    );
    Ok(())
}

#[test]
#[cfg_attr(not(target_os = "linux"), ignore)]
fn hot_blocks_fib() -> Result<()> {
    // This test requires `perf` to be available and usable on the system. Skip
    // if it is not installed or we do not have permissions to `perf record`.
    let perf_check = Command::new("perf").args(&["record", "--", "ls"]).output();
    if perf_check.is_err() || !perf_check.unwrap().status.success() {
        eprintln!("skipping hot_blocks_fib: perf not available");
        return Ok(());
    }

    let output = wasmtime(&[
        "hot-blocks",
        "--event",
        "instructions",
        "--percent",
        "90",
        "tests/all/cli_tests/fib.wat",
    ])?
    .output()?;

    // The command should succeed.
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // perf may fail due to permissions (perf_event_paranoid), which is OK
        // in CI. Just skip in that case.
        if stderr.contains("perf_event_open")
            || stderr.contains("permission")
            || stderr.contains("not permitted")
        {
            eprintln!("skipping hot_blocks_fib: perf permission denied");
            return Ok(());
        }
        bail!(
            "hot-blocks failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            stderr
        );
    }

    let stdout = String::from_utf8_lossy(&output.stdout);

    // The output should mention the function and basic block info.
    // We don't assert exact percentages since they vary by run.
    assert!(
        stdout.contains("block") || stdout.contains("function"),
        "expected hot-blocks output to contain block/function info, got:\n{stdout}"
    );
    assert!(
        stdout.contains("[Assembly]") || stdout.contains("total samples"),
        "expected hot-blocks output to contain column headers or sample info, got:\n{stdout}"
    );

    Ok(())
}

#[test]
#[cfg(unix)]
fn non_utf8_raises_error() -> Result<()> {
    use std::ffi::{OsStr, OsString};
    use std::os::unix::prelude::*;

    let invalid_utf8 = OsStr::from_bytes(b"\xFF");

    // If everything is valid this should succeed...
    run_wasmtime(&["-Sinherit-env", "tests/all/cli_tests/simple.wat"])?;

    // -Sinherit-env
    {
        let output = wasmtime(&["-Sinherit-env", "tests/all/cli_tests/simple.wat"])?
            .env("HI", invalid_utf8)
            .output()?;
        if output.status.success() {
            bail!("should have failed: {output:?}")
        }
    }
    // --env=HI
    {
        let output = wasmtime(&["--env=HI", "tests/all/cli_tests/simple.wat"])?
            .env("HI", invalid_utf8)
            .output()?;
        if output.status.success() {
            bail!("should have failed: {output:?}")
        }
    }
    // --env=HI=$bad
    {
        let mut bad = OsString::from("--env=HI=");
        bad.push(invalid_utf8);
        let output = get_wasmtime_command()?
            .arg(&bad)
            .arg("tests/all/cli_tests/simple.wat")
            .output()?;
        if output.status.success() {
            bail!("should have failed: {output:?}")
        }
    }
    // $bad (bare argument)
    {
        let output = wasmtime(&["tests/all/cli_tests/simple.wat"])?
            .arg(invalid_utf8)
            .output()?;
        if output.status.success() {
            bail!("should have failed: {output:?}")
        }
    }
    Ok(())
}

#[test]
fn compile_empty_component_with_debug_info() -> Result<()> {
    // A component with no core modules reached simulated-DWARF generation with
    // nothing to describe, which used to panic instead of compiling.
    let td = TempDir::new()?;
    let cwasm = td.path().join("empty-component.cwasm");
    let stdout = run_wasmtime(&[
        "compile",
        "-D",
        "debug-info=y",
        "tests/all/cli_tests/empty_component.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?;
    assert_eq!(stdout, "");
    Ok(())
}

#[test]
fn environment_configuration() -> Result<()> {
    let td = TempDir::new()?;
    let cwasm = td.path().join("empty-component.cwasm");
    run_wasmtime(&[
        "compile",
        "tests/all/cli_tests/empty_component.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?;

    // Pass option bag of arguments
    let output = wasmtime(&[
        "compile",
        "tests/all/cli_tests/empty_component.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?
    .env("WASMTIME_WASM", "component-model=n")
    .output()?;
    assert!(!output.status.success());

    // Pass specific argument
    let output = wasmtime(&[
        "compile",
        "tests/all/cli_tests/empty_component.wat",
        "-o",
        cwasm.to_str().unwrap(),
    ])?
    .env("WASMTIME_WASM_COMPONENT_MODEL", "n")
    .output()?;
    assert!(!output.status.success());

    // Pass invalid argument
    let output = wasmtime(&["tests/all/cli_tests/simple.wat"])?
        .env("WASMTIME_WASM_COMPONENT_MODEL", "invalid")
        .output()?;
    assert!(!output.status.success());
    let output = wasmtime(&["tests/all/cli_tests/simple.wat"])?
        .env("WASMTIME_WASM", "invalid")
        .output()?;
    assert!(!output.status.success());

    // CLI overrides env vars
    run_cmd(
        wasmtime(&[
            "compile",
            "-Wcomponent-model",
            "tests/all/cli_tests/empty_component.wat",
            "-o",
            cwasm.to_str().unwrap(),
        ])?
        .env("WASMTIME_WASM_COMPONENT_MODEL", "n"),
    )?;
    run_cmd(
        wasmtime(&[
            "compile",
            "-Wcomponent-model",
            "tests/all/cli_tests/empty_component.wat",
            "-o",
            cwasm.to_str().unwrap(),
        ])?
        .env("WASMTIME_WASM", "component-model=n"),
    )?;

    // specific env var overrides general
    run_cmd(
        wasmtime(&[
            "compile",
            "tests/all/cli_tests/empty_component.wat",
            "-o",
            cwasm.to_str().unwrap(),
        ])?
        .env("WASMTIME_WASM", "component-model=n")
        .env("WASMTIME_WASM_COMPONENT_MODEL", "y"),
    )?;
    Ok(())
}

#[test]
fn unsafe_intrinsics_bare_flag() -> Result<()> {
    // The bare flag defaults the import name to `unsafe-intrinsics`, which is
    // what the component imports.
    run_wasmtime(&[
        "-Wcomponent-model",
        "-C",
        "unsafe-intrinsics",
        "tests/all/cli_tests/unsafe-intrinsics.wat",
    ])?;
    Ok(())
}

#[test]
fn unsafe_intrinsics_named() -> Result<()> {
    run_wasmtime(&[
        "-Wcomponent-model",
        "-C",
        "unsafe-intrinsics=unsafe-intrinsics",
        "tests/all/cli_tests/unsafe-intrinsics.wat",
    ])?;

    // Exposing the intrinsics under a different name leaves the component's
    // import unsatisfied.
    let output = get_wasmtime_command()?
        .args(&[
            "-Wcomponent-model",
            "-C",
            "unsafe-intrinsics=some-other-name",
            "tests/all/cli_tests/unsafe-intrinsics.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("component imports instance `unsafe-intrinsics`"),
        "bad stderr: {stderr}"
    );

    Ok(())
}

#[test]
fn unsafe_intrinsics_rejects_core_module() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&["-C", "unsafe-intrinsics", "tests/all/cli_tests/simple.wat"])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("can only be used with components"),
        "bad stderr: {stderr}"
    );
    Ok(())
}

#[test]
fn compile_time_builtins() -> Result<()> {
    // The main component traps unless both builtins are actually linked in and
    // return their expected values.
    run_wasmtime(&[
        "-Wcomponent-model",
        "-C",
        "unsafe-intrinsics",
        "-C",
        "inlining=y",
        "-C",
        "compile-time-builtin=host-api-a=tests/all/cli_tests/host-api-a.wat",
        "-C",
        "compile-time-builtin=host-api-b=tests/all/cli_tests/host-api-b.wat",
        "tests/all/cli_tests/compile-time-builtin-main.wat",
    ])?;
    Ok(())
}

#[test]
fn compile_time_builtin_name_defaults_to_file_stem() -> Result<()> {
    // Both fixtures' file stems are exactly the import names they satisfy, so
    // the `<name>=` prefix can be omitted.
    run_wasmtime(&[
        "-Wcomponent-model",
        "-C",
        "unsafe-intrinsics",
        "-C",
        "compile-time-builtin=tests/all/cli_tests/host-api-a.wat",
        "-C",
        "compile-time-builtin=tests/all/cli_tests/host-api-b.wat",
        "tests/all/cli_tests/compile-time-builtin-main.wat",
    ])?;

    // A file whose stem is *not* the import name leaves `host-api-b`
    // unsatisfied.
    let td = TempDir::new()?;
    let other = td.path().join("some-other-name.wat");
    std::fs::copy("tests/all/cli_tests/host-api-b.wat", &other)?;
    let output = get_wasmtime_command()?
        .args(&[
            "-Wcomponent-model",
            "-C",
            "unsafe-intrinsics",
            "-C",
            "compile-time-builtin=tests/all/cli_tests/host-api-a.wat",
            "-C",
            &format!("compile-time-builtin={}", other.display()),
            "tests/all/cli_tests/compile-time-builtin-main.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("host-api-b"), "bad stderr: {stderr}");

    Ok(())
}

#[test]
fn compile_time_builtins_require_intrinsics() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "-Wcomponent-model",
            "-C",
            "compile-time-builtin=tests/all/cli_tests/host-api-a.wat",
            "-C",
            "compile-time-builtin=tests/all/cli_tests/host-api-b.wat",
            "tests/all/cli_tests/compile-time-builtin-main.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("must configure the unsafe-intrinsics import"),
        "bad stderr: {stderr}"
    );
    Ok(())
}

#[test]
fn compile_time_builtin_bad_syntax() -> Result<()> {
    // Empty value: there is no file stem to derive a name from.
    let output = get_wasmtime_command()?
        .args(&[
            "-C",
            "compile-time-builtin=",
            "tests/all/cli_tests/simple.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cannot derive a compile-time builtin name"),
        "bad stderr: {stderr}"
    );

    // Empty name in the explicit `<name>=<path>` form.
    let output = get_wasmtime_command()?
        .args(&[
            "-C",
            "compile-time-builtin==host-api-a.wat",
            "tests/all/cli_tests/simple.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("name cannot be empty"),
        "bad stderr: {stderr}"
    );

    Ok(())
}

#[test]
fn compile_time_builtin_missing_file() -> Result<()> {
    let output = get_wasmtime_command()?
        .args(&[
            "-Wcomponent-model",
            "-C",
            "unsafe-intrinsics",
            "-C",
            "compile-time-builtin=host-api-a=tests/all/cli_tests/does-not-exist.wat",
            "tests/all/cli_tests/compile-time-builtin-main.wat",
        ])
        .output()?;
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("tests/all/cli_tests/does-not-exist.wat"),
        "bad stderr: {stderr}"
    );
    Ok(())
}

#[test]
fn compile_time_builtins_compile_subcommand() -> Result<()> {
    let td = TempDir::new()?;
    let cwasm = td.path().join("compile-time-builtin-main.cwasm");
    run_wasmtime(&[
        "compile",
        "-C",
        "unsafe-intrinsics",
        "-C",
        "compile-time-builtin=tests/all/cli_tests/host-api-a.wat",
        "-C",
        "compile-time-builtin=tests/all/cli_tests/host-api-b.wat",
        "-o",
        cwasm.to_str().unwrap(),
        "tests/all/cli_tests/compile-time-builtin-main.wat",
    ])?;

    run_wasmtime(&[
        "-Wcomponent-model",
        "--allow-precompiled",
        cwasm.to_str().unwrap(),
    ])?;
    Ok(())
}

#[test]
fn hostcall_fuel() -> Result<()> {
    for func in ["f1()", "f2()", "f3()", "f4()", "f5()", "f6()", "f7()"] {
        run_wasmtime(&[
            "--invoke",
            func,
            "tests/all/cli_tests/hostcall_fuel.wat",
            func,
        ])?;
        assert!(
            run_wasmtime(&[
                "-Shostcall-fuel=1000",
                "--invoke",
                func,
                "tests/all/cli_tests/hostcall_fuel.wat",
                func,
            ])
            .is_err()
        );
    }
    Ok(())
}

#[test]
#[cfg_attr(target_pointer_width = "32", ignore)] // this test takes 4GiB virtual memory
fn wasi_snapshot0_poll_oneoff_hostcall_fuel() -> Result<()> {
    let stdout = run_wasmtime(&[
        "run",
        "-Shostcall-fuel=1000,preview0=y",
        "--invoke=run",
        "tests/all/cli_tests/poll-oneoff.wat",
    ])?;
    assert_eq!(stdout, "48\n"); // `errno::nomem`
    Ok(())
}

// The CLI derives the async stack size from `-Wmax-wasm-stack` when the latter
// is set on its own, and that derivation used to overflow for very large
// values. A stack that large may legitimately fail to be allocated, but the
// CLI must not panic while computing the async stack size.
/// An enormous `-W max-wasm-stack` must not overflow the CLI's derivation of the
/// async stack size.
///
/// This asserts the absence of the *overflow*, not the absence of *any* failure:
/// on a 32-bit target `usize::MAX` asks for a ~4 GiB stack, so an allocation
/// failure is a legitimate outcome there (the merge queue's i686 job failed once
/// because this test demanded that the request succeed).
#[test]
fn max_wasm_stack_large_value_does_not_overflow() -> Result<()> {
    let output = run_wasmtime(&[
        "run",
        "-W",
        &format!("max-wasm-stack={}", usize::MAX),
        "tests/all/cli_tests/simple.wat",
    ]);
    let output = format!("{output:?}");
    assert!(
        !output.contains("attempt to add with overflow"),
        "the async stack size derivation overflowed: {output}"
    );
    Ok(())
}

#[test]
fn p3_partial_write_then_stdout() -> Result<()> {
    let output = run_wasmtime(&[
        "run",
        "-Wcomponent-model-async",
        "-Sp3",
        "tests/all/cli_tests/p3-partial-write-then-stdout.wat",
    ])?;
    assert_eq!(output, "456789\n");
    Ok(())
}