Skip to content

Returned-view origin tracking depends on declaration order: a view-returning fn defined below its caller ties nothing (§21.1 Rule 6; UAF compiles) #1473

Closed

Description

@ehartford

Spec: §21.1 Rule 6 (returned-view origin tracking), Rule 1 (view liveness), §3.4, §22 ("Verdicts are reproducible"). Declaration order must not change whether a program is accepted.

Repro (installed compiler v0.15.2.1 and stage1 at ba2d5d1):

fn main:
    var v: Vec[i32] = Vec.new()
    v.push(1)
    let r = first(v)
    v.push(2)          // may reallocate: `r` dangles
    print(f"{r}")
fn first(xs: &Vec[i32]) -> &i32: &xs[0]

Actual: with check prints ok (and it compiles and runs).
Expected: the same error the program gets when first is declared before main:

error: cannot mutate `v` while `r` is a live view into it
 --> order3.w:6:5

Root cause (reading, not yet in lldb): a call site ties its result to the arguments through the callee's effect summary — record_call_view_origins (SemaCheck.w) reads sig_param_effect(.., EFF_ESCAPE_VIEW) and sig_param_view_origin, which check_fn_body_with_sig_at writes when the callee's body is checked (SemaCheck.w ~2554-2559). Bodies are checked in declaration order, so a caller that precedes the callee reads an empty summary and records no origin. The same holds for expr_view_depends_on_origin and check_yielded_view_origins. #1196 is the same ordering class for inferred return types.

This is a soundness hole: a use-after-free compiles when the view-returning function is defined below its caller. The same program with an ephemeral struct return (fn Stmt.p(db: &Db) -> Stmt: Stmt { parent: db, .. } below main) accepts drop(db) while the Stmt lives.

Workaround used: modeled-C stage 6 (the facade constructors are rendered after every user declaration) declares the constructors' summaries from the facade's dependency facts before any body is checked (SemaFacade.w apply_facade_dependency_effects), as apply_interface_declared_effects does for D39 interfaces. Ordinary With functions have no workaround.

Found while implementing modeled-C stage 6; not fixed there (it is Sema's body-checking order, its own isolated batch).

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