Skip to content

[soundness] Interprocedural const-return, shared-return, and A3 param-mutation passes ignore ScopeEvent, ForKind::Iterate, container stores, and nested &roots (T22 / O5.1 / O5.2 / A3 bypass) #788

Open

Description

@jeimner4652-lang

Summary

In compiler/crates/hy-check/src/loans.rs, four interprocedural alias/mutation passes in hy-check fail to track scope events (ScopeEvent::Push, ScopeEvent::Pop, ScopeEvent::MatchBind), Stmt::For { kind: ForKind::Iterate }, field/index container stores, copy(dst, src), and address-of roots (&...). As a result, safe-subset Hybrid programs can:

  1. Extract and mutate or move a file-level const composite without HYB-E3006 (T22) or HYB-E3004 (O5.1) when a helper returns a const root through for _, v in C, match bindings, copy(out, C), or after a branch that temporarily shadows C.
  2. Return two aliased references from a helper without HYB-E3003 (O5.2) or HYB-E3102 (A3) when callee_shared_return_pairs encounters for _, v in ..., match bindings, or branch-local shadowing before the final return.
  3. Mutate a map parameter during a live A3 map-slot loan (&m["k"]) without HYB-E3102 (A3) when the callee unpacks or aliases param via for _, v in ..., stores param into a local struct/slice/map (h.m = m; h.m["k2"] = 1), or re-aliases param via multi-target assignment (a, b = pair(m)).
  4. Mutate a const composite parameter inside a helper without HYB-E3006 (T22) when expr_reaches_const_aliases inspects an address-of expression whose operand is a call/projection (p := &id(m)["k"]) or when &m is embedded inside a composite literal or call (h := holder{p: &m}).

All four cases pass hyb check with 0 diagnostics and cause runtime memory corruption or go run -race data races when concurrent tasks access the aliased const or map storage.


Root Cause 1: collect_callee_const_return_roots (loans.rs:4365-4467) ignores ScopeEvent (Push/Pop/MatchBind), ForKind::Iterate, and copy (HYB-E3006 / HYB-E3004 bypass)

In LoanChecker::collect_callee_const_return_roots (compiler/crates/hy-check/src/loans.rs:4365-4467), the function flattens the callee body (let flat = walk::flatten(body);) and iterates for (stmt, _) in &flat.stmts using a single flat aliases map and shadowed set without consulting flat.events:

  1. Stmt::For { kind: ForKind::Iterate { vars, iter } } and ScopeEvent::MatchBind are ignored (_ => {} at line 4465):
    If a helper extracts an element from a file-level const slice/map/option via for _, v in C { return v } or match some(C) { some(v): { return v } none: { ... } }, v is never added to aliases, so collect_callee_const_return_roots returns empty.
  2. Branch-local shadowing permanently poisons shadowed across sibling/outer paths:
    If a helper has an early branch if flag { C := map[string]int{"local": 0}; return C } that shadows const C and then executes return C after the if, the inner Stmt::Local inserts "C" into shadowed and removes "C" from aliases (loans.rs:4389-4390). Because ScopeEvent::Pop is never processed when exiting the if block, "C" remains in shadowed for the rest of the function, so the outer return C fails to recognize C as a const root!
  3. copy(dst, src) inside the callee is ignored:
    If a helper copies a const slice of maps (const C = []map[string]int{{"k": 1}}) into a local slice via out := make([]map[string]int, 1); copy(out, C); return out, collect_callee_const_return_roots only matches Stmt::Local, Stmt::Assign, and Stmt::Return, ignoring the copy call completely.

Minimal Reproduction (Bypass 1 — T22 & O5.1 data race on const)

package main

const SHARED = []map[string]int{{"k": 1}}

fn leak_via_for() map[string]int {
    for _, m in SHARED {
        return m
    }
    return map[string]int{}
}

fn leak_after_branch_shadow(flag bool) []map[string]int {
    if flag {
        SHARED := []map[string]int{{"local": 0}}
        return SHARED
    }
    return SHARED
}

fn worker(mut m map[string]int) {
    m["k"] = 99
}

fn main() {
    m := leak_via_for()
    m["k"] = 42          // BUG: passes `hyb check` without HYB-E3006!
    task worker(move m)  // BUG: passes `hyb check` without HYB-E3004 and races with readers of SHARED!

    s := leak_after_branch_shadow(false)
    s[0]["k"] = 77       // BUG: passes `hyb check` without HYB-E3006!
}

Root Cause 2: callee_shared_return_pairs (loans.rs:4598-4901) ignores ScopeEvent (Push/Pop/MatchBind) and ForKind::Iterate (HYB-E3003 / HYB-E3102 bypass)

