diff --git a/Cargo.lock b/Cargo.lock index d9aa04d192f6..2e400a9bc4b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -446,6 +446,17 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "colored" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd" +dependencies = [ + "atty", + "lazy_static", + "winapi", +] + [[package]] name = "component-fuzz-util" version = "0.0.0" @@ -505,6 +516,17 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d6f2aa4d0537bcc1c74df8755072bd31c1ef1a3a1b85a68e8404a8c353b7b8b" +[[package]] +name = "core-wasm-ast" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d6cb3f87920b558fca63472f9c3e07c0ff97e7445dc13e32b04ed8d39b15a0" +dependencies = [ + "log", + "num_cpus", + "threadpool", +] + [[package]] name = "cpp_demangle" version = "0.3.5" @@ -1418,6 +1440,15 @@ dependencies = [ "libc", ] +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + [[package]] name = "hermit-abi" version = "0.3.0" @@ -1875,11 +1906,11 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.13.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" dependencies = [ - "hermit-abi 0.1.19", + "hermit-abi 0.2.6", "libc", ] @@ -2885,6 +2916,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -3268,6 +3308,16 @@ version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" +[[package]] +name = "wasm-coredump-builder" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "154a5b6ab0d19ef348cfebfda15871987f97d4282dd279da4146c846099ab7f5" +dependencies = [ + "core-wasm-ast", + "wasm-printer", +] + [[package]] name = "wasm-encoder" version = "0.23.0" @@ -3291,6 +3341,19 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "wasm-printer" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a3f1d871c18b5cc855c56a99ac1328787931d024c62da01a16dc612f1c04ce6" +dependencies = [ + "byteorder", + "colored", + "core-wasm-ast", + "leb128", + "log", +] + [[package]] name = "wasm-smith" version = "0.12.2" @@ -3506,6 +3569,7 @@ dependencies = [ "tempfile", "test-programs", "tokio", + "wasm-coredump-builder", "wasmparser", "wasmtime", "wasmtime-cache", diff --git a/Cargo.toml b/Cargo.toml index f052cbe1d628..df4b60bd8a2a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ wat = { workspace = true } serde = "1.0.94" serde_json = "1.0.26" wasmparser = { workspace = true } +wasm-coredump-builder = { version = "0.1.9" } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["mm", "param"] } diff --git a/docs/examples-coredump.md b/docs/examples-coredump.md new file mode 100644 index 000000000000..6a78dd5176f2 --- /dev/null +++ b/docs/examples-coredump.md @@ -0,0 +1,62 @@ +# Using Wasm coredump + +The following steps describe how to debug using Wasm coredump in Wasmtime: + +1. Compile your WebAssembly with debug info enabled; for example: + + ```sh + $ rustc foo.rs --target=wasm32-wasi -C debuginfo=2 + ``` + +
+ foo.rs + + fn c(v: usize) { + a(v - 3); + } + + fn b(v: usize) { + c(v - 3); + } + + fn a(v: usize) { + b(v - 3); + } + + pub fn main() { + a(10); + } +
+ +2. Run with Wasmtime and Wasm coredump enabled: + + ```sh + $ wasmtime --coredump-on-trap=/tmp/coredump foo.wasm + + thread 'main' panicked at 'attempt to subtract with overflow', foo.rs:10:7 + note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + Error: failed to run main module `foo.wasm` + + Caused by: + 0: Core dumped at /tmp/coredump + 1: failed to invoke command default + 2: error while executing at wasm backtrace: + ... + ``` + +3. Use [wasmgdb] to debug: + ```sh + $ wasmgdb foo.wasm /tmp/coredump + + wasmgdb> bt + ... + #13 000175 as panic () at library/core/src/panicking.rs + #12 000010 as a (v=???) at /path/to/foo.rs + #11 000009 as c (v=???) at /path/to/foo.rs + #10 000011 as b (v=???) at /path/to/foo.rs + #9 000010 as a (v=???) at /path/to/foo.rs + #8 000012 as main () at /path/to/foo.rs + ... + ``` + +[wasmgdb]: https://crates.io/crates/wasmgdb diff --git a/src/commands/run.rs b/src/commands/run.rs index 4f5751c3befe..1e4de8f6515e 100644 --- a/src/commands/run.rs +++ b/src/commands/run.rs @@ -4,10 +4,12 @@ use anyhow::{anyhow, bail, Context as _, Result}; use clap::Parser; use once_cell::sync::Lazy; use std::ffi::OsStr; +use std::fs::File; +use std::io::Write; use std::path::{Component, Path, PathBuf}; use std::thread; use std::time::Duration; -use wasmtime::{Engine, Func, Linker, Module, Store, Val, ValType}; +use wasmtime::{Engine, Func, Linker, Module, Store, Val, ValType, WasmBacktrace}; use wasmtime_cli_flags::{CommonOptions, WasiModules}; use wasmtime_wasi::maybe_exit_on_error; use wasmtime_wasi::sync::{ambient_authority, Dir, TcpListener, WasiCtxBuilder}; @@ -151,6 +153,10 @@ pub struct RunCommand { )] wasm_timeout: Option, + /// Enable coredump generation after a WebAssembly trap. + #[clap(long = "coredump-on-trap", value_name = "PATH")] + coredump_on_trap: Option, + // NOTE: this must come last for trailing varargs /// The arguments to pass to the module #[clap(value_name = "ARGS")] @@ -170,6 +176,15 @@ impl RunCommand { let preopen_sockets = self.compute_preopen_sockets()?; + // Validate coredump-on-trap argument + if let Some(coredump_path) = self.coredump_on_trap.as_ref() { + if coredump_path.contains("%") { + return Err(anyhow!( + "The coredump-on-trap path does not support patterns yet." + )); + } + } + // Make wasi available by default. let preopen_dirs = self.compute_preopen_dirs()?; let argv = self.compute_argv(); @@ -376,13 +391,54 @@ impl RunCommand { // Invoke the function and then afterwards print all the results that came // out, if there are any. let mut results = vec![Val::null(); ty.results().len()]; - func.call(store, &values, &mut results).with_context(|| { + let invoke_res = func.call(store, &values, &mut results).with_context(|| { if let Some(name) = name { format!("failed to invoke `{}`", name) } else { format!("failed to invoke command default") } - })?; + }); + match invoke_res { + Ok(_) => {} + Err(err) => { + if let Some(coredump_path) = self.coredump_on_trap.as_ref() { + let bt = err + .downcast_ref::() + .ok_or_else(|| anyhow!("failed to downcast to WasmBacktrace"))?; + + let mut coredump_builder = wasm_coredump_builder::CoredumpBuilder::new() + .executable_name(&self.module.to_str().unwrap_or_else(|| "unknown")); + + { + let mut thread_builder = + wasm_coredump_builder::ThreadBuilder::new().thread_name("main"); + + for frame in bt.frames() { + let coredump_frame = wasm_coredump_builder::FrameBuilder::new() + .funcidx(frame.func_index()) + .build(); + thread_builder.add_frame(coredump_frame); + } + + coredump_builder.add_thread(thread_builder.build()); + } + + let coredump = coredump_builder + .serialize() + .map_err(|err| anyhow!("failed to serialize coredump: {}", err))?; + + let mut f = File::create(coredump_path) + .context(format!("failed to create file at `{}`", coredump_path))?; + f.write_all(&coredump) + .context("failed to write coredump file")?; + + return Err(err.context(format!("Core dumped at {}", coredump_path))); + } else { + return Err(err); + } + } + }; + if !results.is_empty() { eprintln!( "warning: using `--invoke` with a function that returns values \