Skip to content

Soundness: struct-literal field init copies a non-Copy (Drop) value instead of moving it → double-free #605

Closed

Description

@ehartford

Summary

Placing an existing non-Copy (Drop-implementing) value into a struct-literal field bitwise-copies it instead of moving it: the source binding stays usable (no "use of moved value"), and both the source and the field are dropped. For a type that owns a resource, this is a double-free (and a use-after-move the checker doesn't catch).

Repro (double-free, concrete)

extern fn malloc(n: u64) -> *mut u8
extern fn free(p: *mut u8)
type Owned { handle: *mut u8 }
impl Drop for Owned:
    fn drop(move self: Self):
        print_i32(7)
        unsafe { free(self.handle) }
type Box2 { inner: Owned }
fn main:
    let o = Owned { handle: unsafe { malloc(8) } }
    let b = Box2 { inner: o }      // copies o into b.inner instead of moving
    print_i32(1)

Output: 1, 7, 7 — drop (and free on the same pointer) runs twice.

Nature (characterized)

type W { id: i32 }
impl Drop for W:
    fn drop(move self: Self): print_i32(self.id)
type Holder { w: W }
fn main:
    let tmp = W { id: 5 }
    let h = Holder { w: tmp }   // <-- copies, does not move/consume tmp
    print_i32(tmp.id)           // compiles & prints 5 — tmp still usable

Output 5, 5, 5: tmp.id reads fine after the "move" (so tmp was not consumed), then both tmp and h.w drop. A non-Copy value got duplicated.

Scope (what triggers / what doesn't)

  • Triggers: placing an existing non-Copy value (a local binding, or a function-call result) into a struct-literal field — Struct { f: local }, Struct { f: make() }.
  • Does NOT trigger (correct, single drop):
    • direct nested literal in place: Holder { w: W { id: 5 } } → one drop;
    • move function arguments: take(make(5)) consumes correctly (verified);
    • constructor returning a wrapper whose field is a Copy raw pointer (Owned { handle: p } where handle: *mut u8) → single drop through construct→return→scope-exit.

Severity / impact

Double-free + undetected use-after-move on any Drop type stored into a struct field from a binding or call. Directly blocks #357 (proven-ownership Drop wrappers): a generated owning wrapper is correct in simple scopes, but double-frees the moment a user stores it in a struct field — the common case — so owning wrappers are not actually safe until this is fixed. It is a prerequisite for #357's positive path to deliver its safety guarantee.

Likely area

Struct-literal field-initialization lowering / move analysis: a non-Copy field initializer that is a place or call result must be treated as a move (consume the source, clear its drop flag), the same way move parameters and direct let bindings already are. Found via the #357 ownership matrix (spell-and-run before building).

Activity

  1. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Blast radius mapped — broader than struct-literal field init (two distinct root causes)

    Before fixing, I enumerated every by-value construction site (spell-and-run, reading actual outputs — an earlier grep heuristic gave false signals, so these are all confirmed by output). The bug is not struct-specific.

    Root cause 1 (this issue): aggregate construction copies a named non-Copy value instead of moving it

    For Struct { f: x }, [x], (x, …), EnumVariant(x) where x is an existing binding/call result of a non-Copy (Drop) type, the initializer is bitwise-copied, not moved: the source stays usable (use-after-move is not detected) and its drop flag is not cleared.

    Construction site Moves correctly?
    let y = x / move param / plain param ✅ moves (use-after caught)
    Some(x) / Ok(x) (Option/Result ctor call) ✅ moves (use-after caught)
    struct field Struct { f: x } ❌ copies (use-after not caught)
    array literal [x] ❌ copies
    tuple (x, …) ❌ copies
    user enum variant E.Payload(x) ❌ copies

    Downstream severity depends on whether the aggregate drops its contents (see root cause 2): struct drops its field → this becomes a DOUBLE-FREE (confirmed: free() twice on one pointer). Array/tuple/enum don't drop contents, so there it's a leak + an unsound live duplicate of a non-Copy value.

    Likely area: aggregate/composite construction lowering must treat a non-Copy field/element/payload initializer that is a place or call result as a move (consume source, clear drop flag) — the way let bindings and move/Some(...) already do.

    Root cause 2: filed separately as the Drop-propagation leak (see linked issue)

    Option, Vec, array, tuple, and user enums do not run Drop on their contained values → resource leak. (Vec has no element-dropping Drop impl at all; Option<W>/Vec<W> in a deterministic scope drop their W zero times.)

    Why both gate #357

    An owning Drop wrapper is safe only as a bare local. Stored in a struct → double-free (root cause 1). Stored in Option/Vec/array/tuple/enum → leak (root cause 2). Those are the normal homes for a resource handle, so #357's wrappers are broadly unsafe until both are fixed. The fix for this issue must close every copy-instead-of-move site (struct/array/tuple/enum), not just struct-field — one pass, with a construction-site test matrix.

  2. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Landed: struct-literal double-free fixed (Drop-gated), commit 80f8e2e on main

    A non-Copy value placed in a struct-literal field was bitwise-copied; for a Drop value that meant a double-free (confirmed: free() twice on one pointer). Fixed:

    • SemaCheck.check_struct_literal: mark a whole non-Copy identifier field value moved (use-after-move detection).
    • MirLower struct-literal lowering: consume_moved_operand on the field operand (drop-once), explicit + defaulted fields.
    • Gated on the field value's type having a Drop impl (type_has_drop_impl). Non-Drop value types keep copying — the compiler/stdlib rely on it to share a value across constructions (e.g. lib/std/build.w shares one fs_outputs into both ToolFs and ProcessRunner); harmless without a destructor. Strict-move for all non-Copy would require migrating that sharing to explicit clones — a separate project.
    • One compiler site relied on the copy (CCodegen used mir_mod after moving it into the codegen struct) — migrated.

    Verified: fixpoint holds; behavior 702, compile-error 614, spec 178. Tests: behav_drop_move_into_struct_field, err_use_after_move_into_struct_field.

    Finding: array/tuple/enum need #605 + #606 together

    So #605-move alone for array/tuple/enum doesn't help (moved-in value then dropped nowhere — still a leak), and #606-drop alone would turn those leaks into double-frees. They must land together: consume the source at the array/tuple/enum lowering sites AND extend the auto-drop dispatcher to drop those contents.

    Remaining

  3. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Tuple/array/enum element-drop needs per-element move-state tracking (attempted, reverted)

    Piloted tuple #606 (element drop) + #605 (move into tuple), Drop-gated. It fixed the literal-tuple leak and built + held fixpoint, but regressed the channel tests with a double-free (panic: invalid free):

    let (tx, rx) = channel() returns a tuple of (Sender, Receiver) — both Drop. The destructure moves the elements out to tx/rx, which then drop individually. My unconditional tuple drop-glue dropped them again → double-free.

    Why this is harder than the struct case

    Structs already track per-field consumption (drop_consumed_field, checked in mir_emit_drop_fields_ptr), so partial moves out of a struct don't double-drop. Tuples (and arrays, and enum payloads) have no per-element drop-state, so enabling element-drop without it double-frees on destructure / partial move. Enum is worse: drop must be discriminant-aware (only the active variant's payload) and respect moves of that payload.

    So tuple/array/enum #606 is not a bounded pilot — it requires adding per-element (and per-variant) drop-state tracking to the move analysis + drop glue. Reverted the tuple attempt; tree is back to the struct-fix baseline (channels green).

    Status

    • struct double-free: fixed and shipped (the confirmed, severe bug, and CoreFoundation's reference-counted type family: model it as a D51 convention profile #357's primary blocker — owning wrapper stored in a struct).
    • tuple/array/enum element-drop: needs per-element/per-variant drop-state — a substantial drop-system extension, not a repeat of the struct fix. Severity here is leak/double-free-on-partial-move, gated behind aggregate destructuring of Drop values.
  4. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Tuple element-drop attempt #2: literal cases work, destructure does not converge — reverted

    Re-attempted tuple #606 (element drop) + #605 (move) with both halves (sema mark_moved_if_consumed + MIR consume_moved_operand), Drop-gated:

    Why destructure doesn't converge by patching

    Destructuring moves every element out, so the source tuple must be fully consumed (its drop suppressed). Neither path achieves it reliably:

    • The sema mark applies only when the source is a plain identifier (let (a,b) = t), not a call-result temporary (channel()).
    • The MIR cancel_scheduled_value_drop_for_local targets mir_place_plain_local(rhs_place), but rhs_place after materialize_operand is often a copy temp, not the source local whose drop is scheduled — so the source tuple's drop survives and double-frees the already-moved-out elements.

    The struct case was self-contained because structs already track per-field consumption (drop_consumed_field) and the only gap was the literal. Tuples/arrays/enums have no per-element drop-state, and destructure/extraction is exactly where that's needed. Patching individual move-sites isn't sound here.

    Conclusion

    Tuple/array/enum element-drop needs a foundational per-element drop-state (or a uniform "this aggregate was fully consumed by destructure/extraction, suppress its value-drop" mechanism that tracks the real source local, including call temporaries) — a deliberate drop-system design, not per-site patches. Reverted to the green struct-fix baseline (channels pass). The severe, confirmed double-free (struct literals) remains fixed and shipped.

  5. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Closing — the full remainder of this issue is done as of 2026-07-01/02.

    Aggregate construction (struct/tuple/array/enum-variant literals) moves non-Copy values per spec §2.4; owner safety rides the §2.5 niche (reset-on-move + guarded drop), so the double-free class is impossible by construction. The precision follow-ups that kept this open are all closed:

    • A6 nested aggregate-in-struct-field drop: verified delivered by the niche across all six shapes (plain/tuple/array/Option/Vec/two-level), pinned heap-backed in 036bb50.
    • A7 pattern-discard ownership: _ and .. in consuming destructures/match arms leaked their Drop values (whole-subject _ arms leaked the entire subject). Fixed in 0e22d06; enum payload-rest .A(a, ..) in 60cc437.
    • A8 partial extraction: tuples were already per-element precise; array index extraction leaked non-extracted siblings via the whole-base consume — fixed in ca71307 (slot blanked via reset-on-move, array keeps its guarded per-element drop; includes the projected-destination padding-memset codegen fix).

    Every shape is pinned in the debug-allocator lane (leak count=0, no DOUBLE FREE) and the behavior suite with exact drop counts. Full gates green (build, fixpoint, :test, :test-green).

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