Skip to content

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

Debugging: add integration test with LLDB and some minor tweaks. (#12856)

Chris Fallin856fb2721cb3
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 2d7ee5e43b..2703041bff 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -1033,6 +1033,30 @@ jobs:
LLDB: lldb-18
WASI_SDK_PATH: /tmp/wasi-sdk
+ # Test guest-debug (gdbstub) functionality with LLDB.
+ # Requires wasi-sdk >= 32 for LLDB with the Wasm remote-debug plugin.
+ test_guest_debug:
+ needs: determine
+ if: needs.determine.outputs.run-dwarf
+ name: Test guest debugging
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ submodules: true
+ - uses: ./.github/actions/install-rust
+ - run: |
+ rustup target add wasm32-wasip2 wasm32-wasip1 wasm32-unknown-unknown
+ cd /tmp
+ curl --retry 5 --retry-all-errors -OL https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-32/wasi-sdk-32.0-x86_64-linux.tar.gz
+ tar -xzf wasi-sdk-32.0-x86_64-linux.tar.gz
+ mv wasi-sdk-32.0-x86_64-linux wasi-sdk
+ - run: |
+ cargo test --features gdbstub --test all -- --ignored --test-threads 1 guest_debug::
+ env:
+ LLDB: /tmp/wasi-sdk/bin/lldb
+ WASI_SDK_PATH: /tmp/wasi-sdk
+
build-preview1-component-adapter:
name: Build wasi-preview1-component-adapter
needs: determine
diff --git a/crates/debugger/src/host.rs b/crates/debugger/src/host.rs
index 8e0bb3921a..df6741d198 100644
--- a/crates/debugger/src/host.rs
+++ b/crates/debugger/src/host.rs
@@ -29,10 +29,21 @@ pub fn add_debuggee<T: Send + 'static>(
})?)
}
+impl bindings::DebugMainImports for ResourceTable {
+ async fn print_debugger_info(&mut self, message: String) -> wasmtime::Result<()> {
+ eprintln!("Debugger: {message}");
+ Ok(())
+ }
+}
+
/// Add the debugger world's host functions to a [`wasmtime::component::Linker`].
pub fn add_to_linker<T: Send + 'static>(
linker: &mut wasmtime::component::Linker<T>,
f: fn(&mut T) -> &mut ResourceTable,
) -> wasmtime::Result<()> {
- wit::add_to_linker::<_, wasmtime::component::HasSelf<ResourceTable>>(linker, f)
+ wit::add_to_linker::<_, wasmtime::component::HasSelf<ResourceTable>>(linker, f)?;
+ bindings::DebugMain::add_to_linker_imports::<_, wasmtime::component::HasSelf<ResourceTable>>(
+ linker, f,
+ )?;
+ Ok(())
}
diff --git a/crates/debugger/wit/world.wit b/crates/debugger/wit/world.wit
index 09c88d95fb..e3c602ce26 100644
--- a/crates/debugger/wit/world.wit
+++ b/crates/debugger/wit/world.wit
@@ -3,6 +3,11 @@ package bytecodealliance:[email protected];
world debug-main {
import wasi:io/[email protected];
import debuggee;
+
+ /// Print an informational message from the debugger (e.g. "listening
+ /// on port 1234") to the user. The host decides how to display this.
+ import print-debugger-info: func(message: string);
+
export debugger;
}
diff --git a/crates/gdbstub-component/src/lib.rs b/crates/gdbstub-component/src/lib.rs
index 78bd9ac09c..bcc929b2bb 100644
--- a/crates/gdbstub-component/src/lib.rs
+++ b/crates/gdbstub-component/src/lib.rs
@@ -81,22 +81,24 @@ struct Debugger<'a> {
impl<'a> Debugger<'a> {
async fn run(&mut self) -> Result<()> {
- // Single-step once so modules are loaded and PC is at the
- // first instruction.
- self.start_single_step(api::ResumptionValue::Normal);
- self.running.as_mut().unwrap().wait().await;
- let _ = self.running.take().unwrap().result(self.debuggee)?;
+ // Load module info from the debuggee. Modules are
+ // pre-registered on the debuggee store before the Debuggee is
+ // created, so they are visible here without needing to
+ // execute any Wasm.
self.update_on_stop();
let listener = TcpListener::bind(&self.options.tcp_address)
.await
.expect("Could not bind to TCP port");
- log::info!("Debugger waiting on {}", self.options.tcp_address);
- log::info!(
- "In LLDB, attach with `process connect --plugin wasm connect://{}",
- self.options.tcp_address
- );
+ 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,
+ ));
// Only accept one connection for the run; once the debugger
// disconnects, we'll just continue.
diff --git a/crates/test-programs/artifacts/build.rs b/crates/test-programs/artifacts/build.rs
index 86681f7873..294b123230 100644
--- a/crates/test-programs/artifacts/build.rs
+++ b/crates/test-programs/artifacts/build.rs
@@ -94,6 +94,7 @@ impl Artifacts {
s if s.starts_with("nn_") => "nn",
s if s.starts_with("piped_") => "piped",
s if s.starts_with("debugger_") => "debugger",
+ s if s.starts_with("guest_debug_") => "guest_debug",
s if s.starts_with("dwarf_") => "dwarf",
s if s.starts_with("config_") => "config",
s if s.starts_with("keyvalue_") => "keyvalue",
diff --git a/crates/test-programs/src/bin/guest_debug_fib.c b/crates/test-programs/src/bin/guest_debug_fib.c
new file mode 100644
index 0000000000..986842eaa6
--- /dev/null
+++ b/crates/test-programs/src/bin/guest_debug_fib.c
@@ -0,0 +1,19 @@
+//! flags = []
+
+#include <stdio.h>
+
+int fib(int n) {
+ int t, a = 0, b = 1;
+ for (int i = 0; i < n; i++) {
+ t = a;
+ a = b;
+ b += t;
+ }
+ return b;
+}
+
+int main() {
+ int result = fib(5);
+ printf("fib(5) = %d\n", result);
+ return 0;
+}
diff --git a/crates/wasmtime/src/runtime/component/component.rs b/crates/wasmtime/src/runtime/component/component.rs
index 0ec5065311..fb0d5997c7 100644
--- a/crates/wasmtime/src/runtime/component/component.rs
+++ b/crates/wasmtime/src/runtime/component/component.rs
@@ -482,7 +482,7 @@ impl Component {
&self.inner.static_modules[idx]
}
- #[cfg(feature = "profiling")]
+ #[cfg(any(feature = "profiling", feature = "debug"))]
pub(crate) fn static_modules(&self) -> impl Iterator<Item = &Module> {
self.inner.static_modules.values()
}
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index 556934abc2..935cf44c11 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -1306,6 +1306,35 @@ impl<T> Store<T> {
pub fn clear_debug_handler(&mut self) {
self.inner.debug_handler = None;
}
+
+ /// Register a [`Module`] with this store's module registry for
+ /// debugging, without instantiating it.
+ ///
+ /// This makes the module visible to debuggers (via
+ /// `debug_all_modules`) before the module is actually
+ /// instantiated. This is useful for guest-debug workflows where
+ /// the debugger needs to see modules to set breakpoints before
+ /// the first Wasm instruction executes.
+ #[cfg(feature = "debug")]
+ pub fn debug_register_module(&mut self, module: &crate::Module) -> crate::Result<()> {
+ let (modules, engine, breakpoints) = self.inner.modules_and_engine_and_breakpoints_mut();
+ modules.register_module(module, engine, breakpoints)?;
+ Ok(())
+ }
+
+ /// Register all inner modules of a [`Component`](crate::component::Component)
+ /// with this store's module registry for debugging, without instantiating
+ /// the component.
+ #[cfg(all(feature = "debug", feature = "component-model"))]
+ pub fn debug_register_component(
+ &mut self,
+ component: &crate::component::Component,
+ ) -> crate::Result<()> {
+ for module in component.static_modules() {
+ self.debug_register_module(module)?;
+ }
+ Ok(())
+ }
}
impl<'a, T> StoreContext<'a, T> {
diff --git a/src/commands/run.rs b/src/commands/run.rs
index 9c13316e5d..fdc4111a32 100644
--- a/src/commands/run.rs
+++ b/src/commands/run.rs
@@ -272,6 +272,20 @@ impl RunCommand {
};
debug_run.add_debugger_api(&mut debug_linker)?;
+ // Pre-register the main module on the debuggee store
+ // so that `debug_all_modules()` returns it before any
+ // Wasm executes. This lets the debugger see modules
+ // and set breakpoints at the initial stop.
+ match &main {
+ RunTarget::Core(m) => {
+ store.debug_register_module(m)?;
+ }
+ #[cfg(feature = "component-model")]
+ RunTarget::Component(c) => {
+ store.debug_register_component(c)?;
+ }
+ }
+
debug_run
.invoke_debugger(
&mut debug_store,
diff --git a/tests/all/guest_debug/mod.rs b/tests/all/guest_debug/mod.rs
new file mode 100644
index 0000000000..a51e42073b
--- /dev/null
+++ b/tests/all/guest_debug/mod.rs
@@ -0,0 +1,221 @@
+//! Integration tests for guest-debug support (gdbstub + LLDB).
+//!
+//! These tests launch `wasmtime run` with `-g <port>`, connect LLDB via
+//! the wasm remote protocol, execute debug scripts (set breakpoints,
+//! continue, step, inspect variables), and validate output.
+//!
+//! Requirements:
+//! - LLDB with Wasm plugin support (`LLDB` env var or `/opt/wasi-sdk/bin/lldb` by default)
+//! - `WASI_SDK_PATH` env var set (for C test programs)
+//! - Built with `--features gdbstub`
+
+use filecheck::{CheckerBuilder, NO_VARIABLES};
+use std::io::{BufRead, BufReader};
+use std::net::TcpListener;
+use std::process::{Child, Command, Stdio};
+use std::time::Duration;
+use test_programs_artifacts::*;
+use wasmtime::{Result, bail, format_err};
+
+/// Find the wasmtime binary built alongside the test binary.
+fn wasmtime_binary() -> std::path::PathBuf {
+ let mut me = std::env::current_exe().expect("current_exe specified");
+ me.pop(); // chop off file name
+ me.pop(); // chop off `deps`
+ if cfg!(target_os = "windows") {
+ me.push("wasmtime.exe");
+ } else {
+ me.push("wasmtime");
+ }
+ 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())
+}
+
+/// The readiness marker printed by the gdbstub to stderr.
+const GDBSTUB_READY_MARKER: &str = "Debugger listening on";
+
+/// A running wasmtime process with a gdbstub endpoint.
+struct WasmtimeWithGdbstub {
+ child: Child,
+ /// Keeps the stderr pipe alive to avoid SIGPIPE on the child.
+ #[allow(dead_code)]
+ 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> {
+ let mut cmd = Command::new(wasmtime_binary());
+ cmd.arg(subcmd)
+ .arg(format!("-g{gdbstub_port}"))
+ .args(extra_args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped());
+ eprintln!("spawning: {cmd:?}");
+ let mut child = cmd.spawn()?;
+
+ let stderr = child.stderr.take().unwrap();
+ let mut reader = BufReader::new(stderr);
+ let deadline = std::time::Instant::now() + timeout;
+ let mut line = String::new();
+ loop {
+ if std::time::Instant::now() > deadline {
+ let _ = child.kill();
+ bail!("timed out waiting for gdbstub readiness");
+ }
+ line.clear();
+ reader.read_line(&mut line)?;
+ eprintln!("wasmtime stderr: {}", line.trim_end());
+ if line.contains(GDBSTUB_READY_MARKER) {
+ return Ok(Self {
+ child,
+ stderr_reader: reader,
+ });
+ }
+ if line.is_empty() {
+ let _ = child.kill();
+ let status = child.wait()?;
+ bail!("wasmtime exited ({status}) without readiness marker");
+ }
+ }
+ }
+}
+
+/// Run an LLDB debug script against a gdbstub endpoint.
+///
+/// Connects LLDB to `127.0.0.1:<port>` using the Wasm plugin,
+/// executes the given script commands, and returns LLDB's stdout.
+fn lldb_with_gdbstub_script(port: u16, script: &str) -> Result<String> {
+ let _ = env_logger::try_init();
+
+ let mut cmd = Command::new(lldb_path());
+ cmd.arg("--batch");
+ cmd.arg("-o").arg(format!(
+ "process connect --plugin wasm connect://127.0.0.1:{port}"
+ ));
+ for line in script.lines() {
+ let line = line.trim();
+ if !line.is_empty() {
+ cmd.arg("-o").arg(line);
+ }
+ }
+
+ eprintln!("Running LLDB: {cmd:?}");
+ let output = cmd.output()?;
+
+ let stdout = String::from_utf8(output.stdout)?;
+ let stderr = String::from_utf8(output.stderr)?;
+ eprintln!("--- LLDB stdout ---\n{stdout}");
+ eprintln!("--- LLDB stderr ---\n{stderr}");
+
+ Ok(stdout)
+}
+
+/// Validate output against FileCheck-style directives.
+fn check_output(output: &str, directives: &str) -> Result<()> {
+ let mut builder = CheckerBuilder::new();
+ builder
+ .text(directives)
+ .map_err(|e| format_err!("unable to build checker: {e:?}"))?;
+ let checker = builder.finish();
+ let check = checker
+ .explain(output, NO_VARIABLES)
+ .map_err(|e| format_err!("{e:?}"))?;
+ assert!(check.0, "didn't pass check {}", check.1);
+ Ok(())
+}
+
+/// Test that breakpoints can be set at the initial stop (before any
+/// continue), then hit when the program runs.
+#[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),
+ )?;
+
+ // Set breakpoint at the initial stop, *before* continuing.
+ // This tests that modules are visible immediately.
+ let output = lldb_with_gdbstub_script(
+ port,
+ r#"
+b fib
+c
+fr v
+c
+"#,
+ )?;
+ wt.child.kill().ok();
+ wt.child.wait()?;
+
+ check_output(
+ &output,
+ r#"
+check: stop reason
+check: fib
+check: n =
+"#,
+ )?;
+ Ok(())
+}
+
+/// Test single-stepping within fib.
+#[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,
+ r#"
+b fib
+c
+n
+n
+n
+fr v
+c
+"#,
+ )?;
+ wt.child.kill().ok();
+ wt.child.wait()?;
+
+ check_output(
+ &output,
+ r#"
+check: stop reason
+check: fib
+"#,
+ )?;
+ Ok(())
+}
diff --git a/tests/all/main.rs b/tests/all/main.rs
index 4d48bc1cf3..ec61178b34 100644
--- a/tests/all/main.rs
+++ b/tests/all/main.rs
@@ -24,6 +24,8 @@ mod func;
mod funcref;
mod gc;
mod globals;
+#[cfg(feature = "gdbstub")]
+mod guest_debug;
mod host_funcs;
mod i31ref;
mod iloop;