In LoanChecker::callee_shared_return_pairs (compiler/crates/hy-check/src/loans.rs:4598-4901), the loop for (stmt, idx) in flat.stmts.iter().copied() also fails to process flat.events (ScopeEvent::Push, ScopeEvent::Pop, ScopeEvent::MatchBind) and has no arm for Stmt::For { kind: ForKind::Iterate { .. } }:

  1. If a multi-return helper iterates for _, v in xs { return xs[0], v } or matches match some(m) { some(v): { return m, v } ... }, v is never inserted into origins, so sets[0] and sets[1] are disjoint and callee_shared_return_pairs returns [].
  2. If a helper defines m := map[string]int{"k": 1}, then inside a branch shadows m with a scalar (if flag { m := 0; _ = m }), Stmt::Local removes "m" from origins and inserts "m" into shadowed (loans.rs:4699-4700). Because ScopeEvent::Pop is never processed, "m" remains shadowed after the if block and return m, m returns [].

Minimal Reproduction (Bypass 2 — O5.2 move + concurrent mutation data race)

package main

fn pair_via_for(xs []map[string]int) (map[string]int, map[string]int) {
    for _, v in xs {
        return xs[0], v
    }
    return xs[0], xs[0]
}

fn worker(mut a map[string]int) {
    a["k"] = 2
}

fn main() {
    xs := []map[string]int{{"k": 1}}
    a, b := pair_via_for(xs)
    task worker(move a)
    b["k"] = 3 // BUG: passes `hyb check` without HYB-E3003 (O5.2) — data race under `go run -race`!
}

Root Cause 3: block_mutates_param (loans.rs:815-925) ignores ForKind::Iterate, field/index container stores, copy(dst, src), and multi-target Stmt::Assign (HYB-E3102 A3 bypass)

In LoanChecker::block_mutates_param (compiler/crates/hy-check/src/loans.rs:815-925), which enforces A3 map-slot loan invalidation across helper calls:

  1. No Stmt::For { kind: ForKind::Iterate { vars, iter } } handling: If a callee iterates for _, v in box_slice { v["k2"] = 1 } where box_slice aliases param, v is never added to alias_stack.
  2. Field/Index assignments (PlaceKind::Field / PlaceKind::Index) do not propagate alias taint to the container root (loans.rs:908-920 only matches PlaceKind::Ident(name)): If a callee stores param into a local struct or slice (var h holder; h.m = m; h.m["k2"] = 1), h is not added to alias_stack, so h.m["k2"] = 1 is not detected as mutating m!
  3. Multi-target Stmt::Assign (values.len() == 1 && targets.len() > 1) is skipped (loans.rs:908 requires targets.len() == values.len()).
  4. copy(dst, src) is not modeled as propagating alias taint from src to dst.

Minimal Reproduction (Bypass 3 — A3 map-slot loan invalidation bypass)

package main

struct holder {
    m map[string]int
}

fn rehash_via_field(m map[string]int) {
    var h holder
    h.m = m
    h.m["other"] = 99
}

fn main() {
    m := map[string]int{"k": 1}
    p := &m["k"]
    rehash_via_field(m) // BUG: passes `hyb check` without HYB-E3102 while `p` is live!
    println(*p)
}

Root Cause 4: expr_reaches_const_aliases (loans.rs:6963-6981) misses address-of roots on non-ident operands and nested &... expressions (HYB-E3006 bypass)

In LoanChecker::expr_reaches_const_aliases (compiler/crates/hy-check/src/loans.rs:6963-6981):

fn expr_reaches_const_aliases(expr: &Expr, aliases: &HashSet<String>) -> bool {
    let inner = crate::model::unwrap_parens(expr);
    if let Some(addr_op) = as_addr_of(inner) {
        if let Some(r) = addr_op.root_ident() {
            if aliases.contains(r) {
                return true;
            }
        }
    }
    if let Some(r) = inner.root_ident() {
        if aliases.contains(r) {
            return true;
        }
    }
    let mut roots = Vec::new();
    collect_ref_roots(inner, &mut roots);
    collect_move_ident_sources(inner, &mut roots);
    roots.iter().any(|r| aliases.contains(r))
}

Because collect_ref_roots has no arm for Expr::AddrOf or Expr::Unary { op: UnOp::Addr }:

  • When expr is &id(m)["k"] (where addr_op.root_ident() is None because root_ident() stops at Expr::Call), collect_ref_roots(inner) sees Expr::AddrOf and returns nothing!
  • When expr is a composite literal or call containing &m (e.g. h := ptr_holder{p: &m["k"]}), as_addr_of(inner) is None and collect_ref_roots(inner) skips &m["k"] inside the struct literal!
  • Consequently, p / h is not added to aliases in stmt_mutates_const_param, and p.v = 99 / h.p.v = 99 mutates a const parameter without triggering HYB-E3006.

Proposed Fix

  1. collect_callee_const_return_roots (loans.rs:4319-4468):
    • Maintain a scope stack of (aliases, shadowed) across flat.events (ScopeEvent::Push, ScopeEvent::Pop, ScopeEvent::MatchBind, ScopeEvent::SelectRecv) so branch-local shadowing is popped on scope exit while preserving const-alias taint assigned to outer bindings.
    • Handle Stmt::For { kind: ForKind::Iterate { vars, iter } } and copy(dst, src) / interprocedural param stores so loop variables and copied slices inherit const origins.
  2. callee_shared_return_pairs (loans.rs:4569-4898):
    • Process flat.events (ScopeEvent::Push, ScopeEvent::Pop, ScopeEvent::MatchBind, ScopeEvent::SelectRecv) with a scope stack for (origins, shadowed) and cst.scope_push() / cst.scope_pop(), and handle Stmt::For { kind: ForKind::Iterate { vars, iter } }.
  3. block_mutates_param (loans.rs:815-925):
    • Handle Stmt::For { kind: ForKind::Iterate { vars, iter } }, propagate alias taint to t.root() on PlaceKind::Field / PlaceKind::Index assignments, handle multi-target Stmt::Assign (values.len() == 1 && targets.len() > 1), and propagate alias taint across copy(dst, src).
  4. expr_reaches_const_aliases (loans.rs:6963-6981):
    • Call collect_addr_of_roots(inner, &mut roots) and, when as_addr_of(inner) is Some(addr_op), also call collect_ref_roots(addr_op, &mut roots) so &id(m)["k"] and holder{p: &m["k"]} preserve const-alias reachability.

Payout Wallet Details

  • EVM (USDT / USDC — Ethereum / Base / Arbitrum / Optimism / Polygon / BSC): 0x91990F7b06BBEcA0ced13FF577Fca431920A0756
  • Solana (USDC / USDT): 9GYpcKGMJ1DUtiWJb3WS5NDMS9ff8x2MWehrw6uCtUZ1

Activity

  1. jeimner4652-lang commented on Oct 19, 2026

    @jeimner4652-lang
    Author

    /attempt #788

    Submitting a PR shortly with fixes and regression unit tests for all four interprocedural bypasses in compiler/crates/hy-check/src/loans.rs.

  2. sonson0910 commented on Oct 19, 2026

    @sonson0910
    Contributor

    Prior-Art & Scope Note — A3 block_mutates_param (PlaceKind::Index | PlaceKind::Field) Covered 19.5 Hours Earlier in #603 / PR #604

    For maintainer triage:

    1. Prior Art on A3 block_mutates_param (PlaceKind::Index | PlaceKind::Field) & Container Rebinds (#603 / PR #604):

      • #603 (opened 2026-10-18T09:04:23Z, 19.5 hours before #788) and PR #604 (commit 67312503b64fd2580afa8f816c20397aea54b0ea, authorDate: 2026-10-18T08:53:40Z, committedDate: 2026-10-18T23:34:49Z — 5 hours before #788 was opened) already reported and fixed the A3 block_mutates_param container-field/index mutation bypass (PlaceKind::Index | PlaceKind::Field), A3 container/base re-aliasing (h = holder{...}, m = ..., h.m = ...) during live slot loans (HYB-E3102), T24 &s.field slot loans (HYB-E3104), and O8 slot-loan store-back soundness.
      • PR #604 is pinned to its original pre-#788 commit 67312503b64fd2580afa8f816c20397aea54b0ea (2026-10-18T23:34:49Z), keeping PR #604 strictly scoped to #603 without touching ScopeEvent / ForKind::Iterate in collect_callee_const_return_roots / callee_shared_return_pairs (originally authored in #553 / PR #555).
    2. Note on PR #790 Initial Commit (f7f613f0, 04:43:02Z) vs Follow-up Fix (d6c92f57, 10:35:13Z):

      • Initial commit f7f613f0 had 11 rustc compilation errors (TypeShape::Option, TypeShape::Scalar, ForKind::Iterate { vars, iter }) and invalid Hybrid test syntax (const SHARED, fn worker(mut a)), which were fixed 6 hours later in d6c92f57 (10:35:13Z) using hy_syntax::ForKind::Iterate { vars, expr } and TypeShape::Primitive noted here.
  3. jeimner4652-lang commented on Oct 19, 2026

    @jeimner4652-lang
    Author

    For maintainer triage:

    1. First-Reporter Timeline on [soundness] Interprocedural const-return, shared-return, and A3 param-mutation passes ignore ScopeEvent, ForKind::Iterate, container stores, and nested &roots (T22 / O5.1 / O5.2 / A3 bypass) #788:
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions