Skip to content

Miscompile: auto-ref of mut self receiver passed to &T parameter corrupts memory #568

Closed

Description

@ehartford

Problem

Passing a mut self: T method receiver (or a receiver-rooted place) as an argument to a function taking &T passes sema, compiles, and miscompiles: the callee reads garbage through the reference and the program crashes (SIGSEGV/SIGBUS, alternating — classic corruption). Likely cause: struct method receivers are already pointer-ABI'd ("Methods pass struct self as pointer", src/Codegen.w:4699), and the auto-ref path takes the address of the pointer slot instead of passing it through, so the callee dereferences a double-indirected value as the struct header.

Minimal repro (20 lines, crashes with exit 139)

type Big { a: Vec[i32], names: Vec[i32] }

fn find_in(big: &Big, x: i32) -> i32:
    for i in 0..big.names.len() as i32:
        if big.names.get(i as i64) == x:
            return i
    -1

fn Big.poke(mut self: Big, x: i32) -> i32:
    let idx = find_in(self, x)
    self.a.push(x)
    idx

fn main:
    var b = Big { a: Vec.new(), names: Vec.new() }
    b.names.push(7)
    b.names.push(9)
    let i1 = b.poke(9)
    let i2 = b.poke(7)
    print(f"i1={i1} i2={i2}")

with build -o repro repro.w && ./repro → exit 139.

How it was found

During the #564 &T migration (phase 5): flipping mir_gen_find_local_by_sym(body: MirBody) to &MirBody made its callers — MirBody.gen_save_generator_fields(mut self: MirBody) passing self — hit this shape, and the stage2 compiler then miscompiled its own generator lowering: spec_ss13_4_generators.w and spec_ss13_4_no_references_across_yield.w crashed with alternating SIGBUS/SIGSEGV while build and fixpoint stayed green. The flips were reverted (mir_gen_find_local_by_sym in MirLower.w, async_snapshot_for_span/async_resume_bb_for_span in AsyncLower.w — the latter two share the receiver-rooted-arg family via async_snapshot_for_span(self.cur_mir_body, ...)); they should be re-applied once this is fixed.

Severity

Worst class: accepted by sema, accepted by codegen, wrong at runtime. Any user method passing self to a &T helper hits it. Related but distinct: #567 (sema accepts &T-for-T method args that codegen rejects loudly) and #566 (sema-accepts/codegen-rejects enum paren-calls). This one fails silently.

Expected

Either auto-ref of a pointer-ABI'd receiver passes the existing pointer through (correct codegen), or sema rejects the shape until it does.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions