Skip to content

Soundness: Drop is not propagated through Option/Vec/array/tuple/enum contents → leak #606

Closed

Description

@ehartford

Summary

Drop is not run on values contained in Option, Vec, arrays, tuples, or user enum payloads. When the container goes out of scope, its contents' drop never fires → resource leak. (Sibling of the aggregate-move bug; found together via the #357 ownership matrix.)

Repro (deterministic scope so drop timing is unambiguous)

type W { id: i32 }
impl Drop for W:
    fn drop(move self: Self): print_i32(self.id)

fn scope:
    var v = Vec.new()
    v.push(W { id: 1 })
    v.push(W { id: 2 })
    print_i32(50)
fn main:
    scope()
    print_i32(99)

Output: 50, 99 — neither element's drop runs. Correct would be 50, 1, 2, 99.

Same for Option<W> (let c: Option[W] = Some(W{id:5}) in its own scope → 50, 99, no drop), arrays, tuples, and user enum payloads. By contrast a struct field does drop (50, 5, 99). There is no impl Drop for Vec (or equivalent element-dropping glue) anywhere in lib/std/ or the compiler.

Impact

Every Option/Vec/array/tuple/enum holding a Drop type leaks its contents. Directly gates #357: owning C-resource wrappers stored in Option<Owned>/Vec<Owned> (the common case) never call their destructor → resource leak. With the aggregate-move double-free (companion issue), an owning wrapper is unsafe in a struct and leaks in a container — safe only as a bare local.

Likely area

Drop-glue generation must recurse into container/aggregate contents: generic containers (Vec, Option, Result) need element/payload drop, and array/tuple/enum aggregates need per-element/per-payload drop glue at scope exit. Found via spell-and-run; pairs with the aggregate copy-instead-of-move issue.

