Skip to content

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

wizer: Reject mutable reference-typed globals (#11866)

Alex Crichton0492a340f1ba
diff --git a/crates/wizer/src/info.rs b/crates/wizer/src/info.rs
index f0e778de3d..744f666e11 100644
--- a/crates/wizer/src/info.rs
+++ b/crates/wizer/src/info.rs
@@ -52,7 +52,9 @@ pub struct ModuleContext<'a> {
defined_memories_index: Option<u32>,
/// Export names of defined globals injected by the instrumentation pass.
- pub(crate) defined_global_exports: Option<Vec<String>>,
+ ///
+ /// Note that this only tracks defined mutable globals, not all globals.
+ pub(crate) defined_global_exports: Option<Vec<(u32, String)>>,
/// Export names of defined memories injected by the instrumentation pass.
pub(crate) defined_memory_exports: Option<Vec<String>>,
diff --git a/crates/wizer/src/instrument.rs b/crates/wizer/src/instrument.rs
index 2407fe14ae..cc82eed4b6 100644
--- a/crates/wizer/src/instrument.rs
+++ b/crates/wizer/src/instrument.rs
@@ -83,10 +83,13 @@ pub(crate) fn instrument(module: &mut ModuleContext<'_>) -> Vec<u8> {
// Now export all of this module's defined globals, memories,
// and instantiations under well-known names so we can inspect
// them after initialization.
- for (i, (j, _)) in module.defined_globals().enumerate() {
+ for (i, ty) in module.defined_globals() {
+ if !ty.mutable {
+ continue;
+ }
let name = format!("__wizer_global_{i}");
- exports.export(&name, wasm_encoder::ExportKind::Global, j);
- defined_global_exports.push(name);
+ exports.export(&name, wasm_encoder::ExportKind::Global, i);
+ defined_global_exports.push((i, name));
}
for (i, (j, _)) in module.defined_memories().enumerate() {
let name = format!("__wizer_memory_{i}");
diff --git a/crates/wizer/src/lib.rs b/crates/wizer/src/lib.rs
index b978998634..5ba1a29a31 100644
--- a/crates/wizer/src/lib.rs
+++ b/crates/wizer/src/lib.rs
@@ -258,19 +258,8 @@ impl Wizer {
.validate_all(wasm)
.context("wasm validation failed")?;
- // Reject bulk memory stuff that manipulates state we don't
- // snapshot. See the comment inside `wasm_features`.
- let mut wasm = wasm;
- let mut parsers = vec![wasmparser::Parser::new(0)];
- while !parsers.is_empty() {
- let payload = match parsers.last_mut().unwrap().parse(wasm, true)? {
- wasmparser::Chunk::NeedMoreData(_) => unreachable!(),
- wasmparser::Chunk::Parsed { consumed, payload } => {
- wasm = &wasm[consumed..];
- payload
- }
- };
- match payload {
+ for payload in wasmparser::Parser::new(0).parse_all(wasm) {
+ match payload? {
wasmparser::Payload::CodeSectionEntry(code) => {
let mut ops = code.get_operators_reader()?;
while !ops.eof() {
@@ -321,10 +310,27 @@ impl Wizer {
}
}
}
- wasmparser::Payload::End(_) => {
- parsers.pop();
+ wasmparser::Payload::GlobalSection(globals) => {
+ for g in globals {
+ let g = g?.ty;
+ if !g.mutable {
+ continue;
+ }
+ match g.content_type {
+ wasmparser::ValType::I32
+ | wasmparser::ValType::I64
+ | wasmparser::ValType::F32
+ | wasmparser::ValType::F64
+ | wasmparser::ValType::V128 => {}
+ wasmparser::ValType::Ref(_) => {
+ anyhow::bail!(
+ "unsupported mutable global containing a reference type"
+ )
+ }
+ }
+ }
}
- _ => continue,
+ _ => {}
}
}
diff --git a/crates/wizer/src/rewrite.rs b/crates/wizer/src/rewrite.rs
index bf010ce1a5..0566f000f8 100644
--- a/crates/wizer/src/rewrite.rs
+++ b/crates/wizer/src/rewrite.rs
@@ -78,24 +78,44 @@ impl Wizer {
// Encode the initialized global values from the snapshot,
// rather than the original values.
s if s.id == u8::from(SectionId::Global) => {
+ let original_globals = wasmparser::GlobalSectionReader::new(
+ wasmparser::BinaryReader::new(s.data, 0),
+ )
+ .unwrap();
let mut globals = wasm_encoder::GlobalSection::new();
- for ((_, glob_ty), val) in module.defined_globals().zip(snapshot.globals.iter())
- {
- let glob_ty = RoundtripReencoder.global_type(glob_ty).unwrap();
- globals.global(
- glob_ty,
- &match val {
- SnapshotVal::I32(x) => ConstExpr::i32_const(*x),
- SnapshotVal::I64(x) => ConstExpr::i64_const(*x),
- SnapshotVal::F32(x) => {
- ConstExpr::f32_const(wasm_encoder::Ieee32::new(*x))
- }
- SnapshotVal::F64(x) => {
- ConstExpr::f64_const(wasm_encoder::Ieee64::new(*x))
- }
- SnapshotVal::V128(x) => ConstExpr::v128_const(x.cast_signed()),
- },
- );
+ let mut snapshot = snapshot.globals.iter().peekable();
+ for ((i, glob_ty), global) in module.defined_globals().zip(original_globals) {
+ let global = global.unwrap();
+ match snapshot.next_if(|(j, _)| *j == i) {
+ // This is a mutable global and it was present in
+ // the snapshot, so translate the snapshot value to
+ // a constant expression and insert it.
+ Some((_, val)) => {
+ assert!(glob_ty.mutable);
+ let init = match val {
+ SnapshotVal::I32(x) => ConstExpr::i32_const(*x),
+ SnapshotVal::I64(x) => ConstExpr::i64_const(*x),
+ SnapshotVal::F32(x) => {
+ ConstExpr::f32_const(wasm_encoder::Ieee32::new(*x))
+ }
+ SnapshotVal::F64(x) => {
+ ConstExpr::f64_const(wasm_encoder::Ieee64::new(*x))
+ }
+ SnapshotVal::V128(x) => ConstExpr::v128_const(x.cast_signed()),
+ };
+ let glob_ty = RoundtripReencoder.global_type(glob_ty).unwrap();
+ globals.global(glob_ty, &init);
+ }
+
+ // This global isn't mutable so preserve its value
+ // as-is.
+ None => {
+ assert!(!glob_ty.mutable);
+ RoundtripReencoder
+ .parse_global(&mut globals, global)
+ .unwrap();
+ }
+ }
}
encoder.section(&globals);
}
diff --git a/crates/wizer/src/snapshot.rs b/crates/wizer/src/snapshot.rs
index 4dc3ad7a3a..1ac112f624 100644
--- a/crates/wizer/src/snapshot.rs
+++ b/crates/wizer/src/snapshot.rs
@@ -12,7 +12,9 @@ const MAX_DATA_SEGMENTS: usize = 10_000;
/// A "snapshot" of Wasm state from its default value after having been initialized.
pub struct Snapshot {
/// Maps global index to its initialized value.
- pub globals: Vec<SnapshotVal>,
+ ///
+ /// Note that this only tracks defined mutable globals, not all globals.
+ pub globals: Vec<(u32, SnapshotVal)>,
/// A new minimum size for each memory (in units of pages).
pub memory_mins: Vec<u64>,
@@ -100,7 +102,10 @@ pub fn snapshot(module: &ModuleContext<'_>, ctx: &mut dyn InstanceState) -> Snap
}
/// Get the initialized values of all globals.
-fn snapshot_globals(module: &ModuleContext<'_>, ctx: &mut dyn InstanceState) -> Vec<SnapshotVal> {
+fn snapshot_globals(
+ module: &ModuleContext<'_>,
+ ctx: &mut dyn InstanceState,
+) -> Vec<(u32, SnapshotVal)> {
log::debug!("Snapshotting global values");
module
@@ -108,7 +113,7 @@ fn snapshot_globals(module: &ModuleContext<'_>, ctx: &mut dyn InstanceState) ->
.as_ref()
.unwrap()
.iter()
- .map(|name| ctx.global_get(&name))
+ .map(|(i, name)| (*i, ctx.global_get(&name)))
.collect()
}
diff --git a/crates/wizer/tests/all/tests.rs b/crates/wizer/tests/all/tests.rs
index e71346f676..1eb242d69c 100644
--- a/crates/wizer/tests/all/tests.rs
+++ b/crates/wizer/tests/all/tests.rs
@@ -863,3 +863,61 @@ fn relaxed_simd_deterministic() -> Result<()> {
// semantics. We might get 0x4b000002 if we don't.
wizen_and_run_wasm(&[], 0x4b800003, &wasm, wizer)
}
+
+#[test]
+fn reject_mutable_globals_of_reference_types() -> Result<()> {
+ // Non-mutable globals are fine
+ run_wat(
+ &[],
+ 42,
+ r#"
+(module
+ (global funcref (ref.null func))
+ (func (export "wizer.initialize"))
+ (func (export "run") (result i32) i32.const 42)
+)
+ "#,
+ )?;
+
+ // Mutable globals are not fine
+ fails_wizening(
+ r#"
+(module
+ (global (mut funcref) (ref.null func))
+ (func (export "wizer.initialize"))
+ (func (export "run") (result i32) i32.const 42)
+)
+ "#,
+ )?;
+ Ok(())
+}
+
+#[test]
+fn mixture_of_globals() -> Result<()> {
+ let _ = env_logger::try_init();
+ let wasm = wat_to_wasm(
+ r#"
+(module
+ (global $g1 (mut i32) i32.const 1)
+ (global $g2 i32 i32.const 2)
+ (global $g3 (mut i32) i32.const 3)
+ (global $g4 i32 i32.const 4)
+ (func (export "wizer.initialize")
+ (global.set $g1 (i32.const 42))
+ (global.set $g3 (i32.const 43))
+ )
+ (func (export "run") (result i32)
+ global.get $g1
+ global.get $g2
+ global.get $g3
+ global.get $g4
+ i32.add
+ i32.add
+ i32.add
+ )
+)
+ "#,
+ )?;
+ let wizer = get_wizer();
+ wizen_and_run_wasm(&[], 42 + 2 + 43 + 4, &wasm, wizer)
+}