Skip to content

A str field read as a function's tail from an owned local is copied without a retain: let v = make(); …; v.text returns a freed str (double free) #3080

Closed

Description

@ehartford
type V { kind: i32, text: str }
fn make(n: i32) -> V: V { kind: n, text: f"p{n}.w" }
fn text_of(n: i32) -> str:
    let value = make(n)
    if value.kind < 0: return ""
    value.text
fn main:
    print(text_of(1))

with run --debug-alloc on main (bdecb62af):

debug-alloc: DOUBLE FREE addr=… size=64 origin=fmt first_drop=drop#struct __drop_struct_309 second_drop=drop#struct __drop_struct_1

The MIR names it (--dump-mir): the tail form lowers to

_5 = copy _2.text;
drop(_2) @ drop#8 scope-exit _2;
_0 = copy+take _5;

while the same read written return value.text lowers to _0 = copy+retain _2.text. materialize_tail_read_of_dropped_local (MirLower.w) reads a projected copy into a temp before the scope's drops so the read does not follow the drop (#1991), but the copy into that temp carries no hold, so a counted type (a str, a CoW List) gains a holder without a retain: the owner's drop frees the buffer and the function returns it.

Found by the src/ ceremony sweep (#3061): .clone() on a str is ceremony under D111, and the 178 removals exposed this at ComptimeEval.capability_arg_str and its siblings (let value = self.extra_value_at(…); …; value.text), which then corrupted a build.w generated-source path (cli-selfhost-build-w-tests, build-w-generated-source). The clones had been hiding the bug.

Fix: the temp read retains as any owning destination does (retain_consumed_copy on the copy operand). Fixture: test/debug_alloc/da_<this>_tail_field_read_retains.w.

Activity

  1. added a commit that references this issue on Nov 8, 2026
  2. ehartford commented on Nov 8, 2026

    @ehartford
    ContributorAuthor

    Fixed on branch fix-ceremony-5 (PR #3079): materialize_tail_read_of_dropped_local now calls retain_consumed_copy on the temp's read, so the tail lowers to _5 = copy+retain _2.text; drop(_2); _0 = copy+take _5. The repro, the fixture da_3080_tail_field_read_retains, and the build.w generated-source case all run clean under the debug allocator; the repro's output also changes from the wrong p2.w p2.w to p1.w p2.w.

  3. ehartford commented on Nov 8, 2026

    @ehartford
    ContributorAuthor

    Fixed in #3079: the tail temp read retains (materialize_tail_read_of_dropped_local → retain_consumed_copy); fixture da_3080_tail_field_read_retains.

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