Activity

  1. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Correction + mechanism + sizing (retracting the Vec over-claim)

    My "Vec has no Drop / every container leaks every element" rested partly on grep-absence and a push-based measurement — and push is a compiler intrinsic, not a clean move, so that path is confounded by #605. Retracting the broad generalization. Here is the mechanism, traced in code, and the clean (non-#605-confounded) scope.

    Mechanism (broken-vs-absent, decided)

    • Codegen.detect_drop_functions (src/Codegen.w:4741) registers a type's drop only from an explicit impl Drop — there is no synthesized drop fn.
    • Auto field-drop, Codegen.mir_emit_drop_fields_ptr (src/CodegenDispatch.w), begins with if wl_get_type_kind(ty) != wl_struct_type_kind(): return — it recurses into struct fields only.
    • So a struct with no impl Drop still drops its fields (auto); an enum/tuple/array with no impl Drop drops nothing inside it. There is no variant-aware enum drop and no tuple/array element drop. This is absent, not broken-and-misfiring — for these aggregate kinds.

    Confirmed-clean scope (construction is #605-clean: literal-in-place / own-scope)

    Not yet established (needs the intrinsic-path trace, do NOT assume)

    • Vec: whether elements and/or the heap buffer are dropped/freed. Vec insertion is an intrinsic; a clean measurement must go through that path, and "every Vec leaks" would be extraordinary for a self-hosting compiler — so this is explicitly unverified and split out from the confirmed core. (No code in-tree stores a Drop type in a Vec/Option, so the leak is currently unexercised either way.)

    Sizing

    The confirmed core — extend the auto-drop dispatcher to recurse into TY_ENUM (discriminant-aware payload), TY_TUPLE, and TY_ARRAY contents the way it already does for TY_STRUCT fields — is a bounded, contained fix, not a drop-system rewrite. The Vec/generic-container question is separate and must be measured cleanly before it's sized or scoped into this issue.

  2. ehartford commented on Jun 22, 2026

    @ehartford
    ContributorAuthor

    Precise classification of the remaining struct-field drop gap (post step-1/step-2 A5 work)

    Probed at a5-narrow HEAD (after sound borrow-iteration + the consuming-op rejects) with a slot-counter Drop type W { slot: *mut i32 }. Verdict: the remaining nested-aggregate-in-struct-field item is a leak (sound-but-imprecise), not a double-free — so deferrable per the soundness gate.

    The gap (leak): scope-exit drop of a struct local does not recurse into a Vec[Drop] (transitive-drop) field — its elements are never dropped.

    Case Count Expected Verdict
    let h = H{items: Vec[W](3)} — struct-local scope exit 0 3 LEAK
    Outer{ Inner{ items: Vec[W](3) } } — nested struct local 0 3 LEAK (same root)
    H2{ items: Vec[W](2), n } — Vec[Drop] field + sibling 0 2 LEAK (same root)

    What already works (so the gap is narrow and the fix is not "drop structs harder"):

    Case Count Verdict
    local Vec[W](3) scope exit 3 ✅
    Vec[Vec[W]] (2×3) nested aggregate 6 ✅
    struct moved into a fn, dropped via param 3 ✅
    match h: H{ n, items: _ } — extract scalar, wildcard Vec[W] field 2 ✅ (partial-extraction precise drop works)
    struct-local with an own-Drop field (Wrap{ d: D }) scope exit 1 ✅

    Root shape: a struct-local's scope-exit drop fires for own-Drop fields (D) but not for transitive-Drop fields (Vec[W]). The param-drop and match-destructure paths do drop the Vec[W] field correctly — so this is an inconsistency in scope-exit drop scheduling / type_needs_drop recursion for struct locals, not a missing drop mechanism. The wildcard/partial-extraction precise drops sub-item appears already satisfied (the match wildcard case drops exactly once).

    Soundness: strictly under-drop (count 0 < n); never observed an over-drop/double-free/UAF. Deferred. Fixing it means making type_needs_drop(struct) recurse into Vec[Drop] fields for scope-exit elaboration — the exact lever that produced the wide-approach double-frees, so it needs the same care as the rest of A5, not a quick patch.

    Not caused by the step-1/step-2 changes (those touch lower_for_iter_ref, Sema reject branches, and CImport curation — not struct drop-glue).

  3. ehartford commented on Jun 22, 2026

    @ehartford
    ContributorAuthor

    Correction — the earlier mechanism in this thread was mis-scoped

    Deeper recon (slot-counter, with run, all opt levels, --dump-mir) shows the prior framing ("struct-local scope-exit drop fails to recurse into a Vec[Drop] field") is wrong. The actual bug is a three-condition intersection, all required:

    1. the field is transitive-Drop (Vec[W]: needs-drop, no own impl Drop) — an own-Drop field (Wrap{ d: mkD() }) in the identical shape drops fine (count 1);
    2. it is initialized directly from an rvalue / call temp (H { items: mkw() }) — building it in place (H{items:Vec.new()}; h.items.push(..)) or via a named local (let v=mkw(); H{items:v}) drops fine (count 1);
    3. the field/struct is never subsequently used — adding any use (h.items.len()) makes it drop (count 1).

    Opt-independent (leaks at -O0) and unaffected by WITH_ENABLE_MIR_VALUE_LOCALS=1 → front-end, not LLVM, not the value-locals toggle. The buffer is stored (h.items.len()==1); drop(H) is emitted in MIR (not StorageDead).

    The dedup is load-bearing over-drop protection. In the working named-local case the MIR carries both drop(H) and drop(v) yet counts 1, never 2 — codegen ensures exactly one free fires. That suppression is what keeps the sound cases from double-freeing. The leak is its dual hole: when the initializer is a temp whose stmt-temp drop was canceled by the move-consume (consume_moved_operand → cancel_stmt_temp_for_local, MirLower.w:376-387), nobody frees.

    Consequence: a standalone scope-exit-recursion fix (force drop(H) to free the field) would re-introduce the double-frees Path C just closed — the named-local case already frees via the source, and a moved-out field would be re-dropped. This is floor-blind (the floor has zero Vec[Drop], so it catches neither the leak nor the over-drop).

    Disposition unchanged: sound-but-imprecise (strict under-drop; no over-drop observed) → deferred. The fix is #607 real move-IN (transfer ownership to the field, zero/cancel the source), which closes this leak and the move-out double-frees in one model. It is not a standalone #606 patch. A full root-cause (5-whys, exact code path) is being written up separately.

  4. ehartford commented on Jun 22, 2026

    @ehartford
    ContributorAuthor

    Definitive root cause (supersedes my two comments above)

    My "three-condition intersection" framing was still an artifact. With the self-return / escape confound removed (explicit () tail), the truth is simpler and broader:

    drop(struct) never drops a field whose drop is inline-only — Vec[Drop], [N]Drop arrays, and (Drop, …) tuples all leak at the struct's scope-exit drop. Universal, not construction-dependent.

    field type, struct local, () tail (no escape) count
    H { items: Vec[W] } 0 — leak
    H { arr: [2]W } 0 — leak
    H { pair: (W, W) } 0 — leak
    Wrap { d: W } (own-Drop field) 1 — ok
    bare local [2]W / Vec[W] / (W,W) 2/1/2 — ok

    The cases that looked like they worked were all the field's value escaping to a separately-dropped local or return — let v=mkw(); H{items:v} schedules drop(v); h.items.push() as a self-returning tail returns the Vec; both then drop via the value path, and under the collapse model that frees the shared buffer once. Remove the escape and the leak is always there.

    Exact mechanism (located)

    • The struct-field-drop recursion mir_emit_drop_fields_ptr (CodegenDispatch.w:3754) drops each field via the LLVM-typed mir_emit_drop_ptr (3779). That path only emits a drop for a field type with a registered drop fn in drop_fn_values (own-Drop structs/enums) or further nested struct fields.
    • A Vec[T] / array / tuple has no registered drop fn — its element-drops + buffer-free are emitted inline, only by the sema-typed mir_emit_drop_ptr_for_sema_type (4057; Vec at 4078 via mir_emit_drop_vec_ptr, tuple 4069, array 4073). The field recursion never reaches that path, so those fields are silently skipped.
    • Confirmed at the binary: a leaking case has no with_vec_free / with_vec_len / with_vec_get_ptr symbols at all. Confirmed asymmetry: mir_emit_vec_element_drops_ptr (3983) drops elements via mir_emit_drop_ptr_for_sema_type (sema path) — which is why Vec[Vec[W]] and bare locals work, but struct fields don't.
    • Spec violation: §2.4 — "remaining fields are dropped … automatically." Origin: the inline-drop work (3528e471 Vec, 8330e601 array, 29930509 tuple) added the sema-typed value/element drops but never routed struct fields of those types through the sema path.

    Over-drop still governs the fix

    The mechanical fix (route mir_emit_drop_fields_ptr through the sema-typed path, like the element path) alone double-frees: in the escape cases the source local/return already drops the same (collapse-aliased) buffer, so drop(struct) freeing it too = 2. It must be paired with #607 real consuming move-IN (moving a Drop value into a field cancels the source's drop), so the field's drop becomes the sole free. Fixing the recursion without the move-consume reintroduces the Path-C double-frees — floor-blind.

    Disposition unchanged: strict under-drop (leak), sound-but-imprecise → deferred to #607 (mechanical field-recursion fix + move-consume, together). Not a standalone #606 patch.

  5. ehartford commented on Jun 23, 2026

    @ehartford
    ContributorAuthor

    VERDICT (debugger-proven): the mechanical fix double-frees — forced to #607

    The mechanical fix (route struct-field drops through the sema-typed path, mir_emit_drop_ptr_for_sema_type, so inline-drop fields — Vec[Drop], [N]Drop, (Drop,..) — are dropped) was implemented and tested at the instruction level. Result: it closes the leak for in-place-built fields but double-frees any field initialized by moving in a value with its own drop (a call result or a named local). Not sound under the current collapse move model.

    Both-direction matrix (fix applied, multi-field)

    case (struct local, () tail) result
    H{ arr: [W{}, W{}] } — array built in place 2 ✅
    H{ pair: (W{}, W{}) } — tuple in place 2 ✅
    H2{ a: Vec.new(), b: Vec.new() }; h.a.push; h.b.push — two Vec in place 2 ✅
    H{ items: mkw() } — Vec field from a call result panic: invalid free ❌
    Outer{ inner: Inner{ items: mk() } } — nested, call result panic: invalid free ❌
    let v=mkw(); H{ items: v } — Vec field from a named local panic: invalid free ❌
    own-Drop field Wrap{ d: mkD() } 1 ✅ (unchanged)
    Vec[Vec[W]] 6 ✅ (unchanged)
    POD Vec[i32] field ok ✅ (unchanged)

    Instruction-level proof (lldb on the compiled program)

    For let v=mkw(); H{items:v}, breakpoint on with_vec_free: hit count = 2 on the same buffer, second call panics invalid free: pointer is not an allocated payload start. Mechanism: drop(H) now frees items' buffer and the moved-in source v's own drop frees the same buffer — the collapse move-in never canceled v's drop obligation, so both fire.

    (An earlier intermediate reading of "1 free / sound" was a measurement artifact: a wrong projection argument made the field-type lookup return 0, so the field was silently not dropped — the leak was merely masked by the source's single free. Correcting the lookup unmasked the double-free. The debugger settled it.)

    Why it can't be a standalone #606 patch

    The mechanical fix and the move-in source-drop are in direct conflict: the in-place cases work precisely because there is no source local; the move-in cases double-free precisely because there is one and its drop isn't canceled. Dropping the field at struct scope-exit is only sound once moving a Drop value into a field consumes (zeros/cancels) the source — which is #607 real consuming move-IN. The leak (under-drop) and this double-free (over-drop) are the two faces of the same missing ownership transfer; you cannot fix one without the other or you flip the bug's direction.

    Decision required (release scope) — yours

    No code shipped; branch clean at be65f53e. The mechanical-fix patch is reverted. Reproductions above are runnable.

  6. ehartford commented on Jun 23, 2026

    @ehartford
    ContributorAuthor

    Correction + consolidation (retracts the "universal leak" framing above; the FORK VERDICT stands)

    I mischaracterized the leak's trigger multiple times in this thread. Settling it by a clean enumeration with lldb free-counts on the clean compiler:

    construction last statement in fn drop count with_vec_free calls
    move-in H{ items: mkw() } the let itself (tail) 0 — leak 0
    move-in H{ items: mkw() } a trailing stmt ((), print, a use) 2 — ok 1
    in-place h.items.push() ×n the .push() (tail) 2 — ok 1
    in-place h.items.push() ×n a trailing stmt (()) 0 — leak 0

    So the leak is NOT "struct-field drop recursion universally fails" (my earlier "definitive" comment) and NOT the three-condition framing. It is a context-sensitive drop-elaboration bug whose trigger differs by construction style — move-in leaks as a tail let-binding but is fine with a trailing statement; in-place is the opposite. Deterministic (repeats identically), opt-independent. Its deepest root cause is not yet established — it needs dedicated MIR+codegen debugging (lldb on the compiler, watching where drop(_2) does vs. doesn't lower to a with_vec_free), not more black-box run-count probing. I'm explicitly NOT posting a fourth guess at the mechanism.

    The fork verdict is unaffected and stands (debugger-proven)

    The question was whether the mechanical fix (route struct-field drops through mir_emit_drop_ptr_for_sema_type) is sound. It is not — it double-frees, and it regresses currently-working programs. Proof, on the clean compiler vs. the fix:

    • let v = mkw(); H{ items: v }; () — clean: drops correctly (count 2, with_vec_free hit count 1). With the fix: invalid free panic, with_vec_free hit count 2 on the same buffer.
    • Mechanism: the fix makes drop(struct) free the field's buffer, but the moved-in source's drop is not canceled by the collapse move-in, so the buffer is freed twice.

    → The mechanical fix is a regression, not a partial win. Forced to #607 real consuming move-IN (moving a Drop value into a field must cancel/zero the source before field-drop is sound). No standalone #606 patch is viable.

    Decision (release scope) — unchanged, yours

    No code shipped; the mechanical-fix patch is reverted; branch clean at be65f53e.

  7. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Closing — Drop propagation through contents is complete as of 2026-07-01/02, spec §2.4/§2.5.

    Shipped across this issue's lifetime: variant-aware enum payload drop (incl. Option/Result), tuple/array element drop, subject-consume at construction/match/if-let/let-else/?, and Vec[Drop] element drop via the narrow gate (type_needs_drop(Vec[T]) ⇔ type_needs_drop(T); da_vecdrop_* lane). The final tail closed this week:

    • A6 aggregate-in-struct-field drop verified + pinned (036bb50).
    • A7 discard-position ownership: _/.. in consuming patterns now own and drop what they discard (0e22d06, 60cc437).
    • A8 array partial extraction keeps the guarded per-element drop for non-extracted siblings (ca71307).

    Remaining deliberate boundary (NOT this issue): field move-out of a transitive-Drop aggregate stays rejected pending #607 (err_move_out_vec_field_*). Debug-allocator lane + behavior suite pin every shape; full gates 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