Skip to content

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

Guest debugging: add support for watchpoints. (#14775)

Chris Fallin33b89be10f10
diff --git a/crates/cranelift/src/alias_region.rs b/crates/cranelift/src/alias_region.rs
index ffccdd1e37..3eefe3ab56 100644
--- a/crates/cranelift/src/alias_region.rs
+++ b/crates/cranelift/src/alias_region.rs
@@ -28,8 +28,9 @@ use std::collections::HashMap;
use std::hash::{Hash as _, Hasher};
use wasmtime_environ::{
BuiltinFunctionIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, GetPtrSize,
- ModuleInternedTypeIndex, ModuleTypesBuilder, NUM_COMPONENT_CONTEXT_SLOTS, PtrSize as _,
- RuntimeDataIndex, StaticModuleIndex, VMOffsets, VmctxArrayIndex as _, WasmCompositeInnerType,
+ MemoryIndex, ModuleInternedTypeIndex, ModuleTypesBuilder, NUM_COMPONENT_CONTEXT_SLOTS,
+ PtrSize as _, RuntimeDataIndex, StaticModuleIndex, VMOffsets, VmctxArrayIndex as _,
+ WasmCompositeInnerType,
component::{
ComponentBuiltinFunctionIndex, LoweredIndex, ResourceIndex, RuntimeCallbackIndex,
RuntimeComponentInstanceIndex, RuntimeMemoryIndex, RuntimePostReturnIndex,
@@ -194,6 +195,9 @@ enum AliasRegionKey {
/// An access of an exception object's tag-defined word.
GcExnTagDefined,
+
+ /// An access of the shadow bytes of a linear memory, for watchpoints.
+ ShadowMemory,
}
impl AliasRegionKey {
@@ -1714,6 +1718,12 @@ where
pub fn data_segment_region(&mut self, func: &mut ir::Function) -> ir::AliasRegion {
self.region(func, AliasRegionKey::DataSegment)
}
+
+ /// Get the alias region for the shadow bytes of linear memories, which
+ /// watchpoint checks read before stores.
+ pub fn shadow_memory_region(&mut self, func: &mut ir::Function) -> ir::AliasRegion {
+ self.region(func, AliasRegionKey::ShadowMemory)
+ }
}
/// Unsafe intrinsic-related methods.
diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs
index eeb40ccec4..4403277182 100644
--- a/crates/cranelift/src/func_environ.rs
+++ b/crates/cranelift/src/func_environ.rs
@@ -1685,15 +1685,170 @@ impl FuncEnvironment<'_> {
fn make_heap(&mut self, func: &mut ir::Function, index: MemoryIndex) -> Heap {
let memory = self.module.memories[index];
let (base, bound) = self.make_heap_base_bound(func, index);
+ // Shared memories have no shadow and cannot be watched.
+ let shadow = (self.tunables.memory_watchpoints && !memory.shared)
+ .then(|| self.make_shadow_heap(func, index));
self.heaps.push(HeapData {
base,
bound,
kind: MemoryKind::LinearMemory,
memory,
imported: self.module.is_imported_memory(index),
+ shadow,
})
}
+ /// Makes the heap of the watchpoint shadow of `index`, which is a memory of
+ /// the same type and size, found through its `VMMemoryDefinition` pointer
+ /// in the `vmctx`.
+ fn make_shadow_heap(&mut self, func: &mut ir::Function, index: MemoryIndex) -> Heap {
+ let memory = self.module.memories[index];
+ let memory_tunables = MemoryTunables::new(self.tunables, MemoryKind::LinearMemory);
+ let base_readonly = !memory.memory_may_move(&memory_tunables);
+ let definition = self
+ .alias_regions
+ .vmctx()
+ .shadow_memories(index)
+ .to_deferred_load(func);
+ let base = self
+ .alias_regions
+ .vm_memory_definition()
+ .base()
+ .can_move()
+ .readonly_if(base_readonly)
+ .to_deferred_load(func);
+ let len = self
+ .alias_regions
+ .vm_memory_definition()
+ .current_length()
+ .to_deferred_load(func);
+ self.heaps.push(HeapData {
+ base: VmctxLoadChain::new(smallvec![definition, base]),
+ bound: VmctxLoadChain::new(smallvec![definition, len]),
+ kind: MemoryKind::LinearMemory,
+ memory,
+ imported: self.module.is_imported_memory(index),
+ shadow: None,
+ })
+ }
+
+ /// Before a store of `value`, `size` bytes at the Wasm address `index` plus
+ /// `offset` of `memory`, calls the `memory_watch_store` builtin if any of
+ /// the bytes are watched. `shadow_addr` is the native address of the
+ /// bytes' shadow.
+ pub fn watch_store(
+ &mut self,
+ builder: &mut FunctionBuilder<'_>,
+ memory: MemoryIndex,
+ shadow_addr: ir::Value,
+ index: ir::Value,
+ offset: u64,
+ size: u8,
+ value: ir::Value,
+ ) {
+ let mut shadow_flags = ir::MemFlagsData::new();
+ shadow_flags.set_alias_region(Some(self.alias_regions.shadow_memory_region(builder.func)));
+ let watched = match size {
+ 1 => builder.ins().load(I8, shadow_flags, shadow_addr, 0),
+ 2 => builder.ins().load(I16, shadow_flags, shadow_addr, 0),
+ 4 => builder.ins().load(I32, shadow_flags, shadow_addr, 0),
+ 8 => builder.ins().load(I64, shadow_flags, shadow_addr, 0),
+ 16 => {
+ let low = builder.ins().load(I64, shadow_flags, shadow_addr, 0);
+ let high = builder.ins().load(I64, shadow_flags, shadow_addr, 8);
+ builder.ins().bor(low, high)
+ }
+ _ => unreachable!("unexpected store size {size}"),
+ };
+
+ let hit = builder.create_block();
+ let done = builder.create_block();
+ builder.ins().brif(watched, hit, &[], done, &[]);
+ builder.switch_to_block(hit);
+ builder.seal_block(hit);
+ builder.set_cold_block(hit);
+ let vmctx = self.vmctx_val(&mut builder.cursor());
+ let (lo, hi) = Self::watch_value_bits(builder, value);
+ let memory = builder.ins().iconst(I32, i64::from(memory.as_u32()));
+ // The store is in bounds, so this doesn't overflow.
+ let index = Self::to_u64(builder, index);
+ let addr = builder.ins().iadd_imm_s(index, offset.cast_signed());
+ let len = builder.ins().iconst(I32, i64::from(size));
+ let watch = self.builtin_functions.memory_watch_store(builder.func);
+ builder
+ .ins()
+ .call(watch, &[vmctx, memory, addr, len, lo, hi]);
+ builder.ins().jump(done, &[]);
+ builder.switch_to_block(done);
+ builder.seal_block(done);
+ }
+
+ /// The bits of a stored value, zero-extended to 128 bits, in halves.
+ fn watch_value_bits(
+ builder: &mut FunctionBuilder<'_>,
+ value: ir::Value,
+ ) -> (ir::Value, ir::Value) {
+ let ty = builder.func.dfg.value_type(value);
+ let mut flags = ir::MemFlagsData::new();
+ flags.set_endianness(ir::Endianness::Little);
+ if ty.is_vector() {
+ // Split vectors into 64-bit lanes rather than bitcasting them to
+ // `i128`, which not every backend supports. With little-endian
+ // lane order, lane 0 holds the low bits.
+ let lanes = builder.ins().bitcast(I64X2, flags, value);
+ let lo = builder.ins().extractlane(lanes, 0);
+ let hi = builder.ins().extractlane(lanes, 1);
+ return (lo, hi);
+ }
+ let bits = match ty {
+ F32 => builder.ins().bitcast(I32, flags, value),
+ F64 => builder.ins().bitcast(I64, flags, value),
+ _ => value,
+ };
+ match builder.func.dfg.value_type(bits) {
+ I64 => (bits, builder.ins().iconst(I64, 0)),
+ _ => (
+ builder.ins().uextend(I64, bits),
+ builder.ins().iconst(I64, 0),
+ ),
+ }
+ }
+
+ /// Before a bulk write of `len` bytes at the Wasm address `dst` of
+ /// `memory`, calls the `memory_watch_range` builtin, which checks whether
+ /// any of the bytes are watched.
+ fn watch_range(
+ &mut self,
+ builder: &mut FunctionBuilder<'_>,
+ memory: MemoryIndex,
+ dst: ir::Value,
+ len: ir::Value,
+ ) {
+ if !self.tunables.memory_watchpoints {
+ return;
+ }
+ let heap = self.get_or_create_heap(builder.func, memory);
+ if self.heaps[heap].shadow.is_none() {
+ return;
+ }
+ let vmctx = self.vmctx_val(&mut builder.cursor());
+ let memory = builder.ins().iconst(I32, i64::from(memory.as_u32()));
+ let dst = Self::to_u64(builder, dst);
+ let len = Self::to_u64(builder, len);
+ let watch = self.builtin_functions.memory_watch_range(builder.func);
+ builder.ins().call(watch, &[vmctx, memory, dst, len]);
+ }
+
+ fn to_u64(builder: &mut FunctionBuilder<'_>, value: ir::Value) -> ir::Value {
+ let ty = builder.func.dfg.value_type(value);
+ assert!(ty.is_int() && ty.bits() <= 64, "unexpected type {ty}");
+ if ty == I64 {
+ value
+ } else {
+ builder.ins().uextend(I64, value)
+ }
+ }
+
fn make_heap_base_bound(
&mut self,
func: &mut ir::Function,
@@ -3886,6 +4041,7 @@ impl FuncEnvironment<'_> {
) -> WasmResult<()> {
let cost = self.tunables.operator_cost.variable().memory_copy_per_byte;
let fuel = self.pre_translate_bulk_op(builder, len, cost);
+ self.watch_range(builder, dst_index, dst, len);
self.translate_entity_copy(builder, dst_index, src_index, dst, src, len)?;
self.post_translate_bulk_op(builder, fuel)
}
@@ -4220,6 +4376,7 @@ impl FuncEnvironment<'_> {
) -> WasmResult<()> {
let cost = self.tunables.operator_cost.variable().memory_fill_per_byte;
let fuel = self.pre_translate_bulk_op(builder, len, cost);
+ self.watch_range(builder, memory_index, dst, len);
self.translate_entity_fill(builder, memory_index, dst, val, len)?;
self.post_translate_bulk_op(builder, fuel)
}
@@ -4236,6 +4393,7 @@ impl FuncEnvironment<'_> {
let seg_index = DataIndex::from_u32(seg_index);
let cost = self.tunables.operator_cost.variable().memory_init_per_byte;
let fuel = self.pre_translate_bulk_op(builder, len, cost);
+ self.watch_range(builder, memory_index, dst, len);
self.translate_entity_copy(
builder,
memory_index,
@@ -6411,6 +6569,7 @@ impl FuncEnvironment<'_> {
let start = builder.ins().iconst(I32, 0);
let cost = self.tunables.operator_cost.variable().memory_init_per_byte;
let fuel = self.pre_translate_bulk_op(builder, len, cost);
+ self.watch_range(builder, memory, offset, len);
self.translate_entity_copy(builder, memory, data, offset, start, len)?;
self.post_translate_bulk_op(builder, fuel)?;
diff --git a/crates/cranelift/src/func_environ/gc.rs b/crates/cranelift/src/func_environ/gc.rs
index 3187bf27b3..0f8c5c79fe 100644
--- a/crates/cranelift/src/func_environ/gc.rs
+++ b/crates/cranelift/src/func_environ/gc.rs
@@ -1755,6 +1755,7 @@ impl FuncEnvironment<'_> {
memory,
kind: MemoryKind::GcHeap,
imported: false,
+ shadow: None,
});
self.gc_heap = Some(heap);
heap
diff --git a/crates/cranelift/src/translate/code_translator.rs b/crates/cranelift/src/translate/code_translator.rs
index 4347125a56..65aab77fb1 100644
--- a/crates/cranelift/src/translate/code_translator.rs
+++ b/crates/cranelift/src/translate/code_translator.rs
@@ -73,12 +73,12 @@
use crate::bounds_checks::{BoundsCheck, bounds_check_and_compute_addr};
use crate::func_environ::{Extension, FuncEnvironment};
-use crate::translate::TargetEnvironment;
use crate::translate::environ::StructFieldsVec;
use crate::translate::stack::{ControlStackFrame, ElseData};
use crate::translate::translation_utils::{
block_with_params, blocktype_params_results, f32_translation, f64_translation, set_block_params,
};
+use crate::translate::{HeapData, TargetEnvironment};
use crate::trap::TranslateTrap;
use crate::{MAX_BR_TABLE_TARGETS, Reachability};
use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
@@ -3633,7 +3633,41 @@ fn prepare_addr(
MemArgTarget::Array(_) => return Err(wasm_unsupported!("multibyte-array-access proposal")),
};
let heap = environ.get_or_create_heap(builder.func, memory_index);
+ let heap = environ.heaps()[heap].clone();
+ let addr = match heap_addr(memarg, access_size, &heap, index, builder, environ) {
+ Reachability::Unreachable => return Ok(Reachability::Unreachable),
+ Reachability::Reachable(a) => a,
+ };
+
+ // Note that we don't set `is_aligned` here, even if the load instruction's
+ // alignment immediate may say it's aligned, because WebAssembly's
+ // immediate field is just a hint, while Cranelift's aligned flag needs a
+ // guarantee. WebAssembly memory accesses are always little-endian.
+ let mut flags = MemFlagsData::new();
+ flags.set_endianness(ir::Endianness::Little);
+
+ // The access occurs to a per-memory disjoint category of abstract
+ // state. This may allow alias analysis to merge redundant loads,
+ // etc. when heap accesses occur interleaved with other (table,
+ // vmctx, stack) accesses.
+ let region = environ.memory_alias_region(builder.func, memory_index);
+ flags.set_alias_region(Some(region));
+ Ok(Reachability::Reachable((flags, index, addr)))
+}
+
+/// Bounds checks an access of `access_size` bytes at the Wasm address `index`
+/// plus `memarg.offset` in `heap`, and computes its native address.
+///
+/// Returns `Unreachable` when the access will unconditionally trap.
+fn heap_addr(
+ memarg: &MemArg,
+ access_size: u8,
+ heap: &HeapData,
+ index: Value,
+ builder: &mut FunctionBuilder,
+ environ: &mut FuncEnvironment<'_>,
+) -> Reachability<Value> {
// How exactly the bounds check is performed here and what it's performed
// on is a bit tricky. Generally we want to rely on access violations (e.g.
// segfaults) to generate traps since that means we don't have to bounds
@@ -3704,14 +3738,13 @@ fn prepare_addr(
// offsets in `memarg` are <=2gb, which means we get the fast path of one
// `heap_addr` instruction plus a hardcoded i32-offset in memory-related
// instructions.
- let heap = environ.heaps()[heap].clone();
- let addr = match u32::try_from(memarg.offset) {
+ match u32::try_from(memarg.offset) {
// If our offset fits within a u32, then we can place the it into the
// offset immediate of the `heap_addr` instruction.
Ok(offset) => bounds_check_and_compute_addr(
builder,
environ,
- &heap,
+ heap,
index,
BoundsCheck::StaticOffset {
offset,
@@ -3759,7 +3792,7 @@ fn prepare_addr(
bounds_check_and_compute_addr(
builder,
environ,
- &heap,
+ heap,
adjusted_index,
BoundsCheck::StaticOffset {
offset: 0,
@@ -3768,27 +3801,7 @@ fn prepare_addr(
ir::TrapCode::HEAP_OUT_OF_BOUNDS,
)
}
- };
- let addr = match addr {
- Reachability::Unreachable => return Ok(Reachability::Unreachable),
- Reachability::Reachable(a) => a,
- };
-
- // Note that we don't set `is_aligned` here, even if the load instruction's
- // alignment immediate may says it's aligned, because WebAssembly's
- // immediate field is just a hint, while Cranelift's aligned flag needs a
- // guarantee. WebAssembly memory accesses are always little-endian.
- let mut flags = MemFlagsData::new();
- flags.set_endianness(ir::Endianness::Little);
-
- // The access occurs to a per-memory disjoint category of abstract
- // state. This may allow alias analysis to merge redundant loads,
- // etc. when heap accesses occur interleaved with other (table,
- // vmctx, stack) accesses.
- let region = environ.memory_alias_region(builder.func, memory_index);
- flags.set_alias_region(Some(region));
-
- Ok(Reachability::Reachable((flags, index, addr)))
+ }
}
fn align_atomic_addr(
@@ -3882,6 +3895,7 @@ fn translate_store(
);
environ.before_store(builder, mem_op_size, wasm_index, memarg.offset);
+ watch_store(memarg, mem_op_size, wasm_index, val, builder, environ);
let flags = builder.func.dfg.mem_flags.insert(flags).unwrap();
builder
@@ -3890,6 +3904,44 @@ fn translate_store(
Ok(())
}
+/// Before a store of `value`, `size` bytes at the Wasm address `index` plus
+/// `memarg.offset`, checks the memory's shadow for watchpoints, if it has one.
+///
+/// The shadow is as large as the memory, so the shadow's bounds check passes
+/// exactly when the store's does.
+fn watch_store(
+ memarg: &MemArg,
+ size: u8,
+ index: Value,
+ value: Value,
+ builder: &mut FunctionBuilder,
+ environ: &mut FuncEnvironment<'_>,
+) {
+ let memory = match memarg.target {
+ MemArgTarget::Memory(index) => MemoryIndex::from_u32(index),
+ // Callers have already rejected array accesses in `prepare_addr`.
+ MemArgTarget::Array(_) => unreachable!(),
+ };
+ let heap = environ.get_or_create_heap(builder.func, memory);
+ let Some(shadow) = environ.heaps()[heap].shadow else {
+ return;
+ };
+ let shadow = environ.heaps()[shadow].clone();
+ if let Reachability::Reachable(shadow_addr) =
+ heap_addr(memarg, size, &shadow, index, builder, environ)
+ {
+ environ.watch_store(
+ builder,
+ memory,
+ shadow_addr,
+ index,
+ memarg.offset,
+ size,
+ value,
+ );
+ }
+}
+
fn mem_op_size(opcode: ir::Opcode, ty: Type) -> u8 {
match opcode {
ir::Opcode::Istore8 | ir::Opcode::Sload8 | ir::Opcode::Uload8 => 1,
@@ -3939,7 +3991,7 @@ fn translate_atomic_rmw(
arg2 = builder.ins().ireduce(access_ty, arg2);
}
- let (flags, _, addr) = unwrap_or_return_unreachable_state!(
+ let (flags, index, addr) = unwrap_or_return_unreachable_state!(
environ,
prepare_atomic_addr(
memarg,
@@ -3949,6 +4001,8 @@ fn translate_atomic_rmw(
)?
);
+ let size = u8::try_from(access_ty.bytes()).unwrap();
+ watch_store(memarg, size, index, arg2, builder, environ);
let mut res = builder.ins().atomic_rmw(access_ty, flags, op, addr, arg2);
if access_ty != widened_ty {
res = builder.ins().uextend(widened_ty, res);
@@ -3994,7 +4048,7 @@ fn translate_atomic_cas(
replacement = builder.ins().ireduce(access_ty, replacement);
}
- let (flags, _, addr) = unwrap_or_return_unreachable_state!(
+ let (flags, index, addr) = unwrap_or_return_unreachable_state!(
environ,
prepare_atomic_addr(
memarg,
@@ -4003,6 +4057,8 @@ fn translate_atomic_cas(
environ,
)?
);
+ let size = u8::try_from(access_ty.bytes()).unwrap();
+ watch_store(memarg, size, index, replacement, builder, environ);
let mut res = builder.ins().atomic_cas(flags, addr, expected, replacement);
if access_ty != widened_ty {
res = builder.ins().uextend(widened_ty, res);
@@ -4082,7 +4138,7 @@ fn translate_atomic_store(
data = builder.ins().ireduce(access_ty, data);
}
- let (flags, _, addr) = unwrap_or_return_unreachable_state!(
+ let (flags, index, addr) = unwrap_or_return_unreachable_state!(
environ,
prepare_atomic_addr(
memarg,
@@ -4091,6 +4147,8 @@ fn translate_atomic_store(
environ,
)?
);
+ let size = u8::try_from(access_ty.bytes()).unwrap();
+ watch_store(memarg, size, index, data, builder, environ);
builder.ins().atomic_store(flags, data, addr);
Ok(())
}
diff --git a/crates/cranelift/src/translate/heap.rs b/crates/cranelift/src/translate/heap.rs
index 09146f38c4..219252db96 100644
--- a/crates/cranelift/src/translate/heap.rs
+++ b/crates/cranelift/src/translate/heap.rs
@@ -133,6 +133,10 @@ pub struct HeapData {
/// Whether this heap is an imported linear memory.
pub imported: bool,
+
+ /// The heap of this linear memory's shadow bytes, when stores check them
+ /// for watchpoints (`Tunables::memory_watchpoints`).
+ pub shadow: Option<Heap>,
}
impl HeapData {
diff --git a/crates/debugger/src/host/api.rs b/crates/debugger/src/host/api.rs
index d470fc7439..5422d3050c 100644
--- a/crates/debugger/src/host/api.rs
+++ b/crates/debugger/src/host/api.rs
@@ -278,6 +278,22 @@ fn result_to_event(table: &mut ResourceTable, value: DebugRunResult) -> Result<w
DebugRunResult::HostcallError => wit::Event::Trap,
DebugRunResult::Trap(_t) => wit::Event::Trap,
DebugRunResult::Breakpoint => wit::Event::Breakpoint,
+ DebugRunResult::Watchpoint(hit) => {
+ let memory = table.push(Memory::Unshared(hit.memory))?;
+ // Scalar and vector stores are at most 16 bytes, so the
+ // value's low `len` little-endian bytes are the bytes
+ // being written, in memory order.
+ let value = hit.value.map(|value| {
+ let len = usize::try_from(hit.len).unwrap().min(16);
+ value.to_le_bytes()[..len].to_vec()
+ });
+ wit::Event::Watchpoint(wit::WatchpointHit {
+ memory,
+ address: hit.address,
+ len: hit.len,
+ value,
+ })
+ }
DebugRunResult::EpochYield => wit::Event::Interrupted,
DebugRunResult::Exception(e) => {
let e = table.push(WasmException(e))?;
@@ -635,6 +651,30 @@ impl wit::HostMemory for ResourceTable {
Ok(())
}
+ async fn add_watchpoint(
+ &mut self,
+ self_: Resource<Memory>,
+ d: Resource<Debuggee>,
+ addr: u64,
+ len: u64,
+ ) -> Result<()> {
+ let memory = self.get(&self_)?.clone();
+ let d = debugger(self, &d)?;
+ d.memory_watch(memory, addr, len, true).await
+ }
+
+ async fn remove_watchpoint(
+ &mut self,
+ self_: Resource<Memory>,
+ d: Resource<Debuggee>,
+ addr: u64,
+ len: u64,
+ ) -> Result<()> {
+ let memory = self.get(&self_)?.clone();
+ let d = debugger(self, &d)?;
+ d.memory_watch(memory, addr, len, false).await
+ }
+
async fn clone(&mut self, self_: Resource<Memory>) -> Result<Resource<Memory>> {
let memory = self.get(&self_)?.clone();
Ok(self.push(memory)?)
diff --git a/crates/debugger/src/host/opaque.rs b/crates/debugger/src/host/opaque.rs
index 7214403459..46912eb148 100644
--- a/crates/debugger/src/host/opaque.rs
+++ b/crates/debugger/src/host/opaque.rs
@@ -126,6 +126,14 @@ pub(crate) trait OpaqueDebugger {
data: u64,
) -> Result<Option<()>>;
+ async fn memory_watch(
+ &mut self,
+ memory: Memory,
+ addr: u64,
+ len: u64,
+ watch: bool,
+ ) -> Result<()>;
+
async fn global_get(&mut self, global: Global) -> Result<WasmValue>;
async fn global_set(&mut self, global: Global, val: WasmValue) -> Result<()>;
@@ -498,6 +506,33 @@ impl<T: Send + 'static> OpaqueDebugger for crate::Debuggee<T> {
.await
}
+ async fn memory_watch(
+ &mut self,
+ memory: Memory,
+ addr: u64,
+ len: u64,
+ watch: bool,
+ ) -> Result<()> {
+ let memory = match memory {
+ Memory::Unshared(memory) => memory,
+ // Shared memories have no shadow and cannot be watched.
+ #[cfg(feature = "threads")]
+ Memory::Shared(_) => return Err(wit::Error::UnsupportedType.into()),
+ };
+ self.with_store(move |mut store| -> Result<()> {
+ let size = u64::try_from(memory.data_size(&store)).unwrap();
+ let end = addr
+ .checked_add(len)
+ .filter(|&end| end <= size)
+ .ok_or(wit::Error::OutOfBounds)?;
+ memory
+ .debug_watch(&mut store, addr..end, watch)
+ .map_err(|_| wit::Error::OutOfBounds)?;
+ Ok(())
+ })
+ .await?
+ }
+
async fn global_get(&mut self, global: Global) -> Result<WasmValue> {
self.with_store(move |mut store| {
let val = global.get(&mut store);
diff --git a/crates/debugger/src/lib.rs b/crates/debugger/src/lib.rs
index cac37a0f22..8de98bd246 100644
--- a/crates/debugger/src/lib.rs
+++ b/crates/debugger/src/lib.rs
@@ -24,7 +24,7 @@ use tokio::{
};
use wasmtime::{
AsContextMut, DebugEvent, DebugHandler, Engine, ExnRef, OwnedRooted, Result, Store,
- StoreContextMut, Trap,
+ StoreContextMut, Trap, WatchpointHit,
};
mod host;
@@ -181,6 +181,7 @@ impl<T: Send + 'static> DebugHandler for Handler<T> {
DebugEvent::Exception(exn) => DebugRunResult::Exception(exn),
DebugEvent::Trap(trap) => DebugRunResult::Trap(trap),
DebugEvent::Breakpoint => DebugRunResult::Breakpoint,
+ DebugEvent::Watchpoint(hit) => DebugRunResult::Watchpoint(hit),
DebugEvent::EpochYield => {
// Only pause on epoch yields that were requested via
// interrupt(). Other epoch ticks simply yield to the
@@ -517,6 +518,9 @@ pub enum DebugRunResult {
Trap(Trap),
/// A breakpoint was reached.
Breakpoint,
+ /// Wasm is about to write watched memory; the write happens when
+ /// execution continues.
+ Watchpoint(WatchpointHit),
}
#[cfg(test)]
@@ -716,6 +720,99 @@ mod test {
Ok(())
}
+ #[tokio::test]
+ #[cfg_attr(miri, ignore)]
+ async fn watchpoints() -> wasmtime::Result<()> {
+ let _ = env_logger::try_init();
+
+ let mut config = Config::new();
+ config.guest_debug(true);
+ let engine = Engine::new(&config)?;
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (memory (export "memory") 1)
+ (func (export "main")
+ (i32.store8 (i32.const 7) (i32.const 1))
+ (i32.store offset=6 (i32.const 0) (i32.const 0x11223344))
+ (i32.store8 (i32.const 12) (i32.const 2))
+ (memory.fill (i32.const 0) (i32.const 0xaa) (i32.const 16))))
+ "#,
+ )?;
+
+ let mut store = Store::new(&engine, ());
+ let instance = Instance::new_async(&mut store, &module, &[]).await?;
+ let memory = instance.get_memory(&mut store, "memory").unwrap();
+ let main = instance.get_typed_func::<(), ()>(&mut store, "main")?;
+
+ // Watch bytes [8, 12): the first store is just below the
+ // range, the second overlaps it partially, the third is just
+ // above it, and the fill covers all of it.
+ memory.debug_watch(&mut store, 8..12, true)?;
+
+ let mut debuggee = Debuggee::new(store, move |store| {
+ Box::pin(async move {
+ main.call_async(&mut *store, ()).await?;
+ Ok(())
+ })
+ });
+
+ let event = debuggee.run().await?;
+ let DebugRunResult::Watchpoint(hit) = event else {
+ panic!("expected a watchpoint, got {event:?}");
+ };
+ assert_eq!(
+ hit,
+ WatchpointHit {
+ memory,
+ address: 6,
+ len: 4,
+ value: Some(0x11223344),
+ }
+ );
+ // The event is raised before the write happens.
+ debuggee
+ .with_store(move |store| {
+ assert_eq!(&memory.data(&store)[6..10], &[0, 1, 0, 0]);
+ })
+ .await?;
+
+ let event = debuggee.run().await?;
+ let DebugRunResult::Watchpoint(hit) = event else {
+ panic!("expected a watchpoint, got {event:?}");
+ };
+ assert_eq!(
+ hit,
+ WatchpointHit {
+ memory,
+ address: 0,
+ len: 16,
+ value: None,
+ }
+ );
+ debuggee
+ .with_store(move |mut store| {
+ // The previous write has now happened, but not the
+ // fill.
+ assert_eq!(&memory.data(&store)[6..10], &0x11223344_u32.to_le_bytes());
+ assert_eq!(memory.data(&store)[12], 2);
+ // Stop watching; the rest of execution runs freely.
+ memory.debug_watch(&mut store, 0..16, false).unwrap();
+ })
+ .await?;
+
+ let event = debuggee.run().await?;
+ assert!(matches!(event, DebugRunResult::Finished));
+ debuggee
+ .with_store(move |store| {
+ assert_eq!(&memory.data(&store)[..16], &[0xaa; 16]);
+ })
+ .await?;
+
+ Ok(())
+ }
+
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn early_finish() -> Result<()> {
diff --git a/crates/debugger/wit/world.wit b/crates/debugger/wit/world.wit
index 0931e61ab4..30041c57a0 100644
--- a/crates/debugger/wit/world.wit
+++ b/crates/debugger/wit/world.wit
@@ -168,6 +168,25 @@ interface debuggee {
exception(wasm-exception),
/// An injected call completed with return value(s).
injected-call-return(list<wasm-value>),
+ /// Wasm is about to write memory watched with
+ /// `memory.add-watchpoint`, pausing execution *before* the write.
+ /// The write happens when execution resumes.
+ watchpoint(watchpoint-hit),
+ }
+
+ /// A guest write to watched bytes of a linear memory.
+ record watchpoint-hit {
+ /// The memory being written.
+ memory: memory,
+ /// The address of the first byte written. This may be below the
+ /// watched range if the write only partially overlaps it.
+ address: u64,
+ /// The number of bytes written, at least one of which is watched.
+ len: u64,
+ /// For a scalar or vector store, the bytes being stored (`len`
+ /// bytes, in memory order). `none` for bulk memory operations
+ /// such as `memory.fill` or `memory.copy`.
+ value: option<list<u8>>,
}
resource instance {
@@ -250,6 +269,32 @@ interface debuggee {
/// Set a u64 (in little endian order) at an address.
set-u64: func(d: borrow<debuggee>, addr: u64, value: u64) -> result<_, error>;
+ /// Watch guest writes to the `len` bytes starting at `addr`.
+ ///
+ /// Any Wasm store or bulk memory operation that writes at least
+ /// one watched byte pauses execution with a `watchpoint` event
+ /// before the write happens. Only writes can be watched.
+ ///
+ /// Whether a byte is watched is a per-byte property: watching an
+ /// already-watched byte has no further effect, and
+ /// `remove-watchpoint` unwatches every byte in its range,
+ /// regardless of how many (possibly overlapping) ranges watched
+ /// it. Debuggers that allow overlapping watchpoints must track
+ /// them and re-add the still-remaining watchpoints after a removal.
+ ///
+ /// Returns `out-of-bounds` if any byte in the range is beyond the
+ /// memory's current size, and `unsupported-type` for a shared
+ /// memory, which cannot be watched.
+ add-watchpoint: func(d: borrow<debuggee>, addr: u64, len: u64) -> result<_, error>;
+
+ /// Stop watching guest writes to the `len` bytes starting at
+ /// `addr`. See `add-watchpoint` for the per-byte semantics.
+ ///
+ /// Returns `out-of-bounds` if any byte in the range is beyond the
+ /// memory's current size, and `unsupported-type` for a shared
+ /// memory.
+ remove-watchpoint: func(d: borrow<debuggee>, addr: u64, len: u64) -> result<_, error>;
+
/// Clone this handle.
clone: func() -> memory;
diff --git a/crates/environ/src/builtin.rs b/crates/environ/src/builtin.rs
index 8ccfdd77aa..a4f8d2ba84 100644
--- a/crates/environ/src/builtin.rs
+++ b/crates/environ/src/builtin.rs
@@ -197,6 +197,13 @@ macro_rules! foreach_builtin_function {
);
#[cfg(feature = "stack-switching")]
asan_finish_switch_fiber(vmctx: vmctx, fake_stack: pointer, current_csi: pointer);
+
+ // Handles a store of `len` bytes, whose bits are `lo` and `hi`, to
+ // watched bytes of a linear memory, before the store.
+ memory_watch_store(vmctx: vmctx, memory: u32, addr: u64, len: u32, lo: u64, hi: u64) -> bool;
+ // Handles a bulk write (`memory.{fill,copy,init}`) of `len` bytes
+ // to a linear memory, before it, if any of the bytes are watched.
+ memory_watch_range(vmctx: vmctx, memory: u32, addr: u64, len: u64) -> bool;
}
};
}
diff --git a/crates/environ/src/compile/module_environ.rs b/crates/environ/src/compile/module_environ.rs
index a8234c1c56..d84d40c1fa 100644
--- a/crates/environ/src/compile/module_environ.rs
+++ b/crates/environ/src/compile/module_environ.rs
@@ -451,6 +451,7 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
data: &'data [u8],
) -> Result<ModuleTranslation<'data>> {
self.result.wasm = data;
+ self.result.module.has_shadow_memories = self.tunables.memory_watchpoints;
for payload in parser.parse_all(data) {
self.translate_payload(payload?)?;
diff --git a/crates/environ/src/module.rs b/crates/environ/src/module.rs
index f15583615a..7e9e80e422 100644
--- a/crates/environ/src/module.rs
+++ b/crates/environ/src/module.rs
@@ -243,6 +243,11 @@ pub struct Module {
/// Does this module need a GC heap to run?
pub needs_gc_heap: bool,
+ /// Does this module's compiled code check its memories' shadows for
+ /// watchpoints (`Tunables::memory_watchpoints`), and so need a pointer to
+ /// each memory's shadow `VMMemoryDefinition` in its `VMContext`?
+ pub has_shadow_memories: bool,
+
/// Number of functions that "escape" from this module may need to have a
/// `VMFuncRef` constructed for them.
///
@@ -345,6 +350,7 @@ impl Module {
num_imported_globals: Default::default(),
num_imported_tags: Default::default(),
needs_gc_heap: Default::default(),
+ has_shadow_memories: Default::default(),
num_escaped_funcs: Default::default(),
functions: Default::default(),
tables: Default::default(),
@@ -693,6 +699,7 @@ impl TypeTrace for Module {
num_imported_tags: _,
num_escaped_funcs: _,
needs_gc_heap: _,
+ has_shadow_memories: _,
functions,
tables,
memories: _,
@@ -745,6 +752,7 @@ impl TypeTrace for Module {
num_imported_tags: _,
num_escaped_funcs: _,
needs_gc_heap: _,
+ has_shadow_memories: _,
functions,
tables,
memories: _,
diff --git a/crates/environ/src/tunables.rs b/crates/environ/src/tunables.rs
index b21dd6733b..ee5d4893fd 100644
--- a/crates/environ/src/tunables.rs
+++ b/crates/environ/src/tunables.rs
@@ -151,6 +151,10 @@ define_tunables! {
/// enabled.
pub concurrency_support: bool,
+ /// Whether compiled code checks a linear memory's shadow before each
+ /// store, for watchpoints.
+ pub memory_watchpoints: bool,
+
/// Whether recording in RR is enabled or not. This is used primarily
/// to signal checksum computation for compiled artifacts.
pub recording: bool,
@@ -285,6 +289,7 @@ impl Tunables {
inlining_sum_size_threshold: 2000,
debug_guest: false,
concurrency_support: true,
+ memory_watchpoints: false,
recording: false,
asan_stack_switching: false,
gc_zeal_alloc_counter: None,
@@ -395,6 +400,11 @@ impl<'a> MemoryTunables<'a> {
Self { tunables, kind }
}
+ /// Whether compiled code checks this memory's shadow for watchpoints.
+ pub fn watchpoints(&self) -> bool {
+ self.tunables.memory_watchpoints && self.kind == MemoryKind::LinearMemory
+ }
+
/// The virtual memory reservation for this kind of memory.
pub fn reservation(&self) -> u64 {
match self.kind {
diff --git a/crates/environ/src/vmctxtypes.rs b/crates/environ/src/vmctxtypes.rs
index 8da8df63a4..8a13fc8e27 100644
--- a/crates/environ/src/vmctxtypes.rs
+++ b/crates/environ/src/vmctxtypes.rs
@@ -192,6 +192,12 @@ macro_rules! for_each_vmctx_type {
owned_memories[num_owned_memories; OwnedMemoryIndex]: VMMemoryDefinition
}
+ array {
+ #[readonly]
+ #[can_move]
+ shadow_memories[num_shadow_memories; MemoryIndex]: VmPtr<VMMemoryDefinition>
+ }
+
array {
#[aggregate]
imported_functions[num_imported_functions; FuncIndex]: VMFunctionImport
diff --git a/crates/environ/src/vmoffsets.rs b/crates/environ/src/vmoffsets.rs
index d96e49ed3f..053bb17352 100644
--- a/crates/environ/src/vmoffsets.rs
+++ b/crates/environ/src/vmoffsets.rs
@@ -728,6 +728,10 @@ pub struct VMOffsets<P> {
pub num_defined_memories: u32,
/// The number of memories owned by the module instance.
pub num_owned_memories: u32,
+ /// The number of shadow memory pointers: one per memory, imported and
+ /// defined, if the module's code checks memory shadows for watchpoints,
+ /// and otherwise none.
+ pub num_shadow_memories: u32,
/// The number of defined globals in the module.
pub num_defined_globals: u32,
/// The number of defined tags in the module.
@@ -744,6 +748,7 @@ pub struct VMOffsets<P> {
imported_memories: u32,
memories: u32,
owned_memories: u32,
+ shadow_memories: u32,
imported_functions: u32,
imported_tables: u32,
imported_globals: u32,
@@ -904,6 +909,10 @@ pub struct VMOffsetsFields<P> {
pub num_defined_memories: u32,
/// The number of memories owned by the module instance.
pub num_owned_memories: u32,
+ /// The number of shadow memory pointers: one per memory, imported and
+ /// defined, if the module's code checks memory shadows for watchpoints,
+ /// and otherwise none.
+ pub num_shadow_memories: u32,
/// The number of defined globals in the module.
pub num_defined_globals: u32,
/// The number of defined tags in the module.
@@ -938,6 +947,11 @@ impl<P: PtrSize> VMOffsets<P> {
num_defined_tables: cast_to_u32(module.num_defined_tables()),
num_defined_memories: cast_to_u32(module.num_defined_memories()),
num_owned_memories,
+ num_shadow_memories: if module.has_shadow_memories {
+ cast_to_u32(module.memories.len())
+ } else {
+ 0
+ },
num_defined_globals: cast_to_u32(module.globals.len() - module.num_imported_globals),
num_defined_tags: cast_to_u32(module.tags.len() - module.num_imported_tags),
num_escaped_funcs: cast_to_u32(module.num_escaped_funcs),
@@ -973,6 +987,7 @@ impl<P: PtrSize> VMOffsets<P> {
num_defined_memories: _,
num_defined_tags: _,
num_owned_memories: _,
+ num_shadow_memories: _,
num_escaped_funcs: _,
num_runtime_data: _,
has_startup_func: _,
@@ -1015,6 +1030,7 @@ impl<P: PtrSize> VMOffsets<P> {
imported_globals: "imported globals",
imported_tables: "imported tables",
imported_functions: "imported functions",
+ shadow_memories: "shadow memories",
owned_memories: "owned memories",
memories: "defined memories",
imported_memories: "imported memories",
@@ -1043,6 +1059,7 @@ impl<P: PtrSize> From<VMOffsetsFields<P>> for VMOffsets<P> {
num_defined_tables: fields.num_defined_tables,
num_defined_memories: fields.num_defined_memories,
num_owned_memories: fields.num_owned_memories,
+ num_shadow_memories: fields.num_shadow_memories,
num_defined_globals: fields.num_defined_globals,
num_defined_tags: fields.num_defined_tags,
num_escaped_funcs: fields.num_escaped_funcs,
@@ -1051,6 +1068,7 @@ impl<P: PtrSize> From<VMOffsetsFields<P>> for VMOffsets<P> {
imported_memories: 0,
memories: 0,
owned_memories: 0,
+ shadow_memories: 0,
imported_functions: 0,
imported_tables: 0,
imported_globals: 0,
@@ -1181,6 +1199,7 @@ mod tests {
num_defined_tables: 0,
num_defined_memories: 0,
num_owned_memories: 0,
+ num_shadow_memories: 0,
num_defined_globals: 0,
num_defined_tags,
num_escaped_funcs: 1,
diff --git a/crates/gdbstub-component/src/addr.rs b/crates/gdbstub-component/src/addr.rs
index 92d1b0f975..0b05ef5198 100644
--- a/crates/gdbstub-component/src/addr.rs
+++ b/crates/gdbstub-component/src/addr.rs
@@ -84,6 +84,13 @@ impl AddrSpace {
Ok(())
}
+ /// The address of `offset` within memory `m`, registering the
+ /// memory if it has not been seen before.
+ pub fn memory_addr(&mut self, m: &Memory, offset: u32) -> WasmAddr {
+ let id = self.memory_id(m);
+ WasmAddr::new(WasmAddrType::Memory, id, offset).unwrap()
+ }
+
/// Iterate over the base `WasmAddr` of every registered module.
pub fn module_base_addrs(&self) -> impl Iterator<Item = WasmAddr> + '_ {
(0..self.modules.len())
diff --git a/crates/gdbstub-component/src/lib.rs b/crates/gdbstub-component/src/lib.rs
index 7491bce335..64dc7e2f6d 100644
--- a/crates/gdbstub-component/src/lib.rs
+++ b/crates/gdbstub-component/src/lib.rs
@@ -18,6 +18,7 @@ use gdbstub::{
MultiThreadStopReason,
state_machine::{GdbStubStateMachine, GdbStubStateMachineInner, state::Running},
},
+ target::ext::breakpoints::WatchKind,
};
use gdbstub_arch::wasm::addr::WasmAddr;
use log::trace;
@@ -61,6 +62,8 @@ impl api::exports::bytecodealliance::wasmtime::debugger::Guest for Component {
single_stepping: false,
frame_cache: vec![],
addr_space: AddrSpace::new(),
+ watchpoints: vec![],
+ pending_watch: None,
};
wstd::runtime::block_on(async {
if let Err(e) = debugger.run().await {
@@ -80,6 +83,32 @@ struct Debugger<'a> {
single_stepping: bool,
current_pc: WasmAddr,
frame_cache: Vec<api::Frame>,
+ /// Active write watchpoints, as requested by the client, without
+ /// duplicates. They may overlap; see `target.rs` for how these are
+ /// kept in sync with the debuggee's per-byte watches.
+ watchpoints: Vec<Watchpoint>,
+ /// A watchpoint was hit and we are stepping over the write before
+ /// reporting it, holding the address to report.
+ pending_watch: Option<WasmAddr>,
+}
+
+/// One write watchpoint requested by the client.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+struct Watchpoint {
+ /// Start of the watched range; always a memory address.
+ addr: WasmAddr,
+ /// Length of the watched range, in bytes.
+ len: u32,
+}
+
+impl Watchpoint {
+ /// Whether this watchpoint covers any byte in `[start, end)` of
+ /// the memory with the given address-space index.
+ fn overlaps(&self, memory_index: u32, start: u64, end: u64) -> bool {
+ let w_start = u64::from(self.addr.offset());
+ let w_end = w_start + u64::from(self.len);
+ self.addr.module_index() == memory_index && w_start < end && start < w_end
+ }
}
impl<'a> Debugger<'a> {
@@ -223,14 +252,76 @@ impl<'a> Debugger<'a> {
}
}
+ /// The address to report to the client for a watchpoint hit: the
+ /// first byte of the write that a client watchpoint covers, so
+ /// that the client can match it to one of its watchpoints even if
+ /// the write starts below the watched range.
+ fn watch_hit_addr(&mut self, hit: &api::WatchpointHit) -> WasmAddr {
+ let start = hit.address;
+ let end = hit.address.saturating_add(hit.len);
+ let base = self.addr_space.memory_addr(&hit.memory, 0);
+ let memory_index = base.module_index();
+ let first_watched = self
+ .watchpoints
+ .iter()
+ .filter(|w| w.overlaps(memory_index, start, end))
+ .map(|w| start.max(u64::from(w.addr.offset())))
+ .min()
+ .unwrap_or(start);
+ let offset = u32::try_from(first_watched).unwrap_or(u32::MAX);
+ self.addr_space.memory_addr(&hit.memory, offset)
+ }
+
async fn handle_event<'b>(
&mut self,
event: api::Event,
inner: GdbStubStateMachineInner<'b, Running, Self, Conn>,
) -> Result<GdbStubStateMachine<'b, Self, Conn>> {
match event {
+ api::Event::Watchpoint(hit) => {
+ // The debuggee pauses *before* the write, but gdb and
+ // LLDB expect watchpoints on this target to trigger
+ // after the write (they then compare the old and new
+ // values). So first single-step over the write, then
+ // report the watchpoint when that step completes.
+ let addr = self.watch_hit_addr(&hit);
+ trace!(
+ "Event::Watchpoint: address {:#x} len {} -> reporting {:#x}",
+ hit.address,
+ hit.len,
+ addr.as_raw()
+ );
+ let single_stepping = self.single_stepping;
+ self.pending_watch = Some(addr);
+ self.start_single_step(api::ResumptionValue::Normal);
+ // Keep the client's resume mode so that any event
+ // other than the step's completion is handled as it
+ // would have been.
+ self.single_stepping = single_stepping;
+ Ok(GdbStubStateMachine::Running(inner))
+ }
+ api::Event::Breakpoint if self.pending_watch.is_some() => {
+ let addr = self.pending_watch.take().unwrap();
+ trace!("stepped over watched write; reporting watchpoint");
+ self.update_on_stop();
+ let pc_bytes = self.current_pc.as_raw().to_le_bytes();
+ let mut regs = core::iter::once((
+ gdbstub_arch::wasm::reg::id::WasmRegId::Pc,
+ pc_bytes.as_slice(),
+ ));
+ Ok(inner.report_stop_with_regs(
+ self,
+ MultiThreadStopReason::Watch {
+ tid: self.tid,
+ kind: WatchKind::Write,
+ addr: addr.as_raw(),
+ },
+ &mut regs,
+ )?)
+ }
api::Event::Complete => {
trace!("Event::Complete");
+ self.pending_watch = None;
let pc_bytes = self.current_pc.as_raw().to_le_bytes();
let mut regs = core::iter::once((
gdbstub_arch::wasm::reg::id::WasmRegId::Pc,
@@ -265,6 +356,7 @@ impl<'a> Debugger<'a> {
}
api::Event::Trap => {
trace!("Event::Trap");
+ self.pending_watch = None;
self.update_on_stop();
let pc_bytes = self.current_pc.as_raw().to_le_bytes();
let mut regs = core::iter::once((
@@ -285,6 +377,7 @@ impl<'a> Debugger<'a> {
trace!("other event: {event:?}");
if self.interrupt {
self.interrupt = false;
+ self.pending_watch = None;
self.update_on_stop();
let pc_bytes = self.current_pc.as_raw().to_le_bytes();
let mut regs = core::iter::once((
@@ -297,7 +390,12 @@ impl<'a> Debugger<'a> {
&mut regs,
)?)
} else {
- if self.single_stepping {
+ if self.pending_watch.is_some() {
+ // Still stepping over a watched write.
+ let single_stepping = self.single_stepping;
+ self.start_single_step(api::ResumptionValue::Normal);
+ self.single_stepping = single_stepping;
+ } else if self.single_stepping {
self.start_single_step(api::ResumptionValue::Normal);
} else {
self.start_continue(api::ResumptionValue::Normal);
diff --git a/crates/gdbstub-component/src/target.rs b/crates/gdbstub-component/src/target.rs
index c54cf9e58e..c642ccec98 100644
--- a/crates/gdbstub-component/src/target.rs
+++ b/crates/gdbstub-component/src/target.rs
@@ -1,8 +1,8 @@
//! gdbstub `Target` implementation.
-use crate::Debugger;
use crate::addr::AddrSpaceLookup;
use crate::api;
+use crate::{Debugger, Watchpoint};
use gdbstub::arch::lldb::{Encoding, Format, Generic, Register};
use gdbstub::common::{Endianness, Pid, Signal, Tid};
use gdbstub::target::Target;
@@ -17,7 +17,8 @@ use gdbstub::target::ext::base::single_register_access::{
SingleRegisterAccess, SingleRegisterAccessOps,
};
use gdbstub::target::ext::breakpoints::{
- Breakpoints, BreakpointsOps, SwBreakpoint, SwBreakpointOps,
+ Breakpoints, BreakpointsOps, HwWatchpoint, HwWatchpointOps, SwBreakpoint, SwBreakpointOps,
+ WatchKind,
};
use gdbstub::target::ext::host_info::{HostInfo, HostInfoOps, HostInfoResponse};
use gdbstub::target::ext::libraries::{Libraries, LibrariesOps};
@@ -236,6 +237,119 @@ impl<'a> Breakpoints for Debugger<'a> {
fn support_sw_breakpoint(&mut self) -> Option<SwBreakpointOps<'_, Self>> {
Some(self)
}
+
+ #[inline(always)]
+ fn support_hw_watchpoint(&mut self) -> Option<HwWatchpointOps<'_, Self>> {
+ Some(self)
+ }
+}
+
+impl<'a> Debugger<'a> {
+ /// Resolve a client watchpoint request to a `Watchpoint` covering
+ /// bytes that currently exist in one linear memory.
+ fn resolve_watchpoint(&self, addr: u64, len: u64) -> Option<Watchpoint> {
+ let addr = WasmAddr::from_raw(addr)?;
+ let len = u32::try_from(len).ok().filter(|&len| len > 0)?;
+ match self.addr_space.lookup(addr, self.debuggee) {
+ AddrSpaceLookup::Memory { memory, offset } => {
+ let end = u64::from(offset) + u64::from(len);
+ (end <= memory.size_bytes(self.debuggee)).then_some(Watchpoint { addr, len })
+ }
+ _ => None,
+ }
+ }
+
+ /// Set (`watch = true`) or clear the debuggee's watch on all bytes
+ /// of `w`.
+ fn set_watch(&self, w: Watchpoint, watch: bool) -> bool {
+ let AddrSpaceLookup::Memory { memory, offset } =
+ self.addr_space.lookup(w.addr, self.debuggee)
+ else {
+ return false;
+ };
+ let offset = u64::from(offset);
+ let len = u64::from(w.len);
+ let result = if watch {
+ memory.add_watchpoint(self.debuggee, offset, len)
+ } else {
+ memory.remove_watchpoint(self.debuggee, offset, len)
+ };
+ result.is_ok()
+ }
+}
+
+/// Write watchpoints.
+///
+/// The debuggee tracks watches per byte, so overlapping client
+/// watchpoints share bytes: removing one would also unwatch bytes
+/// that another still covers. We therefore keep the set of client
+/// watchpoints, and after clearing a removed watchpoint's bytes we
+/// re-watch every remaining watchpoint that overlaps it.
+///
+/// As in gdbserver, inserting a watchpoint identical (in address and
+/// length) to an existing one is a no-op, and a single removal
+/// removes it: the client reference-counts identical requests.
+impl<'a> HwWatchpoint for Debugger<'a> {
+ fn add_hw_watchpoint(
+ &mut self,
+ addr: u64,
+ len: u64,
+ kind: WatchKind,
+ ) -> TargetResult<bool, Self> {
+ // Wasmtime can only detect writes.
+ if kind != WatchKind::Write {
+ return Ok(false);
+ }
+ let Some(w) = self.resolve_watchpoint(addr, len) else {
+ return Ok(false);
+ };
+ if self.watchpoints.contains(&w) {
+ return Ok(true);
+ }
+ if !self.set_watch(w, true) {
+ return Ok(false);
+ }
+ self.watchpoints.push(w);
+ Ok(true)
+ }
+
+ fn remove_hw_watchpoint(
+ &mut self,
+ addr: u64,
+ len: u64,
+ kind: WatchKind,
+ ) -> TargetResult<bool, Self> {
+ if kind != WatchKind::Write {
+ return Ok(false);
+ }
+ let Some(w) = WasmAddr::from_raw(addr)
+ .zip(u32::try_from(len).ok())
+ .map(|(addr, len)| Watchpoint { addr, len })
+ else {
+ return Ok(false);
+ };
+ let Some(i) = self.watchpoints.iter().position(|x| *x == w) else {
+ return Ok(false);
+ };
+ self.watchpoints.swap_remove(i);
+ if !self.set_watch(w, false) {
+ return Err(TargetError::NonFatal);
+ }
+ let start = u64::from(w.addr.offset());
+ let end = start + u64::from(w.len);
+ let remaining = self
+ .watchpoints
+ .iter()
+ .filter(|x| x.overlaps(w.addr.module_index(), start, end))
+ .copied()
+ .collect::<Vec<_>>();
+ for x in remaining {
+ if !self.set_watch(x, true) {
+ return Err(TargetError::NonFatal);
+ }
+ }
+ Ok(true)
+ }
}
impl<'a> SwBreakpoint for Debugger<'a> {
diff --git a/crates/test-programs/src/bin/debugger_component.rs b/crates/test-programs/src/bin/debugger_component.rs
index ec02336898..7d81314b0b 100644
--- a/crates/test-programs/src/bin/debugger_component.rs
+++ b/crates/test-programs/src/bin/debugger_component.rs
@@ -29,6 +29,9 @@ impl api::exports::bytecodealliance::wasmtime::debugger::Guest for Component {
Some("loop") => {
test_loop(d);
}
+ Some("watch") => {
+ test_watch(d);
+ }
other => panic!("unknown test mode: {other:?}"),
}
}
@@ -125,4 +128,66 @@ fn test_loop(d: &Debuggee) {
eprintln!("OK");
}
+/// Watchpoint test: watch bytes [8, 12) of memory 0 and check that
+/// writes overlapping them (and only those) pause execution before
+/// the write happens.
+///
+/// Tests against `debugger_debuggee_watch.wat`.
+fn test_watch(d: &Debuggee) {
+ // Step once so that the instance exists.
+ let r = Resumption::single_step(d);
+ assert!(matches!(r.result(d).unwrap(), Event::Breakpoint));
+
+ let mem = d
+ .all_instances()
+ .iter()
+ .find_map(|inst| inst.get_memory(d, 0).ok())
+ .expect("debuggee has a memory");
+
+ // Ranges must be within the memory.
+ let size = mem.size_bytes(d);
+ assert!(matches!(
+ mem.add_watchpoint(d, size - 1, 2),
+ Err(Error::OutOfBounds)
+ ));
+ assert!(matches!(
+ mem.add_watchpoint(d, u64::MAX, 2),
+ Err(Error::OutOfBounds)
+ ));
+
+ mem.add_watchpoint(d, 8, 4).unwrap();
+
+ // The `i32.store` to [6, 10) is the first write to hit the watch.
+ let r = Resumption::continue_(d);
+ let Event::Watchpoint(hit) = r.result(d).unwrap() else {
+ panic!("expected a watchpoint event");
+ };
+ assert_eq!(hit.memory.unique_id(), mem.unique_id());
+ assert_eq!((hit.address, hit.len), (6, 4));
+ assert_eq!(hit.value, Some(0x11223344_u32.to_le_bytes().to_vec()));
+ // The write has not happened yet; the store to byte 7 has.
+ assert_eq!(mem.get_bytes(d, 6, 4).unwrap(), [0, 1, 0, 0]);
+
+ // Next, the `memory.fill`, which has no single value.
+ let r = Resumption::continue_(d);
+ let Event::Watchpoint(hit) = r.result(d).unwrap() else {
+ panic!("expected a watchpoint event");
+ };
+ assert_eq!((hit.address, hit.len, hit.value), (0, 16, None));
+ assert_eq!(mem.get_u32(d, 6).unwrap(), 0x11223344);
+ assert_eq!(mem.get_u8(d, 12).unwrap(), 2);
+
+ // Once unwatched, the fill proceeds and the debuggee runs to
+ // completion.
+ mem.remove_watchpoint(d, 0, 16).unwrap();
+ let r = Resumption::continue_(d);
+ let event = r.result(d).unwrap();
+ assert!(
+ matches!(event, Event::Complete),
+ "expected Complete, got {event:?}"
+ );
+
+ eprintln!("OK");
+}
+
fn main() {}
diff --git a/crates/test-programs/src/bin/debugger_debuggee_watch.wat b/crates/test-programs/src/bin/debugger_debuggee_watch.wat
new file mode 100644
index 0000000000..9e3fc1026a
--- /dev/null
+++ b/crates/test-programs/src/bin/debugger_debuggee_watch.wat
@@ -0,0 +1,13 @@
+(module
+ (memory (export "memory") 1)
+ (func (export "_start")
+ ;; Just below the watched range [8, 12).
+ (i32.store8 (i32.const 7) (i32.const 1))
+ ;; Partially overlaps the watched range.
+ (i32.store offset=6 (i32.const 0) (i32.const 0x11223344))
+ ;; Just above the watched range.
+ (i32.store8 (i32.const 12) (i32.const 2))
+ ;; Covers the whole watched range.
+ (memory.fill (i32.const 0) (i32.const 0xaa) (i32.const 16))
+ )
+)
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index 717a11a1f0..a9a7f90412 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -2819,6 +2819,9 @@ impl Config {
self.tunables.configure(&mut tunables);
+ // Debuggers set watchpoints through linear memories' shadows.
+ tunables.memory_watchpoints = tunables.debug_guest;
+
// If no GC heap tunables are explicitly configured, copy the memory
// tunables' configured values so that GC heaps default to the same
// configuration as linear memories.
diff --git a/crates/wasmtime/src/engine/serialization.rs b/crates/wasmtime/src/engine/serialization.rs
index d83c3b8496..0c8b8b3b00 100644
--- a/crates/wasmtime/src/engine/serialization.rs
+++ b/crates/wasmtime/src/engine/serialization.rs
@@ -316,6 +316,7 @@ impl Metadata<'_> {
concurrency_support,
recording,
asan_stack_switching,
+ memory_watchpoints,
// This doesn't affect compilation, it's just a runtime setting.
memory_reservation_for_growth: _,
@@ -429,6 +430,11 @@ impl Metadata<'_> {
other.asan_stack_switching,
"AddressSanitizer stack-switching support",
)?;
+ Self::check_bool(
+ memory_watchpoints,
+ other.memory_watchpoints,
+ "memory watchpoint support",
+ )?;
Self::check_inlining(inlining, other.inlining)?;
Self::check_int(
gc_heap_reservation,
diff --git a/crates/wasmtime/src/runtime/debug.rs b/crates/wasmtime/src/runtime/debug.rs
index 85da2462dc..9df28c0f11 100644
--- a/crates/wasmtime/src/runtime/debug.rs
+++ b/crates/wasmtime/src/runtime/debug.rs
@@ -886,6 +886,71 @@ pub enum DebugEvent<'a> {
Breakpoint,
/// An epoch yield occurred.
EpochYield,
+ /// Guest code is about to write watched bytes of a linear memory; see
+ /// [`Memory::debug_watch`](crate::Memory::debug_watch). The write happens
+ /// once the handler returns.
+ Watchpoint(WatchpointHit),
+}
+
+/// A guest write to watched bytes of a linear memory, reported before the
+/// write happens.
+#[derive(Clone, Copy, Debug)]
+pub struct WatchpointHit {
+ /// The memory being written.
+ pub memory: crate::Memory,
+ /// The address of the write's first byte.
+ pub address: u64,
+ /// The number of bytes written, of which at least one is watched.
+ pub len: u64,
+ /// For a store of up to 16 bytes, the bits being stored (in
+ /// little-endian order, so the first byte is the least significant).
+ /// `None` for bulk memory operations.
+ pub value: Option<u128>,
+}
+
+impl PartialEq for WatchpointHit {
+ fn eq(&self, other: &Self) -> bool {
+ self.memory.same(&other.memory)
+ && (self.address, self.len, self.value) == (other.address, other.len, other.value)
+ }
+}
+
+impl Eq for WatchpointHit {}
+
+impl crate::Memory {
+ /// Watches, or stops watching, guest writes to the bytes in `range` of this
+ /// memory. A guest store or bulk memory operation that writes a watched
+ /// byte raises [`DebugEvent::Watchpoint`] before writing. Whether a byte
+ /// is watched is a per-byte property, so unwatching a range unwatches its
+ /// bytes regardless of how they were watched.
+ ///
+ /// Watchpoints require guest debugging to be enabled; bytes beyond the
+ /// memory's current size cannot be watched.
+ pub fn debug_watch(
+ &self,
+ mut store: impl AsContextMut,
+ range: core::ops::Range<u64>,
+ watch: bool,
+ ) -> Result<()> {
+ let store = store.as_context_mut().0.as_store_opaque();
+ let Some(shadow) = self.vm_shadow_mut(store) else {
+ crate::error::bail!("watchpoints require guest debugging");
+ };
+ let bytes = shadow.bytes_mut();
+ let start = usize::try_from(range.start)?;
+ let end = usize::try_from(range.end)?;
+ let Some(bytes) = bytes.get_mut(start..end) else {
+ crate::error::bail!("watchpoint range is out of bounds of the memory");
+ };
+ for byte in bytes {
+ if watch {
+ *byte |= crate::runtime::vm::WATCH_DEBUG;
+ } else {
+ *byte &= !crate::runtime::vm::WATCH_DEBUG;
+ }
+ }
+ Ok(())
+ }
}
/// A handler for debug events.
diff --git a/crates/wasmtime/src/runtime/memory.rs b/crates/wasmtime/src/runtime/memory.rs
index c07c8dc0a7..360fcb0c43 100644
--- a/crates/wasmtime/src/runtime/memory.rs
+++ b/crates/wasmtime/src/runtime/memory.rs
@@ -735,6 +735,32 @@ impl Memory {
store.id() == self.instance.store_id()
}
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ pub(crate) fn vm_shadow<'a>(
+ &self,
+ store: &'a StoreOpaque,
+ ) -> Option<&'a crate::runtime::vm::ShadowMemory> {
+ store[self.instance].get_defined_memory(self.index).shadow()
+ }
+
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ #[cfg(feature = "debug")]
+ pub(crate) fn vm_shadow_mut<'a>(
+ &self,
+ store: &'a mut StoreOpaque,
+ ) -> Option<&'a mut crate::runtime::vm::ShadowMemory> {
+ self.instance
+ .get_mut(store)
+ .get_defined_memory_mut(self.index)
+ .shadow_mut()
+ }
+
+ /// Whether this is the same memory as `other`.
+ #[cfg(feature = "debug")]
+ pub(crate) fn same(&self, other: &Memory) -> bool {
+ self.instance == other.instance && self.index == other.index
+ }
+
/// Returns a stable identifier for this memory within its store.
///
/// This allows distinguishing memories when introspecting them
diff --git a/crates/wasmtime/src/runtime/vm.rs b/crates/wasmtime/src/runtime/vm.rs
index 76707bb380..9ca03dcfc4 100644
--- a/crates/wasmtime/src/runtime/vm.rs
+++ b/crates/wasmtime/src/runtime/vm.rs
@@ -109,7 +109,9 @@ pub use crate::runtime::vm::instance::{
PoolConcurrencyLimitError, PoolingAllocatorMetrics, PoolingInstanceAllocator,
};
pub use crate::runtime::vm::interpreter::*;
-pub use crate::runtime::vm::memory::{Memory, SharedMemory};
+#[cfg(feature = "debug")]
+pub use crate::runtime::vm::memory::WATCH_DEBUG;
+pub use crate::runtime::vm::memory::{Memory, ShadowMemory, SharedMemory};
pub use crate::runtime::vm::mmap_vec::MmapVec;
pub use crate::runtime::vm::provenance::*;
pub use crate::runtime::vm::stack_switching::*;
diff --git a/crates/wasmtime/src/runtime/vm/instance.rs b/crates/wasmtime/src/runtime/vm/instance.rs
index 460ab810f9..ee824038cb 100644
--- a/crates/wasmtime/src/runtime/vm/instance.rs
+++ b/crates/wasmtime/src/runtime/vm/instance.rs
@@ -1310,6 +1310,35 @@ impl Instance {
}
}
+ // If this module's code checks memory shadows, point to each memory's
+ // watchpoint shadow, if it has one. An imported memory's shadow
+ // belongs to the instance that defines it.
+ if module.has_shadow_memories {
+ // SAFETY: the imports were written above and refer to live
+ // instances.
+ unsafe {
+ let offsets = instance.runtime_info.offsets();
+ let mut ptr = instance.vmctx_plus_offset_raw::<VmPtr<VMMemoryDefinition>>(
+ offsets.shadow_memories().begin(),
+ );
+ for i in 0..module.memories.len() {
+ let index = MemoryIndex::new(i);
+ let memory = match module.defined_memory_index(index) {
+ Some(def_index) => instance.get_defined_memory(def_index),
+ None => {
+ let import = instance.imported_memory(index);
+ instance
+ .sibling_vmctx(import.vmctx.as_non_null())
+ .get_defined_memory(import.index)
+ }
+ };
+ let shadow = memory.shadow().map(|s| s.vmmemory_ptr());
+ ptr.write(VmPtr::from(shadow.unwrap_or(NonNull::dangling())));
+ ptr = ptr.add(1);
+ }
+ }
+ }
+
// Zero-initialize the globals so that nothing is uninitialized memory
// after this function returns. The globals are actually initialized
// with their const expression initializers after the instance is fully
diff --git a/crates/wasmtime/src/runtime/vm/libcalls.rs b/crates/wasmtime/src/runtime/vm/libcalls.rs
index 7b4acc6883..e1cc9cc46f 100644
--- a/crates/wasmtime/src/runtime/vm/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/libcalls.rs
@@ -1227,6 +1227,85 @@ fn throw_ref(store: &mut dyn VMStore, _instance: InstanceId, exnref: u32) -> Res
Err(store.set_pending_exception(&exnref))
}
+/// Handles a guest store of `len` bytes (with bits `hi:lo`) to watched bytes
+/// of a linear memory, before it happens.
+fn memory_watch_store(
+ store: &mut dyn VMStore,
+ instance: InstanceId,
+ memory: u32,
+ addr: u64,
+ len: u32,
+ lo: u64,
+ hi: u64,
+) -> Result<()> {
+ let bits = (u128::from(hi) << 64) | u128::from(lo);
+ let mask = u128::MAX >> (128 - 8 * len.min(16));
+ watched_write(
+ store,
+ instance,
+ memory,
+ addr,
+ u64::from(len),
+ Some(bits & mask),
+ )
+}
+
+/// Handles a guest bulk write of `len` bytes to a linear memory, before it
+/// happens, if any of the bytes are watched.
+fn memory_watch_range(
+ store: &mut dyn VMStore,
+ instance: InstanceId,
+ memory: u32,
+ addr: u64,
+ len: u64,
+) -> Result<()> {
+ watched_write(store, instance, memory, addr, len, None)
+}
+
+fn watched_write(
+ store: &mut dyn VMStore,
+ instance: InstanceId,
+ memory: u32,
+ addr: u64,
+ len: u64,
+ value: Option<u128>,
+) -> Result<()> {
+ let opaque = store.store_opaque_mut();
+ let store_id = opaque.id();
+ let memory = match opaque
+ .instance_mut(instance)
+ .get_exported_memory(store_id, wasmtime_environ::MemoryIndex::from_u32(memory))
+ {
+ crate::runtime::vm::ExportMemory::Unshared(memory) => memory,
+ crate::runtime::vm::ExportMemory::Shared(..) => return Ok(()),
+ };
+ // An out-of-bounds bulk write traps after this returns.
+ let Some(shadow) = memory.vm_shadow(opaque) else {
+ return Ok(());
+ };
+ let start = usize::try_from(addr)
+ .unwrap_or(usize::MAX)
+ .min(shadow.bytes().len());
+ let end = usize::try_from(addr.saturating_add(len))
+ .unwrap_or(usize::MAX)
+ .min(shadow.bytes().len());
+ let bits = shadow.bytes()[start..end]
+ .iter()
+ .fold(0, |bits, byte| bits | *byte);
+ #[cfg(feature = "debug")]
+ if bits & crate::runtime::vm::WATCH_DEBUG != 0 {
+ let hit = crate::WatchpointHit {
+ memory,
+ address: addr,
+ len,
+ value,
+ };
+ store.block_on_debug_handler(crate::DebugEvent::Watchpoint(hit))?;
+ }
+ let _ = (bits, value);
+ Ok(())
+}
+
fn breakpoint(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
#[cfg(feature = "debug")]
{
diff --git a/crates/wasmtime/src/runtime/vm/memory.rs b/crates/wasmtime/src/runtime/vm/memory.rs
index 617d137ec2..7a9a22c3bd 100644
--- a/crates/wasmtime/src/runtime/vm/memory.rs
+++ b/crates/wasmtime/src/runtime/vm/memory.rs
@@ -92,6 +92,11 @@ pub use self::mmap::MmapMemory;
mod malloc;
pub use self::malloc::MallocMemory;
+mod shadow;
+pub use self::shadow::ShadowMemory;
+#[cfg(feature = "debug")]
+pub use self::shadow::WATCH_DEBUG;
+
#[cfg(feature = "pooling-allocator")]
mod static_;
#[cfg(feature = "pooling-allocator")]
@@ -310,6 +315,22 @@ impl Memory {
}
}
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ pub fn shadow(&self) -> Option<&ShadowMemory> {
+ match self {
+ Memory::Local(mem) => mem.shadow(),
+ Memory::Shared(_) => None,
+ }
+ }
+
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ pub fn shadow_mut(&mut self) -> Option<&mut ShadowMemory> {
+ match self {
+ Memory::Local(mem) => mem.shadow_mut(),
+ Memory::Shared(_) => None,
+ }
+ }
+
/// Returns whether or not this memory needs initialization. It
/// may not if it already has initial content thanks to a CoW
/// mechanism.
@@ -478,6 +499,9 @@ pub struct LocalMemory {
/// The memory might be already initialized from a pooled allocator or by the particular
/// allocation's implementation, in which case this is false.
needs_init: bool,
+
+ /// The watchpoint shadow of this memory, when compiled code checks it.
+ shadow: Option<ShadowMemory>,
}
impl LocalMemory {
@@ -494,11 +518,18 @@ impl LocalMemory {
Some(image) => alloc.init_from_image(&crate::MemoryImage::new(image.clone()))?,
None => false,
};
+ // Shared memories have no shadow and cannot be watched.
+ let shadow = if memory_tunables.watchpoints() && !ty.shared {
+ Some(ShadowMemory::new(ty, memory_tunables, alloc.byte_size())?)
+ } else {
+ None
+ };
Ok(LocalMemory {
ty: *ty,
alloc,
memory_may_move: ty.memory_may_move(memory_tunables),
needs_init: !initialized,
+ shadow,
memory_guard_size: memory_tunables.guard_size().try_into().unwrap(),
memory_reservation: memory_tunables.reservation().try_into().unwrap(),
})
@@ -587,6 +618,13 @@ impl LocalMemory {
bail!("Memory maximum size exceeded");
}
+ // The shadow grows along with this memory, below.
+ if let Some(shadow) = &self.shadow {
+ if !shadow.can_grow_to(new_byte_size) {
+ bail!("Memory maximum size exceeded");
+ }
+ }
+
self.alloc.grow_to(new_byte_size)
})();
@@ -601,6 +639,9 @@ impl LocalMemory {
"linear memory moved on grow when it must not have"
);
}
+ if let Some(shadow) = &mut self.shadow {
+ shadow.grow_to(new_byte_size)?;
+ }
Ok(Some((old_byte_size, new_byte_size)))
}
@@ -620,11 +661,17 @@ impl LocalMemory {
/// Return the bounds of the memory (base, byte_size) for consumption by WebAssembly code in a
/// repr(C) struct.
pub fn vmmemory(&self) -> VMMemoryDefinition {
- let base = NonNull::new(self.alloc.as_ptr()).expect("linear memory base is non-null");
- VMMemoryDefinition {
- base: base.into(),
- current_length: self.alloc.byte_size().into(),
- }
+ vmmemory(&*self.alloc)
+ }
+
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ pub fn shadow(&self) -> Option<&ShadowMemory> {
+ self.shadow.as_ref()
+ }
+
+ /// This memory's watchpoint shadow, if compiled code checks it.
+ pub fn shadow_mut(&mut self) -> Option<&mut ShadowMemory> {
+ self.shadow.as_mut()
}
pub fn byte_size(&self) -> usize {
@@ -664,6 +711,16 @@ impl LocalMemory {
}
}
+/// The bounds of `alloc` (base, byte_size) for consumption by WebAssembly code
+/// in a repr(C) struct.
+fn vmmemory(alloc: &dyn LinearMemory) -> VMMemoryDefinition {
+ let base = NonNull::new(alloc.as_ptr()).expect("linear memory base is non-null");
+ VMMemoryDefinition {
+ base: base.into(),
+ current_length: alloc.byte_size().into(),
+ }
+}
+
/// In the configurations where bounds checks were elided in JIT code (because
/// we are using static memories with virtual memory guard pages) this manual
/// check is here so we don't segfault from Rust. For other configurations,
diff --git a/crates/wasmtime/src/runtime/vm/memory/shadow.rs b/crates/wasmtime/src/runtime/vm/memory/shadow.rs
new file mode 100644
index 0000000000..953098c114
--- /dev/null
+++ b/crates/wasmtime/src/runtime/vm/memory/shadow.rs
@@ -0,0 +1,97 @@
+//! The shadow bytes of linear memories, for watchpoints.
+//!
+//! When `Tunables::memory_watchpoints` is enabled, compiled code checks a
+//! memory's shadow before every store: a nonzero shadow byte calls a
+//! watchpoint builtin before the corresponding memory byte is written. The
+//! bits of a shadow byte say why it is watched.
+
+use crate::prelude::*;
+use crate::runtime::vm::memory::DefaultMemoryCreator;
+use crate::runtime::vm::vmcontext::VMMemoryDefinition;
+use crate::{LinearMemory, MemoryCreator, MemoryRequest};
+use core::ptr::NonNull;
+use wasmtime_environ::MemoryTunables;
+
+/// A shadow bit set for each byte a debugger watches.
+#[cfg(feature = "debug")]
+pub const WATCH_DEBUG: u8 = 1 << 0;
+
+/// The shadow of a linear memory: one byte per byte of the memory.
+///
+/// The shadow is itself a linear memory, of the same type and allocated with
+/// the same tunables as the memory it shadows, and grows along with it.
+/// Compiled code accesses the shadow just like any other linear memory, with
+/// its own bounds check, at the same Wasm address as the memory access.
+///
+/// This is owned by the memory's `LocalMemory`, and so is freed along with the
+/// memory itself, when the store deallocates the instance that defines the
+/// memory. Instances that import the memory only hold pointers to it, just as
+/// they do to the memory's `VMMemoryDefinition`, and are deallocated with the
+/// same store.
+pub struct ShadowMemory {
+ alloc: Box<dyn LinearMemory>,
+ // Compiled code reaches the shadow through this definition, which has a
+ // stable address even when the shadow's base moves or its size changes.
+ // Every instance that uses the memory, whether it defines or imports it,
+ // points to this one definition.
+ definition: Box<VMMemoryDefinition>,
+ // Whether compiled code reloads the shadow's base, which otherwise must
+ // never move.
+ may_move: bool,
+}
+
+impl ShadowMemory {
+ /// Creates an unwatched shadow for a memory of type `ty` and `len` bytes.
+ pub fn new(
+ ty: &wasmtime_environ::Memory,
+ memory_tunables: &MemoryTunables<'_>,
+ len: usize,
+ ) -> Result<Self> {
+ let maximum = ty
+ .maximum_byte_size()
+ .ok()
+ .and_then(|n| usize::try_from(n).ok());
+ let request = MemoryRequest::new(ty, memory_tunables, len, maximum);
+ let alloc = DefaultMemoryCreator.new_memory(&request)?;
+ let definition = try_new::<Box<_>>(super::vmmemory(&*alloc))?;
+ Ok(ShadowMemory {
+ alloc,
+ definition,
+ may_move: ty.memory_may_move(memory_tunables),
+ })
+ }
+
+ /// The definition through which compiled code finds the shadow bytes.
+ pub fn vmmemory_ptr(&self) -> NonNull<VMMemoryDefinition> {
+ NonNull::from(&*self.definition)
+ }
+
+ /// The shadow bytes, one per byte of the memory.
+ pub fn bytes(&self) -> &[u8] {
+ // SAFETY: the allocation's first `byte_size` bytes are accessible,
+ // and only borrowed through this shadow.
+ unsafe { core::slice::from_raw_parts(self.alloc.as_ptr(), self.byte_size()) }
+ }
+
+ /// The shadow bytes, one per byte of the memory.
+ pub fn bytes_mut(&mut self) -> &mut [u8] {
+ // SAFETY: as for `bytes`.
+ unsafe { core::slice::from_raw_parts_mut(self.alloc.as_ptr(), self.byte_size()) }
+ }
+
+ pub(super) fn byte_size(&self) -> usize {
+ self.alloc.byte_size()
+ }
+
+ /// Whether the shadow can follow the memory's growth to `len` bytes.
+ pub(super) fn can_grow_to(&self, len: usize) -> bool {
+ self.may_move || len <= self.alloc.byte_capacity()
+ }
+
+ /// Follows the memory's growth to `len` bytes.
+ pub(super) fn grow_to(&mut self, len: usize) -> Result<()> {
+ self.alloc.grow_to(len)?;
+ *self.definition = super::vmmemory(&*self.alloc);
+ Ok(())
+ }
+}
diff --git a/tests/all/debug.rs b/tests/all/debug.rs
index 692dbd1916..88885fb032 100644
--- a/tests/all/debug.rs
+++ b/tests/all/debug.rs
@@ -1870,6 +1870,29 @@ async fn fuel_visible_and_mutable_in_debug_handler() -> wasmtime::Result<()> {
Ok(())
}
+/// Records each watchpoint hit, with the watched memory's first 64 bytes as
+/// the handler sees them.
+#[derive(Clone, Default)]
+struct WatchRecorder(Arc<Mutex<Vec<(u64, u64, Option<u128>, Vec<u8>)>>>);
+
+impl DebugHandler for WatchRecorder {
+ type Data = ();
+ fn handle(
+ &self,
+ store: StoreContextMut<'_, ()>,
+ event: DebugEvent<'_>,
+ ) -> impl Future<Output = ()> + Send {
+ if let DebugEvent::Watchpoint(hit) = event {
+ let memory = hit.memory.data(&store)[..64].to_vec();
+ self.0
+ .lock()
+ .unwrap()
+ .push((hit.address, hit.len, hit.value, memory));
+ }
+ async {}
+ }
+}
+
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn uninit_non_nullable_ref_local_in_single_step() -> Result<()> {
@@ -1978,3 +2001,165 @@ async fn uninit_non_nullable_ref_local_in_single_step() -> Result<()> {
}
}
}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn watchpoints_report_writes_before_they_happen() -> wasmtime::Result<()> {
+ let (module, mut store) = get_module_and_store(
+ |_| {},
+ r#"
+ (module
+ (memory (export "memory") 1)
+ (func (export "main")
+ (i32.store offset=16 (i32.const 0) (i32.const 0x11223344))
+ (i64.store (i32.const 24) (i64.const -1))
+ (v128.store (i32.const 32) (v128.const i64x2 1 2))
+ (f32.store (i32.const 48) (f32.const 1.5))
+ (i32.store8 (i32.const 100) (i32.const 7))
+ (memory.fill (i32.const 40) (i32.const 0xaa) (i32.const 8))))
+ "#,
+ )?;
+ let recorder = WatchRecorder::default();
+ store.set_debug_handler(recorder.clone());
+ let instance = Instance::new_async(&mut store, &module, &[]).await?;
+ let memory = instance.get_memory(&mut store, "memory").unwrap();
+ let main = instance.get_typed_func::<(), ()>(&mut store, "main")?;
+
+ // Watch [17, 52): the i32 store overlaps it partially, and the store to
+ // byte 100 not at all.
+ memory.debug_watch(&mut store, 17..52, true)?;
+ main.call_async(&mut store, ()).await?;
+ {
+ let hits = recorder.0.lock().unwrap();
+ let summary = hits
+ .iter()
+ .map(|(address, len, value, _)| (*address, *len, *value))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ summary,
+ [
+ (16, 4, Some(0x11223344)),
+ (24, 8, Some(u128::from(u64::MAX))),
+ (32, 16, Some((2 << 64) | 1)),
+ (48, 4, Some(u128::from(1.5_f32.to_bits()))),
+ (40, 8, None),
+ ]
+ );
+ // Each hit is reported before its write.
+ assert_eq!(&hits[0].3[16..20], &[0; 4]);
+ assert_eq!(&hits[1].3[16..20], &0x11223344_u32.to_le_bytes());
+ assert_eq!(&hits[4].3[40..48], &2_u64.to_le_bytes());
+ }
+ assert_eq!(&memory.data(&store)[40..48], &[0xaa; 8]);
+
+ // Unwatched bytes no longer report writes.
+ recorder.0.lock().unwrap().clear();
+ memory.debug_watch(&mut store, 0..64, false)?;
+ main.call_async(&mut store, ()).await?;
+ assert!(recorder.0.lock().unwrap().is_empty());
+
+ // Watches must be within the memory.
+ assert!(memory.debug_watch(&mut store, 0..65537, true).is_err());
+ Ok(())
+}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn watchpoints_on_imported_memory_follow_growth() -> wasmtime::Result<()> {
+ // `$definer` defines and grows the memory, and `$importer` writes to it,
+ // so both instances must find the shadow as it grows.
+ let (definer, mut store) = get_module_and_store(
+ |_| {},
+ r#"
+ (module
+ (memory (export "memory") 1)
+ (func (export "grow") (param i32) (result i32)
+ (memory.grow (local.get 0))))
+ "#,
+ )?;
+ let importer = Module::new(
+ store.engine(),
+ r#"
+ (module
+ (import "" "memory" (memory 1))
+ (func (export "store") (param i32 i32)
+ (i32.store8 (local.get 0) (local.get 1))))
+ "#,
+ )?;
+ let recorder = WatchRecorder::default();
+ store.set_debug_handler(recorder.clone());
+ let definer = Instance::new_async(&mut store, &definer, &[]).await?;
+ let memory = definer.get_memory(&mut store, "memory").unwrap();
+ let importer = Instance::new_async(&mut store, &importer, &[memory.into()]).await?;
+ let grow = definer.get_typed_func::<i32, i32>(&mut store, "grow")?;
+ let store8 = importer.get_typed_func::<(i32, i32), ()>(&mut store, "store")?;
+
+ // Watch a byte, then grow the memory, and watch a byte in the new pages
+ // too.
+ memory.debug_watch(&mut store, 10..11, true)?;
+ assert_eq!(grow.call_async(&mut store, 7).await?, 1);
+ let high = 7 * 65536 + 3;
+ memory.debug_watch(&mut store, high..high + 1, true)?;
+
+ // Writes through the importing instance see both watches, and only
+ // those.
+ store8.call_async(&mut store, (10, 1)).await?;
+ store8.call_async(&mut store, (11, 1)).await?;
+ store8
+ .call_async(&mut store, (i32::try_from(high)?, 1))
+ .await?;
+ let hits = recorder
+ .0
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|(address, len, _, _)| (*address, *len))
+ .collect::<Vec<_>>();
+ assert_eq!(hits, [(10, 1), (high, 1)]);
+ Ok(())
+}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn watchpoints_out_of_bounds_stores_trap() -> wasmtime::Result<()> {
+ // Try both mmap- and malloc-backed memories (and so shadows).
+ let configs: [fn(&mut Config); 2] = [
+ |_| {},
+ |config| {
+ config
+ .memory_reservation(0)
+ .memory_guard_size(0)
+ .memory_init_cow(false);
+ },
+ ];
+ for configure in configs {
+ let (module, mut store) = get_module_and_store(
+ configure,
+ r#"
+ (module
+ (memory (export "memory") 1)
+ (func (export "store") (param i32)
+ (i64.store (local.get 0) (i64.const -1))))
+ "#,
+ )?;
+ let recorder = WatchRecorder::default();
+ store.set_debug_handler(recorder.clone());
+ let instance = Instance::new_async(&mut store, &module, &[]).await?;
+ let memory = instance.get_memory(&mut store, "memory").unwrap();
+ let store_i64 = instance.get_typed_func::<i32, ()>(&mut store, "store")?;
+ memory.debug_watch(&mut store, 65528..65536, true)?;
+
+ // A store that is partially or entirely out of bounds traps before
+ // checking for watchpoints.
+ for addr in [65532, 65536, 1 << 20, -1] {
+ let err = store_i64.call_async(&mut store, addr).await.unwrap_err();
+ assert_eq!(err.downcast::<Trap>()?, Trap::MemoryOutOfBounds);
+ }
+ assert!(recorder.0.lock().unwrap().is_empty());
+
+ // An in-bounds store to the same watched bytes is reported.
+ store_i64.call_async(&mut store, 65528).await?;
+ assert_eq!(recorder.0.lock().unwrap().len(), 1);
+ }
+ Ok(())
+}
diff --git a/tests/all/debug_component.rs b/tests/all/debug_component.rs
index 6dc7ead5d6..305a69c57a 100644
--- a/tests/all/debug_component.rs
+++ b/tests/all/debug_component.rs
@@ -47,6 +47,15 @@ fn debugger_debuggee_loop() -> Result<()> {
)
}
+#[test]
+fn debugger_debuggee_watch() -> Result<()> {
+ run_debugger_test(
+ DEBUGGER_COMPONENT_COMPONENT,
+ DEBUGGER_DEBUGGEE_WATCH_COMPONENT,
+ "watch",
+ )
+}
+
#[test]
fn debugger_component() -> Result<()> {
// This is present so that `assert_test_exists` can assert presence of unit-tests for all
diff --git a/tests/all/guest_debug/mod.rs b/tests/all/guest_debug/mod.rs
index b115dd9967..23a98716bc 100644
--- a/tests/all/guest_debug/mod.rs
+++ b/tests/all/guest_debug/mod.rs
@@ -501,6 +501,53 @@ check: handle
Ok(())
}
+/// Test write watchpoints on a stack variable: LLDB reports each write
+/// that changes `a` as a watchpoint stop, after the write.
+#[test]
+#[ignore]
+fn guest_debug_cli_fib_watchpoint() -> Result<()> {
+ let mut wt = WasmtimeWithGdbstub::spawn(
+ "run",
+ &["-Ccache=n", GUEST_DEBUG_FIB],
+ Duration::from_secs(30),
+ )?;
+
+ let output = lldb_with_gdbstub_script(
+ wt.port,
+ r#"
+b fib
+c
+br disable 1
+watchpoint set variable a
+c
+fr v
+c
+fr v
+watchpoint delete 1
+c
+"#,
+ )?;
+ wt.child.kill().ok();
+ wt.child.wait()?;
+
+ check_output(
+ &output,
+ r#"
+check: Watchpoint created: Watchpoint 1
+check: old value: 0
+check: new value: 1
+check: stop reason = watchpoint 1
+check: a = 1
+check: old value: 1
+check: new value: 2
+check: stop reason = watchpoint 1
+check: a = 2
+check: exited with status = 0
+"#,
+ )?;
+ Ok(())
+}
+
/// A minimal GDB remote serial protocol client, for tests that need
/// precise control over the packets sent.
struct RspClient {
@@ -556,6 +603,72 @@ impl RspClient {
}
}
+/// Test write watchpoints at the protocol level: read watchpoints are
+/// rejected, overlapping watchpoints remain after each other's removal,
+/// and stops are reported after the write with the first watched address.
+#[test]
+#[ignore]
+fn guest_debug_rsp_watchpoints() -> Result<()> {
+ let dir = tempfile::tempdir()?;
+ let wat = dir.path().join("watch.wat");
+ std::fs::write(
+ &wat,
+ r#"
+(module
+ (memory (export "memory") 1)
+ (func (export "_start")
+ (i32.store (i32.const 16) (i32.const 0x11223344))
+ (i32.store8 (i32.const 32) (i32.const 1))))
+"#,
+ )?;
+ let mut wt = WasmtimeWithGdbstub::spawn(
+ "run",
+ &["-Ccache=n", wat.to_str().unwrap()],
+ Duration::from_secs(30),
+ )?;
+
+ let result = (|| -> Result<()> {
+ let mut rsp = RspClient::connect(wt.port)?;
+ rsp.request("?")?;
+ // Step to the first instruction, so that the memory exists.
+ let reply = rsp.request("s")?;
+ assert!(reply.starts_with("T05"), "unexpected step reply: {reply}");
+
+ // Only write watchpoints are supported.
+ assert!(rsp.request("Z3,10,4")?.starts_with('E'));
+ assert!(rsp.request("Z4,10,4")?.starts_with('E'));
+ // Watchpoints must be within the memory.
+ assert!(rsp.request("Z2,fffe,4")?.starts_with('E'));
+
+ // Watch [16, 20) and the overlapping [18, 20), then remove the
+ // former: [18, 20) must still be watched.
+ assert_eq!(rsp.request("Z2,10,4")?, "OK");
+ assert_eq!(rsp.request("Z2,12,2")?, "OK");
+ assert_eq!(rsp.request("z2,10,4")?, "OK");
+ // Removing something never added fails.
+ assert!(rsp.request("z2,10,4")?.starts_with('E'));
+
+ // The store to [16, 20) stops, reporting the first watched byte,
+ // once the write has happened.
+ let reply = rsp.request("c")?;
+ assert!(
+ reply.starts_with("T05") && reply.contains("watch:12;"),
+ "unexpected stop reply: {reply}"
+ );
+ assert_eq!(rsp.request("m10,4")?, "44332211");
+
+ // With nothing watched, execution runs to completion.
+ assert_eq!(rsp.request("z2,12,2")?, "OK");
+ let reply = rsp.request("c")?;
+ assert!(reply.starts_with('W'), "unexpected exit reply: {reply}");
+ Ok(())
+ })();
+
+ wt.child.kill().ok();
+ wt.child.wait()?;
+ result
+}
+
/// A long loop with no host calls, which only an interrupt can stop early.
const SPIN_WAT: &str = r#"
(module
diff --git a/tests/disas/memory-watchpoints.wat b/tests/disas/memory-watchpoints.wat
new file mode 100644
index 0000000000..033d850d16
--- /dev/null
+++ b/tests/disas/memory-watchpoints.wat
@@ -0,0 +1,113 @@
+;;! target = "x86_64"
+;;! test = "optimize"
+;;! flags = ["-Dguest-debug=yes"]
+
+;; With guest debugging, each store first checks the memory's shadow bytes, a
+;; bounds-checked access of the shadow memory at the same Wasm address, and
+;; calls the watchpoint builtin if any are set.
+(module
+ (memory 1)
+ (func (param i32 i64)
+ (i64.store offset=8 (local.get 0) (local.get 1))))
+;; function u0:0(i64 vmctx, i64, i32, i64) tail {
+;; ss0 = explicit_slot 32, key = 0
+;; region0 = 123 ""
+;; region1 = 160 ""
+;; region2 = 135 ""
+;; region3 = 215 ""
+;; region4 = 105 ""
+;; region5 = 133 ""
+;; region6 = 171 ""
+;; region7 = 153 ""
+;; sig0 = (i64 vmctx, i8) tail
+;; sig1 = (i64 vmctx) tail
+;; sig2 = (i64) preserve_all
+;; sig3 = (i64 vmctx, i32, i64, i32, i64, i64) -> i8 tail
+;; fn0 = colocated u805306368:39 sig0
+;; fn1 = colocated u805306368:40 sig1
+;; fn2 = colocated patchable u1073741824:45 sig2
+;; fn3 = colocated u805306368:50 sig3
+;;
+;; block0(v0: i64, v1: i64, v2: i32, v3: i64):
+;; @001d v4 = stack_addr.i64 ss0+8
+;; @001d store notrap region2 v2, v4
+;; @001d v5 = stack_addr.i64 ss0+12
+;; @001d store notrap region2 v3, v5
+;; @001d v6 = load.i64 notrap aligned readonly can_move region0 v0+8
+;; @001d v7 = load.i64 notrap aligned region1 v6+24
+;; @001d v8 = get_stack_pointer.i64
+;; @001d v9 = icmp ult v8, v7
+;; @001d brif v9, block2, block3
+;;
+;; block2 cold:
+;; @0022 v19 = iconst.i8 0
+;; @001d call fn0(v0, v19) ; v19 = 0
+;; <ss0, 29, 4294967295> @001d call fn1(v0)
+;; @001d trap user1
+;;
+;; block3:
+;; @001d v11 = stack_addr.i64 ss0
+;; @001d store.i64 notrap region2 v0, v11
+;; <ss0, 30, 4294967295> @001e call fn2(v0)
+;; @001e v12 = stack_addr.i64 ss0+20
+;; @001e store.i32 notrap region2 v2, v12
+;; <ss0, 32, 0> @0020 call fn2(v0)
+;; @0020 v13 = stack_addr.i64 ss0+24
+;; @0020 store.i64 notrap region2 v3, v13
+;; <ss0, 34, 1> @0022 call fn2(v0)
+;; @0022 v15 = load.i64 notrap aligned region4 v0+64
+;; @0022 v14 = uextend.i64 v2
+;; @0022 v16 = iconst.i64 16
+;; @0022 v17 = isub v15, v16 ; v16 = 16
+;; @0022 v18 = icmp ugt v14, v17
+;; @0022 brif v18, block4, block5
+;;
+;; block4 cold:
+;; v54 = iconst.i8 1
+;; @0022 call fn0(v0, v54) ; v54 = 1
+;; <ss0, 34, 4294967295> @0022 call fn1(v0)
+;; @0022 trap user1
+;;
+;; block5:
+;; @0022 v27 = load.i64 notrap aligned readonly can_move region5 v0+72
+;; @0022 v28 = load.i64 notrap aligned region4 v27+8
+;; v48 = iconst.i64 16
+;; v49 = isub v28, v48 ; v48 = 16
+;; @0022 v31 = icmp.i64 ugt v14, v49
+;; @0022 brif v31, block6, block7
+;;
+;; block6 cold:
+;; @0022 v34 = iconst.i8 1
+;; @0022 call fn0(v0, v34) ; v34 = 1
+;; <ss0, 34, 4294967295> @0022 call fn1(v0)
+;; @0022 trap user1
+;;
+;; block7:
+;; @0022 v36 = load.i64 notrap aligned readonly can_move region3 v27
+;; @0022 v37 = iadd v36, v14
+;; @0022 v24 = iconst.i64 8
+;; @0022 v39 = iadd v37, v24 ; v24 = 8
+;; @0022 v40 = load.i64 region7 v39
+;; @0022 brif v40, block8, block9
+;;
+;; block8 cold:
+;; @0022 v42 = iconst.i32 0
+;; v50 = iconst.i64 8
+;; v51 = iadd.i64 v14, v50 ; v50 = 8
+;; @0022 v46 = iconst.i32 8
+;; @0022 v41 = iconst.i64 0
+;; @0022 v47 = call fn3(v0, v42, v51, v46, v3, v41) ; v42 = 0, v46 = 8, v41 = 0
+;; @0022 jump block9
+;;
+;; block9:
+;; @0022 v22 = load.i64 notrap aligned readonly can_move region3 v0+56
+;; @0022 v23 = iadd v22, v14
+;; v52 = iconst.i64 8
+;; v53 = iadd v23, v52 ; v52 = 8
+;; @0022 store.i64 little region6 v3, v53
+;; <ss0, 37, 4294967295> @0025 call fn2(v0)
+;; @0025 jump block1
+;;
+;; block1:
+;; @0025 return
+;; }