Skip to content

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

Debugging: explicitly null-initialize non-nullable locals' state slots. (#14655)

Chris Fallind6ad2b172449
diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs
index 3461bb3fe0..665cba437b 100644
--- a/crates/cranelift/src/func_environ.rs
+++ b/crates/cranelift/src/func_environ.rs
@@ -1317,26 +1317,29 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
}
/// Update the state slot layout with a new layout given a local.
+ ///
+ /// If there is a state slot, `init` is invoked to produce the local's
+ /// initial value, which is stored in its entry.
pub(crate) fn add_state_slot_local(
&mut self,
builder: &mut FunctionBuilder,
ty: WasmValType,
- init: Option<ir::Value>,
- ) {
+ init: impl FnOnce(&mut Self, &mut FunctionBuilder) -> WasmResult<ir::Value>,
+ ) -> WasmResult<()> {
if let Some((slot, b)) = &mut self.state_slot {
let offset = b.add_local(FrameValType::from(ty));
- if let Some(init) = init {
- let slot = *slot;
- let region = self.alias_regions.stack_slot_region(builder.func, slot);
- let address = builder
- .ins()
- .stack_addr(self.pointer_type(), slot, offset.offset());
- let flags = self
- .memflags_for_debug_slot_value_wasm_ty(ty)
- .with_alias_region(Some(region));
- builder.ins().store(flags, init, address, 0);
- }
+ let slot = *slot;
+ let init = init(self, builder)?;
+ let region = self.alias_regions.stack_slot_region(builder.func, slot);
+ let address = builder
+ .ins()
+ .stack_addr(self.pointer_type(), slot, offset.offset());
+ let flags = self
+ .memflags_for_debug_slot_value_wasm_ty(ty)
+ .with_alias_region(Some(region));
+ builder.ins().store(flags, init, address, 0);
}
+ Ok(())
}
fn update_state_slot_stack(
diff --git a/crates/cranelift/src/translate/func_translator.rs b/crates/cranelift/src/translate/func_translator.rs
index d1b0857716..d553b81872 100644
--- a/crates/cranelift/src/translate/func_translator.rs
+++ b/crates/cranelift/src/translate/func_translator.rs
@@ -82,7 +82,7 @@ impl FuncTranslator {
// `environ`. The callback functions may need to insert things in the entry block.
builder.ensure_inserted_block();
- let num_params = declare_wasm_parameters(&mut builder, entry_block, environ);
+ let num_params = declare_wasm_parameters(&mut builder, entry_block, environ)?;
// Set up the translation state with a single pushed control block representing the whole
// function and its return values.
@@ -158,7 +158,7 @@ fn declare_wasm_parameters(
builder: &mut FunctionBuilder,
entry_block: Block,
environ: &mut FuncEnvironment<'_>,
-) -> usize {
+) -> WasmResult<usize> {
let sig_len = builder.func.signature.params.len();
let mut next_local = 0;
for i in 0..sig_len {
@@ -178,7 +178,7 @@ fn declare_wasm_parameters(
let param_value = builder.block_params(entry_block)[i];
builder.def_var(local, param_value);
- environ.add_state_slot_local(builder, wasm_type, Some(param_value));
+ environ.add_state_slot_local(builder, wasm_type, |_, _| Ok(param_value))?;
}
if param_type.purpose == ir::ArgumentPurpose::VMContext {
let param_value = builder.block_params(entry_block)[i];
@@ -186,7 +186,7 @@ fn declare_wasm_parameters(
}
}
- next_local
+ Ok(next_local)
}
/// Parse the local variable declarations that precede the function body.
@@ -277,7 +277,25 @@ fn declare_locals(
builder.def_var(local, init);
builder.set_val_label(init, ValueLabel::new(*next_local));
}
- environ.add_state_slot_local(builder, environ.convert_valtype(wasm_type)?, init);
+ environ.add_state_slot_local(
+ builder,
+ environ.convert_valtype(wasm_type)?,
+ |environ, builder| match init {
+ Some(init) => Ok(init),
+ // A non-nullable reference local has no initial value
+ // (validation ensures it's set before it's read), but its
+ // state-slot entry still needs one: the debug API can read
+ // any local's entry, and the GC traces every
+ // GC-reference-typed entry. Use null.
+ None => {
+ let Ref(rt) = wasm_type else {
+ unreachable!("only non-nullable references have no initial value")
+ };
+ let hty = environ.convert_heap_type(rt.heap_type())?;
+ environ.translate_ref_null(builder.cursor(), hty)
+ }
+ },
+ )?;
*next_local += 1;
}
Ok(())
diff --git a/tests/all/debug.rs b/tests/all/debug.rs
index bf670294a2..692dbd1916 100644
--- a/tests/all/debug.rs
+++ b/tests/all/debug.rs
@@ -1869,3 +1869,112 @@ async fn fuel_visible_and_mutable_in_debug_handler() -> wasmtime::Result<()> {
Ok(())
}
+
+#[tokio::test]
+#[cfg_attr(miri, ignore)]
+async fn uninit_non_nullable_ref_local_in_single_step() -> Result<()> {
+ let _ = env_logger::try_init();
+
+ // `$dirty` fills its frame with a garbage pattern so that `$victim`'s
+ // frame, which occupies the same stack space afterwards, starts with
+ // that garbage in it. `$victim`'s non-nullable local must still read as
+ // null, and must not be traced by the GC, before it is first set.
+ //
+ // Single-stepping is enabled by a host call at the start of `$victim`,
+ // not up front: a debug event in `main` between the two calls would run
+ // host code in the stack space `$dirty` used, overwriting the garbage.
+ let dirty_sets = (0..128)
+ .map(|i| format!("(local.set {i} (i64.const 0x0000123400001234))"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let wat = format!(
+ r#"
+ (module
+ (type $s (struct (field i32)))
+ (import "" "enable_single_step" (func $enable_single_step))
+ (func $dirty
+ (local {i64s})
+ {dirty_sets})
+ (func $victim (result i32)
+ (local $r (ref $s))
+ (call $enable_single_step)
+ (local.set $r (struct.new $s (i32.const 42)))
+ (struct.get $s 0 (local.get $r)))
+ (func (export "main") (result i32)
+ (call $dirty)
+ (call $victim)))
+ "#,
+ i64s = "i64 ".repeat(128),
+ );
+
+ let (module, mut store) = get_module_and_store(
+ |config| {
+ config.wasm_gc(true);
+ },
+ &wat,
+ )?;
+
+ let handler = UninitLocalHandler::default();
+ store.set_debug_handler(handler.clone());
+
+ let enable_single_step = Func::wrap(&mut store, |mut caller: Caller<'_, ()>| {
+ caller
+ .edit_breakpoints()
+ .unwrap()
+ .single_step(true)
+ .unwrap();
+ });
+ let instance =
+ Instance::new_async(&mut store, &module, &[Extern::Func(enable_single_step)]).await?;
+ let main = instance.get_typed_func::<(), i32>(&mut store, "main")?;
+ assert_eq!(main.call_async(&mut store, ()).await?, 42);
+
+ // We should have stopped at least once in `$victim` before the
+ // `local.set`, and then seen the local initialized afterwards.
+ assert!(handler.uninit_steps.load(Ordering::Relaxed) > 0);
+ assert!(handler.init_steps.load(Ordering::Relaxed) > 0);
+ return Ok(());
+
+ #[derive(Clone, Default)]
+ struct UninitLocalHandler {
+ uninit_steps: Arc<AtomicUsize>,
+ init_steps: Arc<AtomicUsize>,
+ }
+
+ impl DebugHandler for UninitLocalHandler {
+ type Data = ();
+
+ fn handle(
+ &self,
+ mut store: StoreContextMut<'_, ()>,
+ event: DebugEvent<'_>,
+ ) -> impl Future<Output = ()> + Send {
+ if let DebugEvent::Breakpoint = event {
+ let frame = store.debug_exit_frames().next().unwrap();
+ let (func, _pc) = frame
+ .wasm_function_index_and_pc(&mut store)
+ .unwrap()
+ .unwrap();
+ // Only look at `$victim`, defined function 1.
+ if func.as_u32() == 1 {
+ // A GC here traces the frame's state slot, including the
+ // entry for `$r`, whether or not it's been set yet.
+ store.gc(None).unwrap();
+ let is_set = frame
+ .local(&mut store, 0)
+ .unwrap()
+ .unwrap_any_ref()
+ .is_some();
+ if is_set {
+ self.init_steps.fetch_add(1, Ordering::Relaxed);
+ } else {
+ // Before the `local.set`, the local reads as null.
+ assert_eq!(self.init_steps.load(Ordering::Relaxed), 0);
+ self.uninit_steps.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ async {}
+ }
+ }
+}