A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
gdbstub and tests: bind to any free port (when instructed); avoid racy integration test. (#14777)
Chris Fallinfe5a057f9eef
diff --git a/crates/gdbstub-component/src/lib.rs b/crates/gdbstub-component/src/lib.rsindex de717b5188..7491bce335 100644--- a/crates/gdbstub-component/src/lib.rs+++ b/crates/gdbstub-component/src/lib.rs@@ -31,6 +31,9 @@ use wstd::{#[derive(Parser)]struct Options {/// The TCP address to listen on, in `<addr>:<port>` format.+ ///+ /// Port 0 instructs the stub server to choose any free port (which+ /// will be printed to stderr at startup).tcp_address: String,/// Verbose logging.#[clap(short = 'v')]@@ -90,14 +93,15 @@ impl<'a> Debugger<'a> {let listener = TcpListener::bind(&self.options.tcp_address).await.expect("Could not bind to TCP port");+ // Print the actually-bound address rather than the requested+ // one, so that binding to port 0 reports the chosen port.+ let local_addr = listener+ .local_addr()+ .expect("Could not get bound TCP address");+ api::print_debugger_info(&format!("Debugger listening on {local_addr}"));api::print_debugger_info(&format!(- "Debugger listening on {}",- self.options.tcp_address,- ));- api::print_debugger_info(&format!(- "In LLDB, attach with: process connect --plugin wasm connect://{}",- self.options.tcp_address,+ "In LLDB, attach with: process connect --plugin wasm connect://{local_addr}",));// Only accept one connection for the run; once the debuggerdiff --git a/src/common.rs b/src/common.rsindex 09ca97e1c2..0d572da932 100644--- a/src/common.rs+++ b/src/common.rs@@ -101,9 +101,11 @@ pub struct RunCommon {/// Attach the built-in gdbstub debugger component, listening on/// the given TCP address. Accepts a port number (e.g. `1234`) or/// a full `address:port`. A bare port number will bind on- /// localhost only (`127.0.0.1`). A debugger (e.g. LLDB) can then- /// connect via `process connect --plugin=wasm- /// connect://<ADDR>:<PORT>`.+ /// localhost only (`127.0.0.1`). A port number of `0` indicates+ /// that any free port should be chosen; the port is printed on startup.+ ///+ /// A debugger (e.g. LLDB) can then connect via `process connect+ /// --plugin=wasm connect://<ADDR>:<PORT>`.#[cfg(feature = "gdbstub")]#[arg(short = 'g', long = "gdbstub", value_name = "[ADDR:]PORT")]pub gdbstub: Option<String>,diff --git a/tests/all/guest_debug/mod.rs b/tests/all/guest_debug/mod.rsindex c51e049126..b115dd9967 100644--- a/tests/all/guest_debug/mod.rs+++ b/tests/all/guest_debug/mod.rs@@ -1,6 +1,7 @@//! Integration tests for guest-debug support (gdbstub + LLDB).//!-//! These tests launch `wasmtime run` with `-g <port>`, connect LLDB via+//! These tests launch `wasmtime run` with `-g 0` (binding to an+//! OS-assigned port, which is parsed from the startup messages), connect LLDB via//! the wasm remote protocol, execute debug scripts (set breakpoints,//! continue, step, inspect variables), and validate output.//!@@ -11,7 +12,7 @@use filecheck::{CheckerBuilder, NO_VARIABLES};use std::io::{BufRead, BufReader, Write};-use std::net::{SocketAddr, TcpListener, TcpStream};+use std::net::{SocketAddr, TcpStream};use std::process::{Child, Command, Stdio};use std::time::Duration;use test_programs_artifacts::*;@@ -30,15 +31,6 @@ fn wasmtime_binary() -> std::path::PathBuf {me}-/// Find an available TCP port by binding to port 0.-fn free_port() -> u16 {- TcpListener::bind("127.0.0.1:0")- .unwrap()- .local_addr()- .unwrap()- .port()-}-/// Path to the wasm-aware LLDB.fn lldb_path() -> String {std::env::var("LLDB").unwrap_or("/opt/wasi-sdk/bin/lldb".to_string())@@ -50,23 +42,25 @@ const GDBSTUB_READY_MARKER: &str = "Debugger listening on";/// A running wasmtime process with a gdbstub endpoint.struct WasmtimeWithGdbstub {child: Child,+ /// The port the gdbstub is listening on, as reported by wasmtime.+ port: u16,/// Keeps the stderr pipe alive to avoid SIGPIPE on the child./// Also used by serve tests to read the HTTP address.stderr_reader: BufReader<std::process::ChildStderr>,}impl WasmtimeWithGdbstub {- /// Spawn wasmtime and wait for stderr to contain the gdbstub- /// readiness marker.- fn spawn(- subcmd: &str,- gdbstub_port: u16,- extra_args: &[&str],- timeout: Duration,- ) -> Result<Self> {+ /// Spawn wasmtime with the gdbstub listening on an OS-assigned+ /// port, and wait for stderr to contain the gdbstub readiness+ /// marker, from which we parse the port.+ ///+ /// Letting wasmtime bind to port 0 (rather than picking a free port+ /// beforehand and passing it in) avoids a race with other processes+ /// (e.g. concurrently-running tests) grabbing the port in between.+ fn spawn(subcmd: &str, extra_args: &[&str], timeout: Duration) -> Result<Self> {let mut cmd = Command::new(wasmtime_binary());cmd.arg(subcmd)- .arg(format!("-g{gdbstub_port}"))+ .arg("-g0").args(extra_args).stdin(Stdio::null()).stdout(Stdio::null())@@ -86,9 +80,18 @@ impl WasmtimeWithGdbstub {line.clear();reader.read_line(&mut line)?;eprintln!("wasmtime stderr: {}", line.trim_end());- if line.contains(GDBSTUB_READY_MARKER) {+ if let Some(idx) = line.find(GDBSTUB_READY_MARKER) {+ let addr = line[idx + GDBSTUB_READY_MARKER.len()..].trim();+ let port = match addr.parse::<SocketAddr>() {+ Ok(addr) => addr.port(),+ Err(e) => {+ let _ = child.kill();+ bail!("failed to parse gdbstub address `{addr}`: {e}");+ }+ };return Ok(Self {child,+ port,stderr_reader: reader,});}@@ -173,10 +176,8 @@ fn check_output(output: &str, directives: &str) -> Result<()> {#[test]#[ignore]fn guest_debug_cli_fib_breakpoint() -> Result<()> {- let port = free_port();let mut wt = WasmtimeWithGdbstub::spawn("run",- port,&["-Ccache=n", GUEST_DEBUG_FIB],Duration::from_secs(30),)?;@@ -184,7 +185,7 @@ fn guest_debug_cli_fib_breakpoint() -> Result<()> {// Set breakpoint at the initial stop, *before* continuing.// This tests that modules are visible immediately.let output = lldb_with_gdbstub_script(- port,+ wt.port,r#"b fibc@@ -210,16 +211,14 @@ check: n =#[test]#[ignore]fn guest_debug_cli_fib_step() -> Result<()> {- let port = free_port();let mut wt = WasmtimeWithGdbstub::spawn("run",- port,&["-Ccache=n", GUEST_DEBUG_FIB],Duration::from_secs(30),)?;let output = lldb_with_gdbstub_script(- port,+ wt.port,r#"b fibc@@ -265,16 +264,14 @@ fn guest_debug_cli_shared_memory() -> Result<()> {.to_str().ok_or_else(|| format_err!("temporary module path is not UTF-8"))?;- let port = free_port();let mut wt = WasmtimeWithGdbstub::spawn("run",- port,&["-Ccache=n", "-W", "threads=y,shared-memory=y", module_path],Duration::from_secs(30),)?;let output = lldb_with_gdbstub_script(- port,+ wt.port,r#"continuememory read --size 4 --format decimal --count 1 0x0@@ -312,16 +309,11 @@ fn guest_debug_cli_breakpoint_in_start_func() -> Result<()> {.to_str().ok_or_else(|| format_err!("temporary module path is not UTF-8"))?;- let port = free_port();- let mut wt = WasmtimeWithGdbstub::spawn(- "run",- port,- &["-Ccache=n", module_path],- Duration::from_secs(30),- )?;+ let mut wt =+ WasmtimeWithGdbstub::spawn("run", &["-Ccache=n", module_path], Duration::from_secs(30))?;let output = lldb_with_gdbstub_script(- port,+ wt.port,r#"b runc@@ -382,11 +374,8 @@ fn parse_http_addr(line: &str) -> Result<SocketAddr> {#[test]#[ignore]fn guest_debug_serve_requests() -> Result<()> {- let gdb_port = free_port();-let mut wt = WasmtimeWithGdbstub::spawn("serve",- gdb_port,&["-Ccache=n","--addr=127.0.0.1:0",@@ -395,6 +384,7 @@ fn guest_debug_serve_requests() -> Result<()> {],Duration::from_secs(30),)?;+ let gdb_port = wt.port;// Connect LLDB in background: just continue to start the HTTP server.let lldb_handle = std::thread::spawn(move || lldb_with_gdbstub_script(gdb_port, "c\n"));@@ -439,11 +429,8 @@ check: resuming#[test]#[ignore]fn guest_debug_serve_breakpoint() -> Result<()> {- let gdb_port = free_port();-let mut wt = WasmtimeWithGdbstub::spawn("serve",- gdb_port,&["-Ccache=n","--addr=127.0.0.1:0",@@ -452,6 +439,7 @@ fn guest_debug_serve_breakpoint() -> Result<()> {],Duration::from_secs(30),)?;+ let gdb_port = wt.port;// LLDB script: set a breakpoint on the incoming-handler Guest::handle,// continue to start the server, then for each request: print backtrace@@ -587,10 +575,9 @@ const SPIN_WAT: &str = r#"/// Continues `SPIN_WAT` under `wasmtime <subcmd> -g` with `args`, then/// interrupts it, expecting a stop rather than an exit.fn interrupt_spin(subcmd: &str, args: &[&str]) -> Result<()> {- let port = free_port();- let mut wt = WasmtimeWithGdbstub::spawn(subcmd, port, args, Duration::from_secs(30))?;+ let mut wt = WasmtimeWithGdbstub::spawn(subcmd, args, Duration::from_secs(30))?;let result = (|| -> Result<()> {- let mut rsp = RspClient::connect(port)?;+ let mut rsp = RspClient::connect(wt.port)?;rsp.request("?")?;rsp.send("c")?;std::thread::sleep(Duration::from_millis(200));