Skip to content

Early return skips owning temporaries in outer statement frames #1172

Closed

Description

@ehartford

An early return from a loop over a temporary Vec leaks the iterable and its elements. This blocks leak-clean verification of the Conan source-manifest parser (#1166), independently of #1169.

Reduced with with reduce --contains 'leak count=3':

fn stop(text: &str) -> Result[i32, str]:
    for part in text.split(","):
        if part == "bad": return Err("bad")
    0
fn main:
    assert(stop("bad,held").is_err())

with run --debug-alloc reports three leaks: the two split strings and the vector. Expected: every owned temporary is released when its containing execution exits, including early returns (spec §2.4 temporary lifetimes and §13 iteration; no spec change).

Allocator route: the original parser's WITH_ALLOC_NO_REUSE=1 run retains 38 leaks. WITH_DEBUG_ALLOC_TRAP_FREE=4295457600 WITH_DEBUG_ALLOC_TRAP_ALLOC_HIT=1 under LLDB stops at str_split_vec_ref -> conan_parse_source_data -> bad for its first leaked string.

Exact compiler instruction proof on reduced stop (MIR sym330): LLDB stops at MirBuilder.lower_return + 336, the call to flush_stmt_temp_frame at src/MirLower.w:7934. There are two pending temporary locals [2, 4] and four frame start offsets [0, 0, 2, 2]. flush_stmt_temp_frame selects only the innermost start 2 and therefore emits no cleanup for either live outer temporary. emit_drops_for_return handles lexical drop scopes, not those outer statement frames, so the return bypasses their normal cleanup.

The repair must emit cleanup for all exited temporary frames without destructively removing frames needed by other CFG branches. Audit equivalent exits (return, ?, cancellation, labeled loop exits) and preserve moved return payloads, reset ordering, and borrow lifetimes. Do not rewrite the parser to introduce named locals as a workaround.

Evidence: out/with-get-investigation/for-temporary-return-frame-state.log, for-temporary-return-flush-lldb.log, conan-source-parser-leak-origin.log, for-temporary-return-leak.log, and for-temporary-return-reduce.log.

The isolated implementation includes all active statement temporaries and pending resets on function-exit edges without removing records needed by continuing branches. It covers explicit return, builtin ?, user-defined Try, and await cancellation.

The 14-case allocator matrix is green both with normal reuse and WITH_ALLOC_NO_REUSE=1. Before the change: return/builtin Try/user Try/cancellation each leaked 3 allocations, nested return leaked 6, and return during argument evaluation leaked 1. Normal branch/loop/argument paths plus break/continue were already clean and remain clean. Returned owned error payloads are checked. Evidence: stmt-exit-before-*.log, stmt-exit-after-*.log, stmt-exit-reuse-*.log, and return-temps-dev.log.

Further verification found two problems in the intermediate implementation:

  • The compiler audit caught five invalid drops in ?? return fallbacks. Reduced MIR shows coalesce-default drops the carrier, then function-exit cleanup drops it again because the carrier's cleanup records were retired only after lowering the default. Retire them before lowering that default. Evidence: return-temps-coalesce-{audit,mir}.log.
  • A defer reading a temporary iterable's current element, and a local ephemeral destructor borrowing that element, fail when temporaries are dropped before deferred/lexical cleanup. Native LLDB at 0x100000694 observes element 0x100068030 containing payload 4295393296 and length 3 immediately before its free; the deferred read at 0x100000744 sees zero/zero. The allocator's hit-1 address trap stops on that free. Compiler LLDB for sym330 shows lower_return+268 emits temporary cleanup before +276 emits defers. Evidence: return-temps-defer-{free-read,trap,lowering}-lldb.log.

The revised implementation records each temporary's ordinary-drop-stack position and merges the stacks in reverse creation order after defers. It preserves both defers and later locals' destructors before their temporary owners die. All 22 cases pass with zero leaks in normal and no-reuse modes, including Option/Result coalescing, defer/destructor reads, both Try errdefers and cancellation with a deferred read. The actual stage2 fixture, full build, focused coalesce audit, and 15-case move matrix pass. Final compiler audit, fixpoint, full suite, drop audit and last-green are still required before closing.

Related tool findings are tracked without exemptions: dense stage1 drop-state scaling (#1173), baseline std.sync analysis violations (#1174), analyzer accepting the destroyed-owner deferred read (#1175), and implicit-main analysis rejection (#1176).

Activity

  1. added 3 commits that reference this issue on Sep 19, 2026
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