A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Avoid spawning a subprocess for every `disas` test (#13828)
Nick Fitzgerald7dbf76df2ad3
diff --git a/Cargo.toml b/Cargo.tomlindex 1c483a26d7..41d0025ba3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -124,6 +124,7 @@ toml = { workspace = true }similar = { workspace = true }libtest-mimic = { workspace = true }capstone = { workspace = true }+termcolor = { workspace = true }object = { workspace = true, features = ['std'] }wasmtime-test-macros = { path = "crates/test-macros" }pulley-interpreter = { workspace = true, features = ["disas"] }diff --git a/src/commands/objdump.rs b/src/commands/objdump.rsindex c85607b634..363501625e 100644--- a/src/commands/objdump.rs+++ b/src/commands/objdump.rs@@ -5,7 +5,7 @@ use clap::Parser;use object::read::elf::ElfFile64;use object::{Endianness, Object, ObjectSection, ObjectSymbol};use smallvec::SmallVec;-use std::io::{IsTerminal, Read, Write};+use std::io::{IsTerminal, Read};use std::iter::{self, Peekable};use std::path::{Path, PathBuf};use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};@@ -106,28 +106,39 @@ impl ObjdumpCommand {/// Executes the command.pub fn execute(self) -> Result<()> {- // Setup stdout handling color options. Also build some variables used- // below to configure colors of certain items.+ // Setup stdout handling color options.let mut choice = self.color;if choice == ColorChoice::Auto && !std::io::stdout().is_terminal() {choice = ColorChoice::Never;}let mut stdout = StandardStream::stdout(choice);+ let bytes = self.read_cwasm()?;+ self.disassemble(&bytes, &mut stdout)+ }++ /// Disassembles the `*.cwasm` image in `bytes`, rendering a human-readable+ /// listing to `stdout`.+ //+ // XXX: This is only `pub` so it can be shared with the `disas` test runner,+ // so that that doesn't need to spawn a subprocess per `disas` test, which+ // is extremely slow on machines with corporate management software that+ // intercept every process spawn.+ #[doc(hidden)]+ pub fn disassemble(&self, bytes: &[u8], stdout: &mut dyn WriteColor) -> Result<()> {+ // Build some variables used below to configure colors of certain items.let mut color_address = ColorSpec::new();color_address.set_bold(true).set_fg(Some(Color::Yellow));let mut color_bytes = ColorSpec::new();color_bytes.set_fg(Some(Color::Magenta));- let bytes = self.read_cwasm()?;-// Double-check this is a `*.cwasm`- if Engine::detect_precompiled(&bytes).is_none() {+ if Engine::detect_precompiled(bytes).is_none() {bail!("not a `*.cwasm` file from wasmtime: {:?}", self.cwasm);}// Parse the input as an ELF file, extract the `.text` section.- let elf = ElfFile64::<Endianness>::parse(&bytes)?;+ let elf = ElfFile64::<Endianness>::parse(bytes)?;let text = elf.section_by_name(".text").context("missing .text section")?;@@ -287,7 +298,7 @@ impl ObjdumpCommand {let mut post_decorations = Vec::new();decorator.decorate(address, &mut pre_decorations, &mut post_decorations);- let print_whitespace_to_decoration = |stdout: &mut StandardStream| -> Result<()> {+ let print_whitespace_to_decoration = |stdout: &mut dyn WriteColor| -> Result<()> {write!(stdout, "{:width$} ", "")?;if self.bytes {for _ in 0..inline_bytes + 1 {@@ -298,7 +309,7 @@ impl ObjdumpCommand {};let print_decorations =- |stdout: &mut StandardStream, decorations: Vec<String>| -> Result<()> {+ |stdout: &mut dyn WriteColor, decorations: Vec<String>| -> Result<()> {for (i, decoration) in decorations.iter().enumerate() {print_whitespace_to_decoration(stdout)?;let mut color = ColorSpec::new();@@ -328,7 +339,7 @@ impl ObjdumpCommand {Ok(())};- print_decorations(&mut stdout, pre_decorations)?;+ print_decorations(&mut *stdout, pre_decorations)?;// Some instructions may disassemble to multiple lines, such as// `br_table` with Pulley. Handle separate lines per-instruction@@ -395,7 +406,7 @@ impl ObjdumpCommand {}}- print_decorations(&mut stdout, post_decorations)?;+ print_decorations(&mut *stdout, post_decorations)?;}}Ok(())diff --git a/tests/disas.rs b/tests/disas.rsindex eb2b4878fb..27bc9ee2a3 100644--- a/tests/disas.rs+++ b/tests/disas.rs@@ -45,13 +45,13 @@ use libtest_mimic::{Arguments, Trial};use serde_derive::Deserialize;use similar::TextDiff;use std::fmt::Write as _;-use std::io::Write as _;use std::path::{Path, PathBuf};-use std::process::Stdio;use tempfile::TempDir;+use termcolor::Buffer;use wasmtime::{CodeBuilder, CodeHint, Engine, OptLevel, Result, Strategy, bail, error::Context as _,};+use wasmtime_cli::commands::ObjdumpCommand;use wasmtime_cli_flags::CommonOptions;fn main() -> Result<()> {@@ -300,43 +300,28 @@ fn assert_output(test: &Test, output: CompileOutput) -> Result<()> {}}CompileOutput::Elf(bytes) => {- let mut cmd = wasmtime_test_util::command(env!("CARGO_BIN_EXE_wasmtime"));- cmd.arg("objdump")- .arg("--address-width=4")- .arg("--address-jumps")- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::piped());+ // XXX: Avoid spawning a `wasmtime objdump` subprocess for every+ // test, which is very expensive on machines with corporate+ // management software that inspects each spawned process. Instead,+ // create an `ObjdumpCommand` within this process directly.+ let mut args = vec!["objdump", "--address-width=4", "--address-jumps"];match &test.config.objdump {- Some(args) => {- cmd.args(args.to_vec());- }- None => {- cmd.arg("--traps=false");- }+ Some(objdump_args) => args.extend(objdump_args.to_vec()),+ None => args.push("--traps=false"),}if let Some(filter) = &test.config.filter {- cmd.arg("--filter").arg(filter);- }-- let mut child = cmd.spawn().context("failed to run wasmtime")?;- child- .stdin- .take()- .unwrap()- .write_all(&bytes)- .context("failed to write stdin")?;- let output = child- .wait_with_output()- .context("failed to wait for child")?;- if !output.status.success() {- bail!(- "objdump failed: {}\nstderr: {}",- output.status,- String::from_utf8_lossy(&output.stderr),- );+ args.push("--filter");+ args.push(filter);}- actual = String::from_utf8(output.stdout).unwrap();+ let command = ObjdumpCommand::try_parse_from(args)+ .context("failed to parse `wasmtime objdump` flags")?;++ let mut output = Buffer::no_color();+ command+ .disassemble(&bytes, &mut output)+ .context("failed to disassemble compiled module")?;+ actual = String::from_utf8(output.into_inner())+ .expect("`ObjdumpCommand` always writes valid UTF-8");}}let actual = actual.trim();