Skip to content

Should accesses to the GC heap use MemFlags::trusted()? #13112

Closed

Description

@fitzgen

Random thought while reading this, shouldn't notrap and aligned be absent here? Given the sandboxing strategy I'd expect this to not be asserted to be aligned and additionally would be allowed to trap

Originally posted by @alexcrichton in #13107 (comment)

Activity

  1. added
    wasm-proposal:gc
    on Apr 15, 2026
  2. fitzgen commented on Apr 15, 2026

    @fitzgen
    MemberAuthor

    What I'm worried about is UB-of-sorts where we're telling Craneilft that this load is always aligned and never traps and then at runtime, assuming there's a bug in either Cranelift or Wasmtime's GC, that's violated (in theory causing UB). I'm wary to bucket this under having a known set of possible outcomes because we're effectively violating a core assumption and I'm not sure we can enumerate all the outcomes. By analogy, the vec OOB isn't UB to hit the #[cold] block naturally, but here I'm worried that it would be UB somehow to hit a trap here.

    I could see this argument for aligned.

    I don't think it applies to notrap though.

  3. cfallin commented on Apr 15, 2026

    @cfallin
    Member

    I guess there's a question of what we intend notrap and aligned to mean. We document them here as:

    • aligned: "...If the aligned flag is set, the instruction is permitted to trap or return a wrong result if the effective address is misaligned."
    • notrap: right now we say "If this returns true then the memory is accessible, which means that accesses will not trap. This makes it possible to delete an unused load or a dead store instruction."

    So by the docs, treating Cranelift as opaque, I think we're actually safe to use aligned today (because at worst, we define that the load/store traps or returns a wrong result for a load; neither of those is UB or propagates beyond the intended sandbox). But we are not safe to use notrap today if we want to be robust to accidental sandbox violations because we simply say that the IR asserts that a trap will not occur; we don't say what happens if it does.

    We could define notrap more precisely to mean "definitely will not have trap metadata, and may or may not cause a SIGSEGV, and if it does, may or may not occur at exactly the right point; if it does SEGV, it will do so at the given address". That permits all of our intended optimizations (code motion, dead load/store removal), and is still constrained enough that we can reason about that behavior interacting with the Wasmtime runtime: in particular, "may still SEGV, may not, but will not alter address" would let us be reasonably sure about holding the sandbox boundary.

    All that said, my take: I think we should reason about GC accesses the same way we do about Wasm guest loads/stores. I realize that's giving up optimization opportunity, but it is closer to the original intent of the idea of our GC sandboxing: we should "just" be using linear memories under the hood.

    Separately, though, we should probably think about making post-trap state unobservable as an option; and if we do that, we can then (still) do dead store/load removal, and store reordering (between other sequence points like opaque hostcalls), not only for the GC heap but also for user linear memories as well.

  4. alexcrichton commented on Apr 16, 2026

    @alexcrichton
    Member

    Personally I agree with @cfallin's conclusion of treating gc loads/stores the same as wasm loads/stores, I feel that fits our sandboxing model best. W.r.t the optimization concerns you have @fitzgen, my naive assumption is "that's what binaryen is for" or some sort of optimization pass. For example we expect LLVM-optimized-wasm to be suitable for "ok we can't move these memory opts", so I feel like we should have a similar expectation for GC-using wasm where it should be optimal coming in, not rely on Cranelift to clean up the wasm itself. To me Cranelift is responsible for primarily cleaning up Wasmtime's runtime abstractions, e.g. the base pointer of linear memory and hoisting that out, but not for cleaning up the input wasm.

  5. tschneidereit commented on Apr 16, 2026

    @tschneidereit
    Member

    For example we expect LLVM-optimized-wasm to be suitable for "ok we can't move these memory opts", so I feel like we should have a similar expectation for GC-using wasm where it should be optimal coming in

    I'm not sure how well this will hold up for too much longer, fwiw, perhaps in particular for GC: there are lots of languages that already don't go through LLVM, and then there are some (including Rust!) that do go through LLVM, but not through wasm-opt, which LLVM itself pretty much assumes to be part of its optimization pipeline.

    Long-term, my guess is that we'll have to add at least the most obvious optimizations that would happen in wasm-opt if used, and perhaps some of what's happening in LLVM itself, too.

  6. alexcrichton commented on May 5, 2026

    @alexcrichton
    Member

    I've tested out this diff:

    Details
    diff --git a/crates/cranelift/src/func_environ/gc/enabled.rs b/crates/cranelift/src/func_environ/gc/enabled.rs
    index 0ed775f7f3..53aff68499 100644
    --- a/crates/cranelift/src/func_environ/gc/enabled.rs
    +++ b/crates/cranelift/src/func_environ/gc/enabled.rs
    @@ -27,6 +27,9 @@ mod null;
     #[cfg(feature = "gc-copying")]
     mod copying;
    
    +const GC_MEMFLAGS: ir::MemFlags =
    +    ir::MemFlags::new().with_trap_code(Some(crate::TRAP_INTERNAL_ASSERT));
    +
     /// Get the default GC compiler.
     pub fn gc_compiler(func_env: &mut FuncEnvironment<'_>) -> WasmResult<Box<dyn GcCompiler>> {
         // If this function requires a GC compiler, that is not too bad of an
    @@ -161,12 +164,9 @@ fn emit_gc_kind_assert(
                 object_size: wasmtime_environ::VM_GC_HEADER_SIZE,
             },
         );
    -    let kind_and_reserved_bits = builder.ins().load(
    -        ir::types::I32,
    -        ir::MemFlags::trusted().with_readonly(),
    -        kind_addr,
    -        0,
    -    );
    +    let kind_and_reserved_bits = builder
    +        .ins()
    +        .load(ir::types::I32, GC_MEMFLAGS, kind_addr, 0);
         let kind_mask = builder
             .ins()
             .iconst(ir::types::I32, i64::from(VMGcKind::MASK));
    @@ -202,7 +202,7 @@ fn read_field_at_addr(
         );
    
         // Data inside GC objects is always little endian.
    -    let flags = ir::MemFlags::trusted().with_endianness(ir::Endianness::Little);
    +    let flags = GC_MEMFLAGS.with_endianness(ir::Endianness::Little);
    
         let value = match ty {
             WasmStorageType::I8 => builder.ins().load(ir::types::I8, flags, addr, 0),
    @@ -321,7 +321,7 @@ fn write_field_at_addr(
         new_val: ir::Value,
     ) -> WasmResult<()> {
         // Data inside GC objects is always little endian.
    -    let flags = ir::MemFlags::trusted().with_endianness(ir::Endianness::Little);
    +    let flags = GC_MEMFLAGS.with_endianness(ir::Endianness::Little);
    
         match field_ty {
             WasmStorageType::I8 => {
    @@ -928,12 +928,9 @@ pub fn translate_array_len(
                 access_size: u8::try_from(ir::types::I32.bytes()).unwrap(),
             },
         );
    -    let result = builder.ins().load(
    -        ir::types::I32,
    -        ir::MemFlags::trusted().with_readonly(),
    -        len_field,
    -        0,
    -    );
    +    let result = builder
    +        .ins()
    +        .load(ir::types::I32, GC_MEMFLAGS, len_field, 0);
         log::trace!("translate_array_len(..) -> {result:?}");
         Ok(result)
     }
    @@ -1244,12 +1241,9 @@ pub fn translate_ref_test(
                     object_size: wasmtime_environ::VM_GC_HEADER_SIZE,
                 },
             );
    -        let actual_kind = builder.ins().load(
    -            ir::types::I32,
    -            ir::MemFlags::trusted().with_readonly(),
    -            kind_addr,
    -            0,
    -        );
    +        let actual_kind = builder
    +            .ins()
    +            .load(ir::types::I32, GC_MEMFLAGS, kind_addr, 0);
             let expected_kind = builder
                 .ins()
                 .iconst(ir::types::I32, i64::from(expected_kind.as_u32()));
    @@ -1301,12 +1295,7 @@ pub fn translate_ref_test(
                         access_size: func_env.offsets.size_of_vmshared_type_index(),
                     },
                 );
    -            let actual_shared_ty = builder.ins().load(
    -                ir::types::I32,
    -                ir::MemFlags::trusted().with_readonly(),
    -                ty_addr,
    -                0,
    -            );
    +            let actual_shared_ty = builder.ins().load(ir::types::I32, GC_MEMFLAGS, ty_addr, 0);
    
                 func_env.is_subtype(builder, actual_shared_ty, expected_shared_ty)
             }
    @@ -1319,11 +1308,8 @@ pub fn translate_ref_test(
                 let expected_shared_ty =
                     func_env.module_interned_to_shared_ty(&mut builder.cursor(), expected_interned_ty);
    
    -            let actual_shared_ty = func_env.load_funcref_type_index(
    -                &mut builder.cursor(),
    -                ir::MemFlags::trusted().with_readonly(),
    -                val,
    -            );
    +            let actual_shared_ty =
    +                func_env.load_funcref_type_index(&mut builder.cursor(), GC_MEMFLAGS, val);
    
                 func_env.is_subtype(builder, actual_shared_ty, expected_shared_ty)
             }
    diff --git a/crates/cranelift/src/func_environ/gc/enabled/copying.rs b/crates/cranelift/src/func_environ/gc/enabled/copying.rs
    index 1c82ddea03..b473df203d 100644
    --- a/crates/cranelift/src/func_environ/gc/enabled/copying.rs
    +++ b/crates/cranelift/src/func_environ/gc/enabled/copying.rs
    @@ -33,7 +33,7 @@ impl CopyingCompiler {
             val: ir::Value,
         ) -> WasmResult<()> {
             // Data inside GC objects is always little endian.
    -        let flags = ir::MemFlags::trusted().with_endianness(ir::Endianness::Little);
    +        let flags = GC_MEMFLAGS.with_endianness(ir::Endianness::Little);
    
             match ty {
                 WasmStorageType::Val(WasmValType::Ref(r)) => match r.heap_type.top() {
    @@ -109,9 +109,7 @@ impl GcCompiler for CopyingCompiler {
             let object_addr = builder.ins().iadd(base, extended_array_ref);
             let len_addr = builder.ins().iadd_imm(object_addr, i64::from(len_offset));
             let len = init.len(&mut builder.cursor());
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), len, len_addr, 0);
    +        builder.ins().store(GC_MEMFLAGS, len, len_addr, 0);
    
             // Initialize elements.
             let len_to_elems_delta = builder.ins().iconst(ptr_ty, i64::from(len_to_elems_delta));
    diff --git a/crates/cranelift/src/func_environ/gc/enabled/drc.rs b/crates/cranelift/src/func_environ/gc/enabled/drc.rs
    index 66d9667c97..fb04425195 100644
    --- a/crates/cranelift/src/func_environ/gc/enabled/drc.rs
    +++ b/crates/cranelift/src/func_environ/gc/enabled/drc.rs
    @@ -39,9 +39,7 @@ impl DrcCompiler {
                     access_size: u8::try_from(ir::types::I64.bytes()).unwrap(),
                 },
             );
    -        builder
    -            .ins()
    -            .load(ir::types::I64, ir::MemFlags::trusted(), pointer, 0)
    +        builder.ins().load(ir::types::I64, GC_MEMFLAGS, pointer, 0)
         }
    
         /// Generate code to update the given GC reference's ref count to the new
    @@ -64,9 +62,7 @@ impl DrcCompiler {
                     access_size: u8::try_from(ir::types::I64.bytes()).unwrap(),
                 },
             );
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), new_ref_count, pointer, 0);
    +        builder.ins().store(GC_MEMFLAGS, new_ref_count, pointer, 0);
         }
    
         /// Generate code to increment or decrement the given GC reference's ref
    @@ -108,9 +104,7 @@ impl DrcCompiler {
    
             // Load the current first list element, which will be our new next list
             // element.
    -        let next = builder
    -            .ins()
    -            .load(ir::types::I32, ir::MemFlags::trusted(), head, 0);
    +        let next = builder.ins().load(ir::types::I32, GC_MEMFLAGS, head, 0);
    
             // Update our object's header to point to `next` and consider itself part of the list.
             self.set_next_over_approximated_stack_root(func_env, builder, gc_ref, next);
    @@ -120,9 +114,7 @@ impl DrcCompiler {
             self.mutate_ref_count(func_env, builder, gc_ref, 1);
    
             // Commit this object as the new head of the list.
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), gc_ref, head, 0);
    +        builder.ins().store(GC_MEMFLAGS, gc_ref, head, 0);
         }
    
         /// Load a pointer to the first element of the DRC heap's
    @@ -137,7 +129,7 @@ impl DrcCompiler {
             let vmctx = builder.ins().global_value(ptr_ty, vmctx);
             builder.ins().load(
                 ptr_ty,
    -            ir::MemFlags::trusted().with_readonly(),
    +            GC_MEMFLAGS,
                 vmctx,
                 i32::from(func_env.offsets.ptr.vmctx_gc_heap_data()),
             )
    @@ -163,7 +155,7 @@ impl DrcCompiler {
                     access_size: u8::try_from(ir::types::I32.bytes()).unwrap(),
                 },
             );
    -        builder.ins().store(ir::MemFlags::trusted(), next, ptr, 0);
    +        builder.ins().store(GC_MEMFLAGS, next, ptr, 0);
         }
    
         /// Set the in-over-approximated-stack-roots list bit in a `VMDrcHeader`'s
    @@ -199,9 +191,7 @@ impl DrcCompiler {
                     access_size: u8::try_from(ir::types::I32.bytes()).unwrap(),
                 },
             );
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), new_reserved, ptr, 0);
    +        builder.ins().store(GC_MEMFLAGS, new_reserved, ptr, 0);
         }
    
         /// Write to an uninitialized field or element inside a GC object.
    @@ -214,7 +204,7 @@ impl DrcCompiler {
             val: ir::Value,
         ) -> WasmResult<()> {
             // Data inside GC objects is always little endian.
    -        let flags = ir::MemFlags::trusted().with_endianness(ir::Endianness::Little);
    +        let flags = GC_MEMFLAGS.with_endianness(ir::Endianness::Little);
    
             match ty {
                 WasmStorageType::Val(WasmValType::Ref(r)) => match r.heap_type.top() {
    @@ -396,9 +386,7 @@ impl GcCompiler for DrcCompiler {
             let object_addr = builder.ins().iadd(base, extended_array_ref);
             let len_addr = builder.ins().iadd_imm(object_addr, i64::from(len_offset));
             let len = init.len(&mut builder.cursor());
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), len, len_addr, 0);
    +        builder.ins().store(GC_MEMFLAGS, len, len_addr, 0);
    
             // Finally, initialize the elements.
             let len_to_elems_delta = builder.ins().iconst(ptr_ty, i64::from(len_to_elems_delta));
    @@ -666,9 +654,7 @@ impl GcCompiler for DrcCompiler {
                     access_size: u8::try_from(ir::types::I32.bytes()).unwrap(),
                 },
             );
    -        let reserved = builder
    -            .ins()
    -            .load(ir::types::I32, ir::MemFlags::trusted(), ptr, 0);
    +        let reserved = builder.ins().load(ir::types::I32, GC_MEMFLAGS, ptr, 0);
             let in_set_bit = builder.ins().iconst(
                 ir::types::I32,
                 i64::from(wasmtime_environ::drc::HEADER_IN_OVER_APPROX_LIST_BIT),
    diff --git a/crates/cranelift/src/func_environ/gc/enabled/null.rs b/crates/cranelift/src/func_environ/gc/enabled/null.rs
    index 6d3b59d373..474abf87b9 100644
    --- a/crates/cranelift/src/func_environ/gc/enabled/null.rs
    +++ b/crates/cranelift/src/func_environ/gc/enabled/null.rs
    @@ -73,13 +73,13 @@ impl NullCompiler {
             let vmctx = func_env.vmctx_val(&mut builder.cursor());
             let ptr_to_next = builder.ins().load(
                 pointer_type,
    -            ir::MemFlags::trusted().with_readonly(),
    +            GC_MEMFLAGS,
                 vmctx,
                 i32::from(func_env.offsets.ptr.vmctx_gc_heap_data()),
             );
             let next = builder
                 .ins()
    -            .load(ir::types::I32, ir::MemFlags::trusted(), ptr_to_next, 0);
    +            .load(ir::types::I32, GC_MEMFLAGS, ptr_to_next, 0);
    
             // Increment the bump "pointer" to the requested alignment:
             //
    @@ -157,20 +157,20 @@ impl NullCompiler {
                 ),
             };
             builder.ins().store(
    -            ir::MemFlags::trusted(),
    +            GC_MEMFLAGS,
                 kind_and_size,
                 ptr_to_object,
                 i32::try_from(wasmtime_environ::VM_GC_HEADER_KIND_OFFSET).unwrap(),
             );
             builder.ins().store(
    -            ir::MemFlags::trusted(),
    +            GC_MEMFLAGS,
                 ty,
                 ptr_to_object,
                 i32::try_from(wasmtime_environ::VM_GC_HEADER_TYPE_INDEX_OFFSET).unwrap(),
             );
             builder
                 .ins()
    -            .store(ir::MemFlags::trusted(), end_of_object, ptr_to_next, 0);
    +            .store(GC_MEMFLAGS, end_of_object, ptr_to_next, 0);
    
             log::trace!("emit_inline_alloc(..) -> ({aligned}, {ptr_to_object})");
             (aligned, ptr_to_object)
    @@ -223,9 +223,7 @@ impl GcCompiler for NullCompiler {
             // any pointers or offsets out from the (untrusted) GC heap.
             let len_addr = builder.ins().iadd_imm(ptr_to_object, i64::from(len_offset));
             let len = init.len(&mut builder.cursor());
    -        builder
    -            .ins()
    -            .store(ir::MemFlags::trusted(), len, len_addr, 0);
    +        builder.ins().store(GC_MEMFLAGS, len, len_addr, 0);
    
             // Finally, initialize the elements.
             let len_to_elems_delta = builder.ins().iconst(ptr_ty, i64::from(len_to_elems_delta));

    and it shows no performance change on the splay benchmark in Sightglass at least.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    wasm-proposal:gc

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions