Skip to content

Element views through an if/match join lose their origin: mutating the Vec while the joined view is live is accepted (use-after-free) #1406

Closed

Description

@ehartford

Spec: §3.8 join rule 3 ("If all reaching expressions are compatible shared references, the result remains a shared reference and carries the union of their possible origins") and §21.1 (a view's origin may not be mutated while the view is live). D27 ruling 3 (a binding names what's there).

fn mkv() -> Vec[str]:
    var v: Vec[str] = Vec.new()
    v.push("a".clone())
    v.push("b".clone())
    v
fn g(c: bool):
    var v = mkv()
    let x = if c: v[0] else: v[1]
    for i in 0..100:
        v.push("q".clone())
    print(x)
fn main:
    g(true)

Actual (installed v0.15.2.1, and a stage1 of dd786a4 + the #1395 branch, which does not touch element joins): compiles; x is a view into v's buffer (MIR: _7 = ref(shared, _2[_6]); _5 = copy _7), the pushes reallocate the buffer, and print(x) reads freed memory — with WITH_DEBUG_ALLOC=1 WITH_DEBUG_ALLOC_SCRIBBLE=1 it prints an empty line instead of a. v[0] = "zzz".clone() in place of the pushes prints zzz through x.

The unjoined spelling is caught: let x = v[0] followed by v.push(...) and a use of x errors with "x views a value stored in v ... mutation would invalidate that view".

Expected: the join's view carries both element origins (v), so the mutation while x is live is the same §21.1 error.

Found while writing the #1395 matrix (element joins are the reference for what a field join should do). Where it probably goes wrong: record_view_binding_from_expr falls back to place_root_sym only for a bare NK_INDEX initializer (SemaCheck.w, the #887 block); the join's collect_expr_view_deps only carries ref-typed origins, so an owned base v under an index arm is never recorded.

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