Repository navigation
Description
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; movefunction arguments:take(make(5))consumes correctly (verified);- constructor returning a wrapper whose field is a Copy raw pointer (
Owned { handle: p }wherehandle: *mut u8) → single drop through construct→return→scope-exit.
- direct nested literal in place:
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
ehartford commentedon Jun 19, 2026
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)wherexis 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.let y = x/moveparam / plain paramSome(x)/Ok(x)(Option/Result ctor call)Struct { f: x }[x](x, …)E.Payload(x)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
letbindings andmove/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 runDropon their contained values → resource leak. (Vechas no element-droppingDropimpl at all;Option<W>/Vec<W>in a deterministic scope drop theirWzero 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.Fix struct-literal field init double-free for Drop values (#605)
ehartford commentedon Jun 19, 2026
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).MirLowerstruct-literal lowering:consume_moved_operandon the field operand (drop-once), explicit + defaulted fields.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.wshares onefs_outputsinto bothToolFsandProcessRunner); harmless without a destructor. Strict-move for all non-Copy would require migrating that sharing to explicit clones — a separate project.CCodegenusedmir_modafter 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
type_has_drop_implis shallow — a struct with a Drop field but no own Drop impl still copies (inner double-free). Needs a transitive needs-drop predicate.ehartford commentedon Jun 19, 2026
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 totx/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 inmir_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
ehartford commentedon Jun 19, 2026
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+ MIRconsume_moved_operand), Drop-gated:(W{..}, 9)→ drops once ✅ (Soundness: Drop is not propagated through Option/Vec/array/tuple/enum contents → leak #606).let tmp = W{..}; (tmp, 9)→ source consumed, drops once ✅ (sema mark on the NK_IDENT element, mirroring the struct fix).let (a, b) = tandlet (tx, rx) = channel()→ still double-frees ❌ (invalid freein the channel tests).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:
let (a,b) = t), not a call-result temporary (channel()).cancel_scheduled_value_drop_for_localtargetsmir_place_plain_local(rhs_place), butrhs_placeaftermaterialize_operandis 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.
Update Phase 8 plan: mark status + add discovered issues (#601/#603/#604
Tuple Drop soundness: move-not-copy and drop elements (#605/#606 tuple)
Array Drop soundness: move-not-copy and drop elements (#605/#606 array)
Enum Drop soundness: variant-aware drop + move-not-copy (#605/#606 enum)
#357: generate proven-ownership owning wrappers for curated c_import …
Update Phase 8 docs: drop/move cluster + #357 first increment shipped
ehartford commentedon Jul 2, 2026
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:
_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.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).
docs: mark #605/#606 A-tail follow-ups closed in implementation plan
docs: record loose-end closure (enum-rest fix, #605/#606 closed, seed…
docs: sync implementation plan checkboxes with shipped #348/#357/#604/#…
Sema+MirLower: D17 — field consumption writes the root; `move place` …
D32: implement STRICT field moves — site-local check, tree migration,…
MirLower: `??` consumes its subject like `?` — the Result/Option temp…
Sema: a pattern never skips a destructor — destructuring a Drop value…
Fix #1280 (Box[T].ptr reads the payload's first field) and #1281 (ele…
Sema: a pattern never skips a destructor — destructuring a Drop value…
MirLower: a user carrier's `?` retires branch()'s ControlFlow temp — …
MirLower: a user carrier's `?` retires branch()'s ControlFlow temp — …
unwrap_or / unwrap_or_else / flatten no longer free the payload they …
D113: a Vec literal consumes its elements; a VecRange cannot outlive …
D113: brackets make a Vec; a fixed array or set is built where demand…