A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Limit the number of frames in backtrace collection (#12542)
Adam Bratschi-Kayec8764ed068b6
diff --git a/crates/fuzzing/src/generators/stacks.rs b/crates/fuzzing/src/generators/stacks.rsindex 0e9e87e3f5..78c92234e1 100644--- a/crates/fuzzing/src/generators/stacks.rs+++ b/crates/fuzzing/src/generators/stacks.rs@@ -6,6 +6,7 @@//! walker.use std::mem;+use std::num::NonZeroUsize;use arbitrary::{Arbitrary, Result, Unstructured};use wasm_encoder::{Instruction, ValType};@@ -20,6 +21,9 @@ const MAX_PARAMS: usize = 10;pub struct Stacks {funcs: Vec<Function>,inputs: Vec<u8>,+ /// The maximum number of backtrace frames to collect, or `None` to disable+ /// backtrace collection.+ pub limit: Option<NonZeroUsize>,}#[derive(Debug, Default)]@@ -42,7 +46,12 @@ impl<'a> Arbitrary<'a> for Stacks {let funcs = Self::arbitrary_funcs(u)?;let n = u.len().min(200);let inputs = u.bytes(n)?.to_vec();- Ok(Stacks { funcs, inputs })+ let limit = NonZeroUsize::new(u.int_in_range(0..=256)?);+ Ok(Stacks {+ funcs,+ inputs,+ limit,+ })}}diff --git a/crates/fuzzing/src/oracles/stacks.rs b/crates/fuzzing/src/oracles/stacks.rsindex fd5fa1b644..cfa54876cd 100644--- a/crates/fuzzing/src/oracles/stacks.rs+++ b/crates/fuzzing/src/oracles/stacks.rs@@ -10,7 +10,9 @@ pub fn check_stacks(stacks: Stacks) -> usize {let wasm = stacks.wasm();crate::oracles::log_wasm(&wasm);- let engine = Engine::default();+ let mut config = Config::new();+ config.wasm_backtrace_max_frames(stacks.limit);+ let engine = Engine::new(&config).unwrap();let module = Module::new(&engine, &wasm).expect("should compile okay");let mut linker = Linker::new(&engine);@@ -79,7 +81,15 @@ pub fn check_stacks(stacks: Stacks) -> usize {let host_trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();let trap = trap.downcast_ref::<Trap>().unwrap();max_stack_depth = max_stack_depth.max(host_trace.len());- assert_stack_matches(&mut store, memory, ptr, len, host_trace, *trap);+ assert_stack_matches(+ &mut store,+ memory,+ ptr,+ len,+ host_trace,+ *trap,+ stacks.limit,+ );}}max_stack_depth@@ -93,6 +103,7 @@ fn assert_stack_matches(len: u32,host_trace: &[FrameInfo],trap: Trap,+ limit: Option<std::num::NonZeroUsize>,) {let mut data = vec![0; len as usize];memory@@ -107,17 +118,41 @@ fn assert_stack_matches(wasm_trace.push(entry);}+ let trace_limit = match limit {+ Some(n) => n.get(),+ None => {+ // Backtraces are disabled; the host trace should be empty.+ assert!(host_trace.is_empty());+ return;+ }+ };+// If the test case here trapped due to stack overflow then the host trace// will have one more frame than the wasm trace. The wasm didn't actually// get to the point of pushing onto its own trace stack where the host will// be able to see the exact function that triggered the stack overflow. In// this situation the host trace is asserted to be one larger and then the// top frame (first) of the host trace is discarded.- let host_trace = if trap == Trap::StackOverflow {- assert_eq!(host_trace.len(), wasm_trace.len() + 1);- &host_trace[1..]+ let (host_trace, wasm_trace) = if trap == Trap::StackOverflow {+ if host_trace.len() == trace_limit {+ assert!(+ trace_limit <= wasm_trace.len() + 1,+ "Host trace size {} is larger than expected {}",+ trace_limit,+ wasm_trace.len() + 1+ );+ } else {+ assert_eq!(host_trace.len(), wasm_trace.len() + 1);+ }+ (+ &host_trace[1..],+ &wasm_trace.get(..trace_limit - 1).unwrap_or(&wasm_trace),+ )} else {- host_trace+ (+ host_trace,+ &wasm_trace.get(..trace_limit).unwrap_or(&wasm_trace),+ )};log::debug!("Wasm thinks its stack is: {wasm_trace:?}");@@ -131,7 +166,7 @@ fn assert_stack_matches(assert_eq!(wasm_trace.len(), host_trace.len());for (wasm_entry, host_entry) in wasm_trace.into_iter().zip(host_trace) {- assert_eq!(wasm_entry, host_entry.func_index());+ assert_eq!(wasm_entry, &host_entry.func_index());}}diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rsindex 89902a7af4..2a0c71286a 100644--- a/crates/wasmtime/src/config.rs+++ b/crates/wasmtime/src/config.rs@@ -2,6 +2,7 @@ use crate::prelude::*;use alloc::sync::Arc;use bitflags::Flags;use core::fmt;+use core::num::NonZeroUsize;use core::str::FromStr;#[cfg(any(feature = "cranelift", feature = "winch"))]use std::path::Path;@@ -31,6 +32,8 @@ pub use wasmtime_cache::{Cache, CacheConfig};#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]pub use wasmtime_environ::CacheStore;+pub(crate) const DEFAULT_WASM_BACKTRACE_MAX_FRAMES: NonZeroUsize = NonZeroUsize::new(20).unwrap();+/// Represents the module instance allocation strategy to use.#[derive(Clone)]#[non_exhaustive]@@ -169,8 +172,8 @@ pub struct Config {pub(crate) enabled_features: WasmFeatures,/// Same as `enabled_features`, but for those that are explicitly disabled.pub(crate) disabled_features: WasmFeatures,- pub(crate) wasm_backtrace: bool,pub(crate) wasm_backtrace_details_env_used: bool,+ pub(crate) wasm_backtrace_max_frames: Option<NonZeroUsize>,pub(crate) native_unwind_info: Option<bool>,#[cfg(any(feature = "async", feature = "stack-switching"))]pub(crate) async_stack_size: usize,@@ -274,8 +277,8 @@ impl Config {// 1` forces this), or at least it passed when this change was// committed.max_wasm_stack: 512 * 1024,- wasm_backtrace: true,wasm_backtrace_details_env_used: false,+ wasm_backtrace_max_frames: Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES),native_unwind_info: None,enabled_features: WasmFeatures::empty(),disabled_features: WasmFeatures::empty(),@@ -466,30 +469,27 @@ impl Config {/// Configures whether [`WasmBacktrace`] will be present in the context of/// errors returned from Wasmtime.///- /// A backtrace may be collected whenever an error is returned from a host- /// function call through to WebAssembly or when WebAssembly itself hits a- /// trap condition, such as an out-of-bounds memory access. This flag- /// indicates, in these conditions, whether the backtrace is collected or- /// not.- ///- /// Currently wasm backtraces are implemented through frame pointer walking.- /// This means that collecting a backtrace is expected to be a fast and- /// relatively cheap operation. Additionally backtrace collection is- /// suitable in concurrent environments since one thread capturing a- /// backtrace won't block other threads.- ///- /// Collected backtraces are attached via- /// [`Error::context`](crate::Error::context) to errors returned from host- /// functions. The [`WasmBacktrace`] type can be acquired via- /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the- /// backtrace. When this option is disabled then this context is never- /// applied to errors coming out of wasm.- ///- /// This option is `true` by default.+ /// This method is deprecated in favor of+ /// [`Config::wasm_backtrace_max_frames`]. Calling `wasm_backtrace(false)`+ /// is equivalent to `wasm_backtrace_max_frames(None)`, and+ /// `wasm_backtrace(true)` will leave `wasm_backtrace_max_frames` unchanged+ /// if the value is `Some` and will otherwise restore the default `Some`+ /// value.////// [`WasmBacktrace`]: crate::WasmBacktrace+ #[deprecated = "use `wasm_backtrace_max_frames` instead"]pub fn wasm_backtrace(&mut self, enable: bool) -> &mut Self {- self.wasm_backtrace = enable;+ match (enable, self.wasm_backtrace_max_frames) {+ (false, _) => self.wasm_backtrace_max_frames = None,+ // Wasm backtraces were disabled; enable them with the+ // default maximum number of frames to capture.+ (true, None) => {+ self.wasm_backtrace_max_frames = Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES)+ }+ // Wasm backtraces are already enabled; keep the existing+ // max-frames configuration.+ (true, Some(_)) => {}+ }self}@@ -528,6 +528,36 @@ impl Config {self}+ /// Configures the maximum number of WebAssembly frames to collect in+ /// backtraces.+ ///+ /// A backtrace may be collected whenever an error is returned from a host+ /// function call through to WebAssembly or when WebAssembly itself hits a+ /// trap condition, such as an out-of-bounds memory access. This flag+ /// indicates, in these conditions, whether the backtrace is collected or+ /// not and how many frames should be collected.+ ///+ /// Currently wasm backtraces are implemented through frame pointer walking.+ /// This means that collecting a backtrace is expected to be a fast and+ /// relatively cheap operation. Additionally backtrace collection is+ /// suitable in concurrent environments since one thread capturing a+ /// backtrace won't block other threads.+ ///+ /// Collected backtraces are attached via+ /// [`Error::context`](crate::Error::context) to errors returned from host+ /// functions. The [`WasmBacktrace`] type can be acquired via+ /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the+ /// backtrace. When this option is set to `None` then this context is never+ /// applied to errors coming out of wasm.+ ///+ /// The default value is 20.+ ///+ /// [`WasmBacktrace`]: crate::WasmBacktrace+ pub fn wasm_backtrace_max_frames(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {+ self.wasm_backtrace_max_frames = limit;+ self+ }+/// Configures whether to generate native unwind information/// (e.g. `.eh_frame` on Linux).///@@ -535,8 +565,8 @@ impl Config {/// capturing mechanisms, such as the system's unwinder or the `backtrace`/// crate, determine how to unwind through Wasm frames. It does not affect/// whether Wasmtime can capture Wasm backtraces or not. The presence of- /// [`WasmBacktrace`] is controlled by the [`Config::wasm_backtrace`]- /// option.+ /// [`WasmBacktrace`] is controlled by the+ /// [`Config::wasm_backtrace_max_frames`] option.////// Native unwind information is included:/// - When targeting Windows, since the Windows ABI requires it.diff --git a/crates/wasmtime/src/runtime/trap.rs b/crates/wasmtime/src/runtime/trap.rsindex 24027acd8d..5ca7a58ae5 100644--- a/crates/wasmtime/src/runtime/trap.rs+++ b/crates/wasmtime/src/runtime/trap.rs@@ -6,6 +6,7 @@ use crate::prelude::*;use crate::store::StoreOpaque;use crate::{AsContext, Module};use core::fmt;+use core::num::NonZeroUsize;use wasmtime_environ::{FilePos, demangle_function_name, demangle_function_name_or_index};/// Representation of a WebAssembly trap and what caused it to occur.@@ -121,7 +122,12 @@ pub(crate) fn from_runtime_box(};if let Some(bt) = backtrace {- let bt = WasmBacktrace::from_captured(store, bt, pc);+ let bt = WasmBacktrace::from_captured(+ store,+ bt,+ pc,+ store.engine().config().wasm_backtrace_max_frames,+ );if !bt.wasm_trace.is_empty() {error = error.context(bt);}@@ -130,7 +136,12 @@ pub(crate) fn from_runtime_box(let _ = &coredumpstack;#[cfg(feature = "coredump")]if let Some(coredump) = coredumpstack {- let bt = WasmBacktrace::from_captured(store, coredump.bt, pc);+ let bt = WasmBacktrace::from_captured(+ store,+ coredump.bt,+ pc,+ store.engine().config().wasm_backtrace_max_frames,+ );let cd = WasmCoreDump::new(store, bt);error = error.context(cd);}@@ -150,7 +161,7 @@ pub(crate) fn from_runtime_box(/// the error is logged.////// Capturing of wasm backtraces can be configured through the-/// [`Config::wasm_backtrace`](crate::Config::wasm_backtrace) method.+/// [`Config::wasm_backtrace_max_frames`](crate::Config::wasm_backtrace_max_frames) method.////// For more information about errors in wasmtime see the documentation of the/// [`Trap`] type.@@ -206,16 +217,16 @@ impl WasmBacktrace {/// current thread. If no WebAssembly is on the stack then the returned/// backtrace will have no frames in it.///- /// Note that this function will respect the [`Config::wasm_backtrace`]- /// configuration option and will return an empty backtrace if that is- /// disabled. To always capture a backtrace use the- /// [`WasmBacktrace::force_capture`] method.+ /// Note that this function will respect the+ /// [`Config::wasm_backtrace_max_frames`] configuration option and will+ /// return an empty backtrace if that is set to `None`. To always capture a+ /// backtrace use the [`WasmBacktrace::force_capture`] method.////// Also note that this function will only capture frames from the/// specified `store` on the stack, ignoring frames from other stores if/// present.///- /// [`Config::wasm_backtrace`]: crate::Config::wasm_backtrace+ /// [`Config::wasm_backtrace_max_frames`]: crate::Config::wasm_backtrace_max_frames////// # Example///@@ -247,8 +258,13 @@ impl WasmBacktrace {/// ```pub fn capture(store: impl AsContext) -> WasmBacktrace {let store = store.as_context();- if store.engine().config().wasm_backtrace {- Self::force_capture(store)+ if let Some(max_frames) = store.engine().config().wasm_backtrace_max_frames {+ Self::from_captured(+ store.0,+ crate::runtime::vm::Backtrace::new(store.0),+ None,+ Some(max_frames),+ )} else {WasmBacktrace {wasm_trace: Vec::new(),@@ -262,24 +278,46 @@ impl WasmBacktrace {/// for the provided store.////// Same as [`WasmBacktrace::capture`] except that it disregards the- /// [`Config::wasm_backtrace`](crate::Config::wasm_backtrace) setting and- /// always captures a backtrace.+ /// [`Config::wasm_backtrace_max_frames`](crate::Config::wasm_backtrace_max_frames)+ /// setting and always captures a backtrace.pub fn force_capture(store: impl AsContext) -> WasmBacktrace {let store = store.as_context();- Self::from_captured(store.0, crate::runtime::vm::Backtrace::new(store.0), None)+ let max_frames = store+ .engine()+ .config()+ .wasm_backtrace_max_frames+ .unwrap_or(crate::config::DEFAULT_WASM_BACKTRACE_MAX_FRAMES);+ Self::from_captured(+ store.0,+ crate::runtime::vm::Backtrace::new(store.0),+ None,+ Some(max_frames),+ )}fn from_captured(store: &StoreOpaque,runtime_trace: crate::runtime::vm::Backtrace,trap_pc: Option<usize>,+ max_frames: Option<NonZeroUsize>,) -> Self {- let mut wasm_trace = Vec::<FrameInfo>::with_capacity(runtime_trace.frames().len());+ let Some(max_frames) = max_frames else {+ return WasmBacktrace {+ wasm_trace: Vec::new(),+ hint_wasm_backtrace_details_env: false,+ _runtime_trace: crate::runtime::vm::Backtrace::empty(),+ };+ };+ let mut wasm_trace = Vec::<FrameInfo>::with_capacity(max_frames.get());let mut hint_wasm_backtrace_details_env = false;let wasm_backtrace_details_env_used =store.engine().config().wasm_backtrace_details_env_used;for frame in runtime_trace.frames() {+ if wasm_trace.len() >= max_frames.get() {+ break;+ }+debug_assert!(frame.pc() != 0);// Note that we need to be careful about the pc we pass indiff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rsindex 7aef97e144..c9f2d80f36 100644--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs@@ -579,7 +579,7 @@ mod call_thread_state {unwinder: store.unwinder(),#[cfg(all(has_native_signals))]signal_handler: store.signal_handler(),- capture_backtrace: store.engine().config().wasm_backtrace,+ capture_backtrace: store.engine().config().wasm_backtrace_max_frames.is_some(),#[cfg(feature = "coredump")]capture_coredump: store.engine().config().coredump_on_trap,vm_store_context: Cell::new(store.vm_store_context_ptr()),diff --git a/tests/all/traps.rs b/tests/all/traps.rsindex 3b578b49d9..c9a1ad3447 100644--- a/tests/all/traps.rs+++ b/tests/all/traps.rs@@ -1,6 +1,7 @@#![cfg(not(miri))]use crate::ErrorExt;+use std::num::NonZeroUsize;use std::panic::{self, AssertUnwindSafe};use std::process::Command;use std::sync::{Arc, Mutex};@@ -211,7 +212,7 @@ fn test_trap_through_host() -> Result<()> {#[test]fn test_trap_backtrace_disabled() -> Result<()> {let mut config = Config::default();- config.wasm_backtrace(false);+ config.wasm_backtrace_max_frames(None);let engine = Engine::new(&config).unwrap();let mut store = Store::<()>::new(&engine, ());let wat = r#"@@ -263,21 +264,25 @@ fn test_trap_trace_cb() -> Result<()> {#[test]fn test_trap_stack_overflow() -> Result<()> {- let mut store = Store::<()>::default();+ let max_frames = NonZeroUsize::new(32).unwrap();let wat = r#"(module $rec_mod(func $run (export "run") (call $run)))"#;- let module = Module::new(store.engine(), wat)?;- let instance = Instance::new(&mut store, &module, &[])?;+ let mut config = Config::new();+ config.wasm_backtrace_max_frames(Some(max_frames));+ let engine = Engine::new(&config).unwrap();+ let module = Module::new(&engine, wat).unwrap();+ let mut store = Store::new(&engine, ());+ let instance = Instance::new(&mut store, &module, &[]).unwrap();let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;let e = run_func.call(&mut store, ()).unwrap_err();let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();- assert!(trace.len() >= 32);+ assert_eq!(trace.len(), max_frames.get());for i in 0..trace.len() {assert_eq!(trace[i].module().name().unwrap(), "rec_mod");assert_eq!(trace[i].func_index(), 0);@@ -1152,7 +1157,7 @@ fn standalone_backtrace() -> Result<()> {#[test]fn standalone_backtrace_disabled() -> Result<()> {let mut config = Config::new();- config.wasm_backtrace(false);+ config.wasm_backtrace_max_frames(None);let engine = Engine::new(&config)?;let mut store = Store::new(&engine, ());let module = Module::new(@@ -1180,7 +1185,7 @@ fn standalone_backtrace_disabled() -> Result<()> {#[test]fn host_return_error_no_backtrace() -> Result<()> {let mut config = Config::new();- config.wasm_backtrace(false);+ config.wasm_backtrace_max_frames(None);let engine = Engine::new(&config)?;let mut store = Store::new(&engine, ());let module = Module::new(@@ -1823,3 +1828,48 @@ fn return_call_to_aborting_wasm_function_with_stack_adjustments() -> Result<()>Ok(())}++#[test]+fn test_wasm_backtrace_max_frames() -> Result<()> {+ fn run(max_frames: Option<NonZeroUsize>) -> wasmtime::Error {+ let wat = r#"+ (module+ (func $f1 (export "f1") (call $f2))+ (func $f2 (call $f3))+ (func $f3 (call $f4))+ (func $f4 (call $f5))+ (func $f5 (call $f6))+ (func $f6 (call $f7))+ (func $f7 (call $f8))+ (func $f8 (call $f9))+ (func $f9 (call $f10))+ (func $f10 (unreachable))+ )+ "#;++ let mut config = Config::new();+ config.wasm_backtrace_max_frames(max_frames);+ let engine = Engine::new(&config).unwrap();+ let module = Module::new(&engine, wat).unwrap();+ let mut store = Store::new(&engine, ());+ let instance = Instance::new(&mut store, &module, &[]).unwrap();+ let f1 = instance.get_typed_func::<(), ()>(&mut store, "f1").unwrap();+ f1.call(&mut store, ()).unwrap_err()+ }++ // Capturing more than 10 frames should get them all.+ let err = run(NonZeroUsize::new(20));+ let bt = err.downcast_ref::<WasmBacktrace>().unwrap();+ assert_eq!(bt.frames().len(), 10);++ // Limit to 5 frames gets the top 5.+ let err = run(NonZeroUsize::new(5));+ let bt = err.downcast_ref::<WasmBacktrace>().unwrap();+ assert_eq!(bt.frames().len(), 5);++ // Limit of None means no frames collected+ let err = run(None);+ assert!(err.downcast_ref::<WasmBacktrace>().is_none());++ Ok(())+}