Repository navigation
unwrap_or / unwrap_or_else / flatten no longer free the payload they return; closures drop owned params; debug allocator sees str double frees (#1363) - #1398
Conversation
b1f82c6 to
55fc9e8
Compare
|
Follow-up after the battery on 787e6d8 (pushed as 55fc9e8): behav_return_temporary_cleanup (user-try, user-errdefer). This double free is older than this PR. The runtime commit 89b1095 is what made it visible. Evidence:
Fix:
behav_c_import_scales_linearly. Run alone on this build it passes (twice: 11.2s cold, 2.5s warm). Re-run on stage2 built from 55fc9e8:
|
…a silent no-op (#1363) with_str_free / with_str_free_drop_origin gate the free on rt_payload_start_is_owned. A block that was already freed is no longer an owned payload start, so a second drop of the same str buffer returned without reaching rt_free — and without reaching the debug ledger. `read_file(p).unwrap_or("")` (#1363) freed its result twice: lldb on with_str_free_drop_origin showed payload 0x100068040 freed at repro.w:4 (drop#9 scope-exit of the unwrap_or receiver temp, __drop_struct_428) and again at drop#17 (the binding `t`), while `run --debug-alloc` printed `leak count=0`. The same program with a Vec payload reported the DOUBLE FREE, because with_vec_free has no such gate. Under the debug allocator a non-owned str pointer is now looked up in the ledger: a freed, not-reused allocation start is reported with both drop origins and aborts (exit 134). Literals, views and blanked strs are not in the ledger (or are live), so the no-op path is unchanged for them.
…y decompose; lazy fallbacks are branch arms; closure bodies drop owned params (#1363) Route: memory bug — debug allocator, address trap, drop plan, IR, lldb. `read_file(p).unwrap_or("")` returned a str with the payload's length over a freed buffer. Evidence, repro `let t = read_file(p).unwrap_or("")`: - MIR (main): `bb2: _6 = move _4<as v0>.f0` (success arm moves the payload out of the materialized receiver temp _4), then `bb4: drop(_4) @ drop#9 scope-exit _4`; `--dump-drop-plan`: `place=_4 state_before=Maybe action=conditional`, `--trace-ownership main:_4`: `_4<as v0>.f0=Maybe`. - IR: bb4 calls `__drop_struct_428(ptr %3)` unconditionally -> the enum glue `with_str_free_drop_origin` on the Ok payload the result now owns. - lldb (small payload): payload 0x100068040 freed at repro.w:4 by that drop, and again at drop#17 (scope exit of `t`). Vec payload under WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1 and the address trap: `trap-free hit=1 origin=drop#enum __drop_enum_143` at the unwrap_or line (matrix.w:194:25), then `DOUBLE FREE ... second_drop=drop#struct __drop_struct_96`. A >1 MB payload is unmapped by the first free, so the read faults (the issue's SIGSEGV in rt_memcpy). Exact line: lower_unwrap_or_method (and lower_unwrap_or_else_method, lower_option_flatten_method) move the variant payload with operand_for_place and leave lower_owned_receiver_place's temp drop scheduled. A move out of a variant payload registers nothing — consume_moved_operand only resets pure field paths (`place_field_projection_count` is -1 through PK_DOWNCAST) — so no reset-on-move blanks it. `??` had the same defect and was fixed by decomposition in #1042; unwrap_or/unwrap_or_else/flatten were not. Fix: one helper, retire_decomposed_carrier, used by `??`, unwrap_or, unwrap_or_else and flatten: the failure arm drops what is left (an Err payload, or nothing) once, and the subject's own drop is retired. The matrix also showed the owned default leaking on the success path of `o ?? d` (and, once the crash was gone, of `o.unwrap_or(d)`): the default is lazy (§10) but was lowered without branch framing, so `d` stayed marked moved after the join and its scope-exit drop was skipped. begin_lazy_arm / end_lazy_arm frame the fallback exactly like a lower_if branch (move state saved and restored, resets flushed in the arm). unwrap_or_else hands the Err payload to the fallback closure. A closure's plain `T` parameter consumes (§3.8, D5): every call site moves the argument in and blanks its source without dropping it — but prepare_anonymous_body never scheduled a drop for parameters, so any owned closure argument the body did not move on leaked (`(x: str) => 1`, `(_) => ""`). The subject temp's drop had been masking that for unwrap_or_else's `(_)`, and double-freed when the closure did consume (`(e) => e.to_str()`). The body now drops non-Copy parameters. Matrix (tools in the PR description): {unwrap_or, unwrap_or_else, ??, match} x {Result, Option} x {str, Vec[i32], struct{str, Vec}} x subject {local, read_file()/call result, field moved out} x default {literal, owned} x {Ok, Err} x {small, >1 MB} = 552 runs under WITH_DEBUG_ALLOC=1. Before: 420 ok, 132 bad (uo/uoe success paths crash or DOUBLE FREE; `??` owned-default leak). After: 552/552 ok, leak count=0. A borrowed `&str` default is rejected by Sema ("would need to copy a `str`"), which is the §10 join rule, not a lowering case. Fixtures: test/debug_alloc/da_carrier_eliminator_payload_owned.w, test/debug_alloc/da_closure_owned_param_dropped.w, test/behavior/behav_unwrap_or_large_str_payload.w (2 MB read_file payload through unwrap_or / unwrap_or_else / ??, and a 500k-element Vec). Ownership/drop change: drop-audit (stage1 candidate vs seed) 136 cells, 0 regressions; move-audit 15 cells, 0 vs-expected FAIL; debug-alloc fixture lane on stage1: all PASS; stage2 (built by this stage1) checks src/main.w ok. Fixes #1363.
…the Break/Continue payload was freed under its new owner (#1363 follow-up) behav_return_temporary_cleanup's user-try and user-errdefer modes reported `DOUBLE FREE ... first_drop=drop#enum __drop_enum_510 second_drop=drop#struct __drop_struct_16` under this branch. The defect is older than the branch; the str-free ledger check from 89b1095 is what made it visible. Evidence. Reduced repro: `one(t) -> Validation: validate(t)?; Valid(0)`, with main matching `Invalid(message)`: - MIR `one`, same shape on main (release cffb1cb) and on this branch: `bb4: call from_break(move _4<as v1>.f0)`, then on the return path `bb6: _0 = move _6; ... drop(_4) @ drop#7 scope-exit _4; return`. _4 is branch()'s ControlFlow result. - lldb on main's binary, breaking on with_str_free_drop_origin: buffer 0x100064010 is freed at ut.w:19 (the `?`, the ControlFlow enum drop) and again at ut.w:25 (main's `message`). - With WITH_DEBUG_ALLOC_SCRIBBLE=1, main's release and the installed v0.15.2.1 both fail temporary_exit_cases.w user-try at 170:33 (`message == "bad"`): the message is read from freed memory. Before 89b1095 the second free hit the str path's ownership check and returned silently. - A non-Copy Continue payload is freed the same way, by the statement-end temp drop. `let v = lookup(k)?; Found(v ++ "+")` printed " +" on v0.15.2.1. Exact line: lower_user_try_question_mark materializes branch()'s result and moves the Break payload into from_break (fail path) and the Continue payload into the result (pass path). The temp's drop stays scheduled, so emit_drops_for_return (fail path) and the statement flush (pass path) free the payload again. A variant-payload move registers no reset (consume_moved_operand, #1394). Builtin `?` (lower_question_mark_value) has retired its scrutinee since #605/#606; the user-Try twin never did. Fix: retire_decomposed_carrier(branch_place) right after the switch. ControlFlow has exactly one payload per variant and both arms move it. The builtin `?` now uses the same helper; the code is identical. Tool: p7_assert_success took a label and never printed it, so this test looped over 30 modes and failed without naming one. It now prints `FAILED [<label>]: rc=N`, and so does p7_assert_failure_contains, which discarded its label with `let _ = label`. This covers all 55 callers. Fixture: test/debug_alloc/da_user_try_payload_owned.w covers Break with a str payload, Continue with a str payload, and `?` under errdefer in a loop. v0.15.2.1: DOUBLE FREE. This branch: leak count=0.
55fc9e8 to
dab175b
Compare
…etire the subject they decompose (#1379) Route: memory bug — debug allocator, WITH_ALLOC_NO_REUSE, the address trap, lldb, then the MIR of the block. `o.filter((v) => v.len() > 0)` over `Option[Vec[i32]]` printed `true` and then `debug-alloc: DOUBLE FREE ... second_drop=drop#enum __drop_enum_448`, rc=134. Evidence (installed v0.15.2.1, repro r.w): - `WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1`: the report persists (a genuine double free), `first_drop=drop#enum __drop_enum_448`. - `WITH_DEBUG_ALLOC_TRAP_FREE=<addr>` under lldb: `trap-alloc hit=1`, `trap-free hit=1 origin=drop#enum __drop_enum_448`, `trap-free hit=2` (same origin). With TRAP_FREE_HIT=1 and a breakpoint on _exit, the first free is `with_vec_free_drop_origin <- main at r.w:5:5`: the enum glue at the filter line. - `--dump-mir`, main: bb3: call copy _8(move _7<as v0>.f0) (predicate, by value) bb7: _9 = aggregate(kind=1, tag=0, fields=[move _7<as v0>.f0]) bb5: _6 = move _9; drop(_7) @ drop#15 scope-exit _7 bb9: drop(_6) @ drop#23 scope-exit _6 `_7` is lower_owned_receiver_place's materialized subject. The kept payload moves into `_9`, but a move out of a variant payload registers no reset-on-move, so drop#15 frees it and drop#23 frees it again. Exact lines (src/MirLower.w, lower_option_combinator_method, the filter branch): - `filter_args.push(self.operand_for_place(payload_place, payload_ty))` moved the payload into the predicate. §10.5 says the predicate is `fn(&T) -> bool`, and Sema (method_arg_expected_type) typed it `fn(T)`. On main a closure does not drop its owned parameter, so this was a spec violation, not the first free. Once closures drop owned params (#1398) it is a third free. - the kept `Some` moved the same payload, and the join left `_7`'s scope-exit drop live. Fix: - Sema: the filter predicate's expected type is `fn(&T) -> bool`. Option.filter now validates its argument like inspect does (a one-argument function whose parameter is `&T`). - MIR: the predicate gets the payload's address (operand_for_place_arg, like inspect). A rejected payload is dropped once, on its path. At the join the subject is retired: retire_decomposed_carrier cancels its statement temp and scheduled drop. - The same retire applies to the other combinators whose every path moves a payload into the result without a consuming closure. Each was a DOUBLE FREE on the seed and on main's stage1: Option.inspect, and Result.inspect / inspect_err / context / with_context. map / and_then / map_err / or_else move a payload into a consuming closure whose body does not yet drop its parameter. They are #1363's and are unchanged here. - observer_param_accepts: an observing callback's parameter must be a reference. types_compatible alone accepted `(q: P) =>` for `&P`, so Sema said nothing and codegen died on "wrong argument type actual=ptr expected=P". That is a silent tool, fixed for filter, inspect and inspect_err. Matrix (test/debug_alloc/da_option_filter_observes_payload.w, leak count 0, exact stdout): Vec / str / struct / i32 payloads × keep / reject / None; a call-result subject; a named `fn(&T) -> bool` predicate; a typed `(q: &P)` closure; an Option[&T] payload; filter feeding map; and Option.inspect Some/None, Result.inspect / inspect_err / context / with_context on both paths. main's stage1: DOUBLE FREE. After: all cells pass. test/compile_errors/err_option_filter_owned_param.w pins the typed owned-parameter rejection. spec §10.3 / §10.5 / §10.6 fixtures and codegen_option_methods pass on stage1. A generic closure annotation (`(v: &Vec[i32]) =>`) types `v` as `i32`. That is a separate parser bug, #1402. The fixture's typed cell uses a non-generic payload. Ownership/drop change: batch alone. move-audit (stage1 vs seed): 15 cells, 0 FAIL, 0 DIFF. drop-audit (stage1 vs seed): 136 cells, 0 non-PASS, 0 regressions. debug-alloc fixture lane on stage1: all PASS. Fixes #1379.
`r.context(msg)` lowered the message as a statement temp and, on the Err arm, moved it into the ContextError; the statement flush then dropped the temp as well. With #1398's debug-allocator fix (the str free path asks the ledger), `root().context(heap_message())?` on an Err reports DOUBLE FREE addr=... size=64 first_drop=drop#struct __drop_struct_16 second_drop=drop#struct __drop_struct_434 The call now takes the message into its own local before the branch: the Err arm moves it into the ContextError, the Ok arm drops it (`context-message-unused`). with_context is unchanged (its message is built inside the Err arm). test/debug_alloc/da_variant_payload_move_blanked.w covers both arms: the Ok arm leaks if the drop is missing (leak count), the Err arm double-frees under a runtime that reports str double frees.
`r.context(msg)` lowered the message as a statement temp and, on the Err arm, moved it into the ContextError; the statement flush then dropped the temp as well. With #1398's debug-allocator fix (the str free path asks the ledger), `root().context(heap_message())?` on an Err reports DOUBLE FREE addr=... size=64 first_drop=drop#struct __drop_struct_16 second_drop=drop#struct __drop_struct_434 The call now takes the message into its own local before the branch: the Err arm moves it into the ContextError, the Ok arm drops it (`context-message-unused`). with_context is unchanged (its message is built inside the Err arm). test/debug_alloc/da_variant_payload_move_blanked.w covers both arms: the Ok arm leaks if the drop is missing (leak count), the Err arm double-frees under a runtime that reports str double frees.
…specialization; keep unit objects on a failed link (#1359, #1331) (#1360) * Patterns: a struct pattern tests its literal fields; exhaustiveness reads whole patterns (#1388) `Point { x: 0, y }` matched any `x` in match, if let, let-else and `for`: MirLower.lower_pattern_match had no NK_PAT_STRUCT branch, so a named-field struct pattern fell into the final "conservatively accepted" default, `self.terminate(TermKind.TK_GOTO, arm_bb, 0, 0, 0)` — no test of any field. Observed on a stage2 of origin/main: AstPool.kind = 0x6b (NK_PAT_STRUCT) reaches the shared goto tail with w1 = TK_GOTO, w2 = arm_bb (bb2); --dump-mir of the repro shows `bb0: goto -> bb2` with no read of `_1.x`. MirLower: - NK_PAT_STRUCT tests every refutable field sub-pattern, as the positional and tuple forms do; field places carry the field's type (read from the subject, so generic struct instances lower — `Pair { a, b }` over `Pair[i32]` was an invalid-MIR ICE). - The default is loud: a pattern kind with no test lowering reports and marks the function unsupported instead of matching every value. A slice pattern over a dynamic slice (`match s: [] => ...` on `[]i32`), which also took the first arm silently, now fails there (#1389). Sema (§9.7, expression-position matches must be exhaustive): - Exhaustiveness is a pattern-matrix usefulness check (Maranget) over the whole pattern: bool, enum variants with their payloads, tuples, structs, bounded integers split into literal/range segments; str, floats and wider types need a catch-all. It names a witness: "non-exhaustive match on 'Point': `Point { x: 1, .. }` is not covered". `Some(5), None` no longer counts as exhaustive over Option[i32], nor `0, 1` over i32 (#994's check half); `0..=127, 128..=255` over u8 does. D43's missing-arm test uses the same answer. - A struct pattern requires a struct subject, names the subject's type, and names only its fields; an enum subject (`Circle { r }`) reached codegen untyped. A refutable `for` pattern keeps its filter semantics (behav_for_full_patterns); with the lowering fixed, `for Point { x: 0, y } in ps` now skips points whose x is not 0. Comprehension clauses never test their pattern at all — filed as #1403. Sweep: `check` over the 423 test/examples files that contain a match, a pattern `for` or a struct/slice pattern, and `test` over the 34 with struct or slice patterns, stage1 of this branch against stage1 of 00408eb: no existing program changed result; only the new fixtures differ. Fixes #1388 * Sema: a value `if`/`match` arm that yields a whole binding moves it (#1380) Route: silent wrong value, a move the checker never modeled — MIR dump, then the checker's own move trace (WITH_DEBUG_MOVE), then the branch. `let p = if c: a else: b; let q = if c: a else: b` compiled and printed `[xy] []`, leak count 0. Evidence (installed v0.15.2.1, repro r.w): - `--dump-mir`, main: `bb3: _9 = move _1; _1 = const zst(ty16)` and `bb4: _9 = move _2; _2 = const zst(ty16)` for the first `if`; the second `if` moves the blanked `_1`/`_2` again (`bb6: _11 = move _1`). MirLower's lower_if moves an arm's whole-binding tail into the join temp; only projected place reads join as a view (#747 03g: `operand_is_view_read` requires `place_proj_counts > 0`). - `WITH_DEBUG_MOVE=1 with check`: `let p = a` logs `[move] sym=a`; the `if` version logs no move for `a` or `b`. Exact line: SemaCheck.check_if_expr (and check_match_expr) check a value arm through check_expr_value_context and never mark its tail consumed; the consumer's mark_moved_if_consumed(value) then sees NK_IF_EXPR / NK_MATCH and does nothing. So Sema's move state never recorded what MIR does. Fix (§2.2): mark_arm_tail_consumed marks a value arm's whole-binding tail (through blocks and parens) consumed in the arm's own move state, before the branch merge — exactly what `let p = a` does. Only a binding that outlives the arm is marked (§29.8 forbids shadowing, so a live name is the outer one). The second read is now "use of moved value"; in a loop, "moved inside a loop". This is the issue's first option. The other (a view join for whole bindings) would change MIR's ownership, not only the checker, and is Eric's call. Every place the new rule rejected in the tree was reading a value the program had already moved — each a real bug, fixed here: - CImport ci_translate_anon_record_cursor: `raw_name` moved into `actual_name`, so a named field of anonymous-record type inside an anonymous record came out as `anon_0` (`o.mid.deep` did not resolve; test/behavior/behav_c_import_nested_anon_record_field_name.w, which fails on the seed). Clone. - CImport ci_translate_macros: `offsetof_result` and `cast_expr_result` were moved before the branches that re-read them, so the offsetof `c_int` branch and the "expression translation" fallback never ran. Running them would be wrong (offsetof is size_t, which clang's semantic type already gives; the fallback typed `{ .a = 3 }` as a `c_int` global, breaking behav_c_import_macro_probe_recovery). Removed, with the extern-var pre-scans and ci_expr_references_var that only fed them: behavior unchanged. - ComptimeEval: effect_tool_identity moved `resolved` into the cache key, so a tool's identity was always `<exe>:unresolved`, never its sha256; glob moved `pattern` (error text lost it) and `rel_file` (a glob based at `.` returned "" for every match). Clone. - BundleInterfaceEmit: `trait_name` moved into the export name, so the impl row (and the bundle fingerprint) had an empty trait field. Clone. - Codegen.declare_function_at_inner: `sema_name_str` / `parsed_name` moved into `name_str` / `alias_text`; later reads saw "". Behavior-neutral (Backend hands Codegen the Sema pool, so the recovered alias and effective name are the same text). Clone. - std.build tool actions (scratch dir error text) and build/release_publish.w (every provenance sidecar after the first said `builder=unknown`). Clone. Matrix (installed v0.15.2.1 vs stage1): if / else-if / match × arm is an owned str / Vec local, a param, a block tail; consumer is let, assign, call arg, struct field, method receiver, `++`/f-string; then-used-after, in a loop, diverging other arm, cloned arms, last use. Before: every used-after cell compiled and read "" (or Vec len 0); after: each is "use of moved value" (the loop cell "moved inside a loop"), cloned and last-use cells compile and print the text. Field arms (`if c: x.s else: y.s`) are not whole bindings and are unchanged here: MIR treats them as a view join and still blanks the field — #1409. Sweep: every file under test/ examples/ lib/ tools/ build/ with a candidate arm shape (655 files) checked with stage1; the only new diagnostics were the sites above. `with-stage1 check src/main.w` ok; `:stage2` (stage1 builds stage2 and the pcre2/zlib/tommyds/c_algorithms bundles) green; stage2 checks src/main.w. c_import behavior tests: 0 regressions (the six stage1 failures fail the same on main's stage1). move-audit (stage1 vs seed): 15 cells, 0 FAIL, 0 DIFF. Fixtures: test/compile_errors/err_if_arm_moves_binding.w, err_match_arm_moves_binding.w, err_if_arm_move_in_loop.w, err_if_arm_moved_by_observer.w; test/behavior/behav_if_arm_binding_join.w, behav_c_import_nested_anon_record_field_name.w. Ownership (move checking) change: batch alone. Fixes #1380. * Spell the field moves the #1395 check finds: .clone() to keep the owner whole, var + move to vacate A field that reaches an owned `if`/`match`/`??` join, a block tail or a break value was an implicit field move the D32 funnel never saw (#1395). Every site the fixed compiler reports in src/, lib/ and test/, respelled with the fix-it the D32 error offers: - `.clone()` where the owner stays whole: Sema's current_module_path in record_named_type_with_pub / record_displaced_fn / embed_file / MirLower's src intrinsics (a `mut fn` blanked it mid-collection — the #1350 bug), ProjectConfig/Compilation root_dir, CImport bail location, ComptimeEval target_name/final_output/location, Codegen analysis_query, CodegenDispatch source paths, Frontend source_dir, Analysis diag facts, BuildGraph target.entry, std.build ToolFs target_name. - `var` + `move` where the owner dies right after: ComptimeEval's control-signal value and write_binary bytes; the raw-slot takes in std.collections (binary_heap, hash_index, sorted_vec, trie) and behav_generic_drop_only_use, which hid `(*slot).value` in `unsafe { }` (the unwrapped spelling was already the D32 error). - derive(Builder)'s generated `build` rebinds the consumed builder to a `var` and vacates each `??` operand explicitly, as the SoA push does. Every spelling is valid under the current rule, so this lands first. * Sema: a field that reaches an owned join, block tail or break value is an implicit field move (#1395) §2.2 (D32): "A field never moves out implicitly — anywhere, in any context." §3.8's join rules make every arm of an `if`/`match`/`??` whose result is owned an owned-value demand (rules 2 and 5: "A reference to a non-Copy value cannot satisfy an owned demand; producing an independent value requires an explicit owning operation such as clone"). Only an unannotated `let x = place.field` binds a view. Root cause: the D32 funnel (mark_moved_if_consumed) is reached with the consumed expression — the `if`/`match`/block node — and never looked at the arms, so `let path = if c: self.p else: ""` passed check while MirLower's lower_expr NK_FIELD_ACCESS arm emitted OK_MOVE of the field place: a `mut fn` reset the receiver's field to "" (the #1350 symptom), a read `fn` byte-copied a Vec field that both owners then freed. The inferred-return tail check never fired either: check_fn_body keyed it on `ret_type == 0`, but an unannotated fn's signature still reads Unit there. Now the if- and match-join, `??`, and break-value sites check each arm of an owned result, and a consumed block checks its tail, through one helper (d32_check_owned_value_field) that feeds the existing funnel: D32's error with its `move`/`.clone()` fix-its, or D22 §13.6's borrowed-field error through a view. The inferred-return tail check keys on the annotation. move_audit gains 58 field cells (str/Vec x mut fn/read fn/owned local x plain, if, match, ??, block, break, argument, inferred return, clone, move); the baseline accepted all 42 error cells. An all-field join with no owned anchor is rejected too, where §3.8 rule 3 would bind a view — the safe direction, filed as #1408. Fixes #1395. * Option.filter's predicate observes `&T`; filter / inspect / context retire the subject they decompose (#1379) Route: memory bug — debug allocator, WITH_ALLOC_NO_REUSE, the address trap, lldb, then the MIR of the block. `o.filter((v) => v.len() > 0)` over `Option[Vec[i32]]` printed `true` and then `debug-alloc: DOUBLE FREE ... second_drop=drop#enum __drop_enum_448`, rc=134. Evidence (installed v0.15.2.1, repro r.w): - `WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1`: the report persists (a genuine double free), `first_drop=drop#enum __drop_enum_448`. - `WITH_DEBUG_ALLOC_TRAP_FREE=<addr>` under lldb: `trap-alloc hit=1`, `trap-free hit=1 origin=drop#enum __drop_enum_448`, `trap-free hit=2` (same origin). With TRAP_FREE_HIT=1 and a breakpoint on _exit, the first free is `with_vec_free_drop_origin <- main at r.w:5:5`: the enum glue at the filter line. - `--dump-mir`, main: bb3: call copy _8(move _7<as v0>.f0) (predicate, by value) bb7: _9 = aggregate(kind=1, tag=0, fields=[move _7<as v0>.f0]) bb5: _6 = move _9; drop(_7) @ drop#15 scope-exit _7 bb9: drop(_6) @ drop#23 scope-exit _6 `_7` is lower_owned_receiver_place's materialized subject. The kept payload moves into `_9`, but a move out of a variant payload registers no reset-on-move, so drop#15 frees it and drop#23 frees it again. Exact lines (src/MirLower.w, lower_option_combinator_method, the filter branch): - `filter_args.push(self.operand_for_place(payload_place, payload_ty))` moved the payload into the predicate. §10.5 says the predicate is `fn(&T) -> bool`, and Sema (method_arg_expected_type) typed it `fn(T)`. On main a closure does not drop its owned parameter, so this was a spec violation, not the first free. Once closures drop owned params (#1398) it is a third free. - the kept `Some` moved the same payload, and the join left `_7`'s scope-exit drop live. Fix: - Sema: the filter predicate's expected type is `fn(&T) -> bool`. Option.filter now validates its argument like inspect does (a one-argument function whose parameter is `&T`). - MIR: the predicate gets the payload's address (operand_for_place_arg, like inspect). A rejected payload is dropped once, on its path. At the join the subject is retired: retire_decomposed_carrier cancels its statement temp and scheduled drop. - The same retire applies to the other combinators whose every path moves a payload into the result without a consuming closure. Each was a DOUBLE FREE on the seed and on main's stage1: Option.inspect, and Result.inspect / inspect_err / context / with_context. map / and_then / map_err / or_else move a payload into a consuming closure whose body does not yet drop its parameter. They are #1363's and are unchanged here. - observer_param_accepts: an observing callback's parameter must be a reference. types_compatible alone accepted `(q: P) =>` for `&P`, so Sema said nothing and codegen died on "wrong argument type actual=ptr expected=P". That is a silent tool, fixed for filter, inspect and inspect_err. Matrix (test/debug_alloc/da_option_filter_observes_payload.w, leak count 0, exact stdout): Vec / str / struct / i32 payloads × keep / reject / None; a call-result subject; a named `fn(&T) -> bool` predicate; a typed `(q: &P)` closure; an Option[&T] payload; filter feeding map; and Option.inspect Some/None, Result.inspect / inspect_err / context / with_context on both paths. main's stage1: DOUBLE FREE. After: all cells pass. test/compile_errors/err_option_filter_owned_param.w pins the typed owned-parameter rejection. spec §10.3 / §10.5 / §10.6 fixtures and codegen_option_methods pass on stage1. A generic closure annotation (`(v: &Vec[i32]) =>`) types `v` as `i32`. That is a separate parser bug, #1402. The fixture's typed cell uses a non-generic payload. Ownership/drop change: batch alone. move-audit (stage1 vs seed): 15 cells, 0 FAIL, 0 DIFF. drop-audit (stage1 vs seed): 136 cells, 0 non-PASS, 0 regressions. debug-alloc fixture lane on stage1: all PASS. Fixes #1379. * MirCore: the drop-state scratch and input maps clone their chunk ids; codegen units pin the receiver-specialization case (#681, #1359) The copy loops in mir_drop_state_blocks_new and MirDropStateBlocks.input worked around a stage1 link failure: `undefined symbol: _Vec.clone__receiver__94_3`. The source compiler does not have this defect. The pinned seed (v0.15.2.0) does, because it predates #1325's gen_owned_specializations. At v0.15.2.0, src/Codegen.w:6021 (ensure_concrete_mir_function) generates a specialization's body in whichever unit reaches a call to it, and unit_demote_foreign_definitions (:1356) deletes the body in every unit that doesn't own it. An instance whose callers all sit outside its owning unit is then defined by no unit. Evidence: the new behavior test under the seed fails to link at 3, 7, 8, 12 and 16 units ("_Vec.clone__receiver__94_3", referenced from ___wcu$146$Holder.dup in ...o.u6.o). Stage1 built from this tree prints 4/376 at each of those counts. On a program where several functions clone a Vec[i32], nm on stage1's WITH_KEEP_UNIT_OBJECTS output shows one definer (u4.o: T _Vec.clone__receiver__224_3) and the other units referencing it (u1.o, u7.o: U). With `.clone()` restored at both sites, the seed-built stage1 links (`:dev` green; stage1 defines T _Vec.clone__receiver__94_3). That only works because of how the 16-unit packing falls for this tree, not because the seed is fixed. #1359 tracks cutting a seed that contains #1325. * WITH_KEEP_UNIT_OBJECTS keeps the unit objects on a failed link too (#1331) compilation_execute_binary_link_plan deleted t.o and t.o.u<k>.o on a failed link before it checked WITH_KEEP_UNIT_OBJECTS. A failed link is exactly when those objects are needed: nm on them names which unit defines and which unit references an undefined or duplicate symbol across codegen units. #1325 and #1359 both had to be chased by breaking in lldb at compilation_cleanup_build_products. With the variable set, a failed link now keeps the objects, removes only the partial binary, and prints where the objects are. Checked with stage1 on a program that calls an undefined extern at 4 units: WITH_KEEP_UNIT_OBJECTS=1 leaves u.o and u.o.u1.o..u3.o in place and prints the note. Without the variable, nothing is left behind, as before. Fixes #1331 --------- Co-authored-by: Eric Hartford <[email protected]>
`r.context(msg)` lowered the message as a statement temp and, on the Err arm, moved it into the ContextError; the statement flush then dropped the temp as well. With #1398's debug-allocator fix (the str free path asks the ledger), `root().context(heap_message())?` on an Err reports DOUBLE FREE addr=... size=64 first_drop=drop#struct __drop_struct_16 second_drop=drop#struct __drop_struct_434 The call now takes the message into its own local before the branch: the Err arm moves it into the ContextError, the Ok arm drops it (`context-message-unused`). with_context is unchanged (its message is built inside the Err arm). test/debug_alloc/da_variant_payload_move_blanked.w covers both arms: the Ok arm leaks if the drop is missing (leak count), the Err arm double-frees under a runtime that reports str double frees.
`r.context(msg)` lowered the message as a statement temp and, on the Err arm, moved it into the ContextError; the statement flush then dropped the temp as well. With #1398's debug-allocator fix (the str free path asks the ledger), `root().context(heap_message())?` on an Err reports DOUBLE FREE addr=... size=64 first_drop=drop#struct __drop_struct_16 second_drop=drop#struct __drop_struct_434 The call now takes the message into its own local before the branch: the Err arm moves it into the ContextError, the Ok arm drops it (`context-message-unused`). with_context is unchanged (its message is built inside the Err arm). test/debug_alloc/da_variant_payload_move_blanked.w covers both arms: the Ok arm leaks if the drop is missing (leak count), the Err arm double-frees under a runtime that reports str double frees.
…ces; variant-payload moves are reset-on-move; a downcast place has no type (#1394, #1381, #1415) (#1425) * validate-ownership: a drop that frees a sub-place moved out without a reset is rejected (#1394) The ownership validator passed #1363's MIR: `_8 = move _6<as v0>.f0` on the success arm, then `drop(_6)` at the join, where the enum drop glue freed the payload the result owned. Two causes: - mark_place joined Moved into the base on a sub-place move, so the base read Maybe and the vacated payload read the same Maybe as its parent; nothing distinguished a partial move from a conditional whole move. A sub-place move now leaves the base's state alone. - validate_ownership_body checked a Drop only for Uninit/MaybeGarbage. It now rejects a drop of a place with a drop-bearing sub-place more moved than the place itself (Moved under Init/Maybe, Maybe under Init): a path reaching the drop vacated it and nothing reset it (§2.5.1). MirCore has no Sema, so lowering records in the module every type a body moves out of a sub-place that has drop glue (sema_moved_drop_types); the validator looks the vacated sub-place up by the typed validator's own place type. * MirLower: a str comparison and an f-string interpolant observe their places (#1394) Two producers lowered an observation as a move. The stricter validate-ownership rejected both, each where an owner drops whole after the "move" of its field: - `v.text == s` with `s: &str` fell outside the str-vs-str observer path and lowered the owned side as a value: `binop(eq, move _2.text, copy _6)` (ComptimeEvaluator.match_pattern in the compiler itself). An owned side compared with a `&str` now observes too. - An f-string interpolant `{u.name}` lowered as `move _1.name` into fmt_buf_write_str, which (like fmt_to_str and every FmtBuffer writer) reads the value and leaves it to its owner (#761). A moved place operand becomes a copy: formatting observes. Nothing reset either "moved" field, so the MIR claimed the owner's drop freed a value it no longer owned. validate-all: 11 corpus files (idiomatic, service x3, email, ephemerality x2, issue65 x2, named arguments, dump_typed_top_level_string_sidecar_key) and src/main.w now pass. * MIR: a downcast place has no type of its own; audit:codegen names both LLVM types (#1381) `with analyze audit:all` failed on every `??`/`unwrap_or`: violation: place 6 in main: projection lowers to LLVM type kind 10 but its MIR type 339 (Option[i32]) is kind 10; ... lower_double_question, lower_unwrap_or_method and most Option/Result combinators built new_downcast_place(value_place, idx, value_ty), typing the downcast place as the whole enum, while codegen (mir_place_projected_type) projects PK_DOWNCAST to the variant's payload struct; match lowering passed 0. One rule now: a downcast place has no type. It is only ever the base of a payload field place, which carries the payload's type. new_downcast_place takes no type (every producer gets the rule), and the typed validator's place walk yields none for a place that ends in a downcast, so a downcast used as a value is reported instead of read as the enum. The audit message compared type identity while printing only kinds; it now prints both LLVM types (wl_print_type, LLVMPrintTypeToString). * MirLower: a move out of a variant payload is reset-on-move; a failed match guard gives its bindings back (#1394) consume_moved_operand registered a move only for a whole local or a pure field path: place_field_projection_count is -1 through PK_DOWNCAST, so a move out of a variant payload registered no reset-on-move (§2.5.1). Every carrier eliminator had to hand-roll the subject's ownership, and the ones that did not left the enum's drop glue to free the payload the result owned. The stricter validate-ownership found them across the corpus: unwrap_or (#1363), Result.map/map_err/or_else's passthrough arm, .context/.with_context, ?., custom Try, sequence/traverse. Under WITH_DEBUG_ALLOC=1 (origin/main stage2) `bad().map((x) => x + 1)` on an Err(Vec) reports DOUBLE FREE first_drop=__drop_enum second_drop= __drop_struct_96. A payload move now queues its blank with the block it happened in. A payload slot overlaps the other variants' payloads, so the blank has to land on the moving path while the enum still holds that variant, never at a statement flush that may sit after a join: it is emitted before the moving block's terminator (carried across a call into the call's continuation), and before an earlier drop or overwrite of the same base in that block. ok()/err() drop their hand-rolled blank for it; lower_context_error_operand now consumes the moved source. A failed match guard dropped the arm's bindings, freeing the payload the next arm then bound again (Some(v) if .. => .., Some(v) => ..: DOUBLE FREE on origin/main). With payloads blanked the next arm would bind the blank instead. Pattern bindings now log what they move out of the subject, and the guard-fail path moves it back and blanks the binding. Evidence (stage2 from this branch): - #1363 repro: validate-all ok; `_8 = move _6<as v0>.f0; _6<as v0>.f0 = const zst` on the success arm, then drop(_6) frees only an Err payload. - validate-all over test/, examples/, lib/std (2138 files): all 24 files the new rule flagged pass; no file newly fails; src/main.w ok. - test/debug_alloc/da_variant_payload_move_blanked.w: map, err(), ?., guarded payload and whole bindings — DOUBLE FREE on origin/main for map, ?., both guards; leak count=0 here. - build.w deep-debug-tool-tests: audit:all on a ??/unwrap_or/map fixture must report violations=0. * MirLower: Result.context owns its message on both paths (#1394) `r.context(msg)` lowered the message as a statement temp and, on the Err arm, moved it into the ContextError; the statement flush then dropped the temp as well. With #1398's debug-allocator fix (the str free path asks the ledger), `root().context(heap_message())?` on an Err reports DOUBLE FREE addr=... size=64 first_drop=drop#struct __drop_struct_16 second_drop=drop#struct __drop_struct_434 The call now takes the message into its own local before the branch: the Err arm moves it into the ContextError, the Ok arm drops it (`context-message-unused`). with_context is unchanged (its message is built inside the Err arm). test/debug_alloc/da_variant_payload_move_blanked.w covers both arms: the Ok arm leaks if the drop is missing (leak count), the Err arm double-frees under a runtime that reports str double frees. * validate-ownership: a move out of a place projected through a reference is rejected (#1415) Before #1395's Sema fix, `let v = if c: self.p else: Vec.new()` in a `&self` method lowered the join arm as `_4 = move _1.*.p`, a move out of the shared receiver's pointee; `--validate-all` said ok and the debug allocator reported the double free (rc=134). A reference never owns its pointee: the frame can neither own the moved value nor reset its source, so the referent's owner and the destination both free it (§2.2 D32: a field vacates only through a `var` base or a `mut fn` receiver, whose place carries no deref — `_2 = move _1.p`; D22: a view never becomes an owner). validate_ownership_body now rejects an OK_MOVE, in any statement or terminator, of a drop-bearing place whose projections dereference a TY_REF. A raw pointer's pointee (the unsafe tier) and a Box's are owned through the pointer and stay legal. Evidence (stage2 from this branch, repro from #1415, origin/main lowering): error: validate-ownership failed: fn sym770 stmt3 span=72: moves out of _1.*.f769 through a reference, which does not own it (§2.2 D32, D22) The parent commit's stage2 says `validate-all: ok` on the same MIR; `run --debug-alloc` on it: DOUBLE FREE ... second_drop=drop#struct __drop_struct_135. src/main.w: validate-all ok. test/internals/mir_move_through_reference_test.w pins the rule (move through &T rejected; copy through &T, move through *T, and a type with no drop glue accepted). --------- Co-authored-by: Eric Hartford <[email protected]>
…1424) (#1428) Fails (DOUBLE FREE) on #1398's build, passes on #1425's reset-on-move (batch X2). Lands after X2. Co-authored-by: Eric Hartford <[email protected]>
Fixes #1363.
Root cause
lower_unwrap_or_method(andlower_unwrap_or_else_method,lower_option_flatten_method) in src/MirLower.w move the variant payload out of the materialized receiver temp on the success arm and leave that temp's scope-exit drop scheduled. A move out of a variant payload registers no reset-on-move (consume_moved_operandonly handles pure field paths;place_field_projection_countis -1 throughPK_DOWNCAST), so the enum drop glue frees the payload the result owns.Evidence (repro
let t = read_file(p).unwrap_or("")):_6 = move _4<as v0>.f0thendrop(_4) @ drop#9 scope-exit _4; drop planstate_before=Maybe action=conditional; IR calls__drop_struct_428(ptr %3)unconditionally.0x100068040freed at repro.w:4 (drop#9) and again at drop#17 (t).WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1+WITH_DEBUG_ALLOC_TRAP_FREE: first freedrop#enum __drop_enum_143at the unwrap_or line, thenDOUBLE FREE ... second_drop=drop#struct __drop_struct_96.Changes
retire_decomposed_carrier: shared by??(??on a Result/Option with an owned payload double-frees: the subject temporary's enum drop frees the payload after it moved out #1042's fix, refactored), unwrap_or, unwrap_or_else, flatten. The failure arm drops what is left once; the subject's own drop is retired.begin_lazy_arm/end_lazy_arm: the lazy fallback (§10) is framed like alower_ifbranch. Before,o ?? dleakeddon the success path.Tparam consumes (§3.8/D5); call sites already moved and blanked the argument. Before,(x: str) => 1leaked x, and unwrap_or_else's(_) => ""depended on the bug above.WITH_DEBUG_ALLOC=1printedleak count=0.Ownership/drop change: batch alone, with
:drop-auditand:move-audit.Matrix
552 runs under
WITH_DEBUG_ALLOC=1, each in its own process. The dimensions:??, match}??owned default leaked on the success pathA borrowed
&strdefault is rejected by Sema ("would need to copy astr"), as the §10 join requires. The 24 cells forunwrap_or_else× Vec × literal default were left out because they crash codegen: #1378.Local evidence (iterate tier, stage1 from this branch)
check src/main.wok (14.5s warm)New fixtures:
Full battery not run: draft until it is.
Filed along the way
unwrap_or_else((_) => Vec.new())crashes codegenif c: a else: bover the same owned strs reads "" — no diagnostic, no view #1380 a secondif c: a else: bover owned strs reads "" (no diagnostic, no view)audit:allfails on every??/unwrap_or (downcast place typing)say(&o.unwrap_or(Vec.new()))MIR lowering fails