Skip to content

Run every active statement temporary's cleanup on a function exit (#1172) - #1183

Merged
ehartford merged 1 commit into
mainfrom
fix-1172-return-temporary-cleanup
Sep 18, 2026
Merged

ehartford merged 1 commit into
mainfrom
fix-1172-return-temporary-cleanup

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Closes #1172. Ownership/drop-scheduling change, alone in its batch.

Bug

A function exit crosses every statement frame, but lower_return flushed only the innermost one. A loop over a temporary iterable whose body leaves the function leaked the iterable and everything it owned:

fn loop_return(text: &str) -> Result[i32, str]:
    for part in text.split(","):
        if part == "bad": return Err(part.clone())
    0

Allocator address trap: allocation site str_split_vec_ref. lldb at MirBuilder.lower_return+336 (the flush_stmt_temp_frame call): pending locals [2, 4], frame starts [0, 0, 2, 2] — flushing the last frame drops neither outer temporary. The same exit shape exists for builtin ?, user-defined Try, and await cancellation.

Fix (src/MirLower.w)

  • Each statement temporary records its depth in the local drop stack (stmt_temp_drop_depths). emit_drops_for_return merges the two stacks in reverse order, after defers, so a temporary owner outlives the locals, deferred reads and destructors that borrow from it. (An intermediate version dropped temporaries before defers: lldb showed the iterable freed at lower_return+268 before the defer at +276 read it.)
  • Exit paths call emit_pending_resets_since(0, 0, 0), which emits resets without popping records that sibling paths still need; the normal statement path keeps flush_pending_resets_since.
  • lower_match (and the if let that desugars to it) and ?? retire the subject's cleanup records before lowering arms. An arm can return before the join, and with exits now dropping temporaries the payload and its carrier were both dropped (lldb: two emit_drop_entry calls for local 330).

Evidence

test/behavior/behav_return_temporary_cleanup.w runs 30 modes of lib/temporary_exit_cases.w under --debug-alloc with WITH_ALLOC_NO_REUSE=1 and requires leak count=0: owned error payloads, nested loop returns, returns while evaluating arguments, both branch paths, normal completion, break/continue, builtin and user Try with and without errdefer, await cancellation with a deferred read, ?? on Option and Result, defer and destructor reads of the temporary owner, and match / if-let / named-subject early returns.

Control on main (c1e32920) vs this branch, same modes:

mode main this branch
return leak count=3 0
nested leak count=6 0
argument leak count=1 0
defer leak count=3 0
match-return, iflet-return 0 0 (guards against the double drop)

Battery (pinned seed v0.15.2.0, WITH=$PWD/src/main)

build rc=0 · :fixpoint rc=0 · :test rc=0 (1041 behaviour files) · :move-audit rc=0, all targets green · :drop-audit rc=0, all targets green · :test-green rc=0 · :last-green rc=0 · analyze … audit:all: 12,571 facts, 0 violations.

Tool gaps found during the hunt (filed, not fixed here)

#1173 drop-state matrix >7 GB on the unbundled regex body · #1174 use std.sync trips eight audit violations on the baseline · #1175 / #1177 the ownership audit passed a deferred read of a destroyed owner and a duplicate cleanup of a moved enum payload · #1176 analyze rejects implicit main.

A return, a builtin or user-defined ?, and an await cancellation cross every
statement frame, but lower_return flushed only the innermost one: a loop over
text.split(",") whose body returned leaked the iterable and its strings
(allocator trap: str_split_vec_ref; lldb at MirBuilder.lower_return+336 with
pending locals [2, 4] and frame starts [0, 0, 2, 2]).

Each statement temporary now records its depth in the local drop stack, and
emit_drops_for_return merges both stacks in reverse order after defers, so a
temporary owner outlives the locals and deferred reads that borrow from it
(lldb: the iterable was freed at lower_return+268 before the defer at +276).
Exit paths emit pending resets without popping records that sibling paths
still need.

A match (and the if-let it desugars from) and ?? retire the subject's cleanup
before lowering arms: an arm can return before the join, and the payload and
its carrier were both dropped (lldb: two emit_drop_entry calls for local 330).

30 modes under --debug-alloc with WITH_ALLOC_NO_REUSE=1. #1172
@ehartford
ehartford merged commit f71737c into main Sep 18, 2026
5 checks passed
ehartford added a commit that referenced this pull request Sep 19, 2026
…n release UAT green (#1191)

* Diagnose Windows package UAT check, build, and run stages on test failures

* Register translated function macros only after emission succeeds

LLDB on the OpenSSL 4.0.2 import observed ci_translate_macros mark OSSL_DEPRECATED emitted at CImport.w:3054, then record the same name untranslated. The stale registry entry authorized a dangling dependent global. Cover successful emission branches, omitted dependencies and equivalent expression forms. Compiler check and dev build pass; targeted positive and diagnostic tests pass.

* Capture Windows package hang stacks and preserve release investigation evidence

* Reject Clang recovery declarations in object macro probes

LLDB stopped ci_try_eval_var_init_for_type on a probe with a Clang error (severity 3); its returned initializer was void { 0, null }. Share parse-error validation with the main header parser and exclude invalid declarations from batched macro type results. Dev build and valid-sibling/used-omission regressions pass.

* Keep skipped and malformed tests out of known-issue verdict inversion

LLDB observed run_test_file_with_build_settings +348 branch on a skipped test status zero into the unexpected-pass diagnostic. The Darwin gate also compared runtime Macos with Darwin and returned false. Correct both contracts and add a cross-platform CLI verdict matrix. Compiler check and dev build pass; both reduced skip probes now return zero without executing their bodies. Full CLI matrix awaits rebuilt stage2.

* Allow isolated native package diagnosis from failed compiler artifacts

* Expose native Conan download failures in Windows diagnostics

* Preserve fresh Windows get failure before reproducing header hangs

* Translate constant macro calls before rejecting runtime invocations

LLDB offsetof-guard-lldb.log: ci_object_macro_is_function_call returns w0=1 for offsetof(with_offset_point_t, x), skipping the constant translator. The CI battery reproduced the existing offsetof fixture failure on all five platforms.

Verify: source check and seed-driven dev build pass; eight targeted macro and offsetof fixtures pass. Full stage-chain and package verification remain pending.

* Use supported launch-mode flags for native stack capture

ProcDump 12.01 rejects -k with -x before launching: Kill after dump is only valid with AeDebug Just-in-Time support (-i). Remove it from each capture; -n 3 bounds collection and the hosted job cleans up its children.

* Resolve install cache outputs through the execution path

LLDB on the pinned driver returned /Users/eric/with/$HOME/.local/... from build_cache_collect_output_paths; install execution resolves HOME instead. Reuse its destination resolver so a completed install can remain fresh. Covers relative, HOME, BINDIR and LIBDIR destinations, changed destinations, modified outputs and deleted outputs.

Validation: compiler source check and behav_build_cache_install_paths pass; the regression failed before the fix with stale: output missing: $INSTALL_BINDIR/artifact. Native evidence: out/with-get-investigation/wo-install-cache-output-lldb.log. Fixes #1157 for newly built drivers; the frozen seed retains its old implementation.

* Use native temporary paths and retain Conan tool diagnostics

LLDB in conan_curl_to_file received /tmp/with-conan-http-99953.json from conan_http_get. Windows native curl independently returned HTTP 200 then failed to open that missing drive-root directory. Use TMP/TEMP on Windows and TMPDIR on POSIX, with per-request scratch directories and cleanup. Capture curl, tar and source compiler output in real files and report it instead of redirecting to a POSIX-only null device.

Validation: compiler source check; offline Conan transport and recipe metadata tests. Transport covers spaces, successful reads, failed downloads, cleanup and an unusable temporary directory. Windows-only unset-temp coverage runs in CI. Evidence: out/with-get-investigation/conan-http-temp-lldb.log and windows-bzip2-native-download-text.log. Refs #1162.

* Compare Mesa DLL copies under both Windows pinned seeds

Add isolated test-channel diagnostics for the exact Mesa DLL bytes copied through ToolFs by the pinned evaluator. Preserve original and copied artifacts and compare their hashes, sizes and file formats. The same action preserves all bytes under the Darwin pinned seed in native and interpreted modes; Windows evidence is still needed.

Validation: local copy action on the 56 MB x64 Mesa DLL, SHA-256 equal in both modes; tools/bump_seed_pins.w --check passes.

* Make C macro collection scale with header size

Windows native dumps stop in ci_collect_object_macro_values while copying a 580692-byte prefix at macro 15517 of 33367. Append table entries with builders. Native Darwin debugging additionally identified c_import_decode_escapes +472 copying each accumulated inline header and macro_source_line_from_cursor +216 reopening and scanning the entire header per definition. Decode with a builder and read each logical definition directly from Clang-owned contents and offsets.

Splice C backslash-newline before parsing a macro definition: LLDB observed an unspliced continued IDENTITY macro entering macro_session_add_from_define_line, while the single-line spelling passes. Cover LF, CRLF, split names/directives and the last line without a newline.

Validation: compiler source check, standalone bootstrap bridge, stage1 build, eight existing macro regressions and the new source-lines regression. Cold 33000-macro C import improves from 45990.103 ms to 326.392 ms. Large dependency-table fixture awaits the full stage chain. Native evidence is recorded in docs/with-get-release-investigation.md and out/with-get-investigation/macro-source-read-symbol-lldb.log. Refs #1163.

* Record macro scaling, transport and cache root evidence

* Reproduce the UAT external DLL path in Windows copy diagnostics

Relative copies preserve all bytes under both Windows seeds. Also exercise the external absolute path actually supplied by the UAT. A local pinned-seed LLDB trace resolves D:/a/_temp/mesa/opengl32.dll as <project>/D:/a/_temp/mesa/opengl32.dll, and the unchecked read then writes a zero-byte success. Preserve relative and external-path outputs separately. Refs #1164.

* Preserve file read failures and declare the Windows Mesa input

Native and interpreted ToolFs copy/read_binary now check read status before writing. Missing or directory sources fail and preserve existing destinations; readable empty and binary files remain valid.

LLDB shows the old unchecked reader returning length zero to eval_toolfs_capability_method for missing.dll. Windows run 35202995832 reproduces a zero-byte Mesa DLL under both pinned seeds for the external drive path. Stage2 passes the sixteen-case matrix and exact 58 MB DLL copies; the seed accepts the declared project-relative UAT input.

* Report missing Linux link libraries and provision graphics UAT dependencies

* Consume the payload transferred by implicit Result tail wrapping

The implicit Ok aggregate in lower_fn_with_sig replaced its result operand
without consuming it, so the body frame freed an owned if/match join payload.
The allocator address trap observes source_yaml_scalar freeing the returned
buffer; LLDB at lower_fn_with_sig+6224 observes the missing consume at the
aggregate assignment (result-tail-wrap-live-lldb.log).

Consume that operand before body cleanup and retain returned strings, vectors,
and aggregate payloads across subsequent allocations in the regression.

Verified seed-driven full build, fixpoint, all tests, and last-green; compiler
audit: 2,528,140 facts and zero violations; move audit: 15 PASS, zero DIFF;
drop audit: 136 PASS, zero regressions; stage2 regression: zero allocator leaks.
The validator blind spot is separately tracked in #1170.

Fixes #1169

* Index macro values and private dependency lookups

Windows bzip2/libcurl native dumps show repeated linear scans through the
1,120,240-byte macro registry during constant initializer translation.
Use keyed value/miss maps and a per-session last-definition index. Expand
private dependencies before C expression parsing for imports as well as
migration, preserving precedence and raw bitwise-or values.

Proof: ci-35205173022-{bzip2-lldb,macro-lookup-disassembly,lookup-memory}.log;
macro-private-expression-return-lldb.log observes the omitted value branch.
Validation: seed-driven build, fixpoint, full test suite and last-green;
compiler audit 2,528,011 facts with zero violations; expanded 33,000-macro
regression and six related fixtures; actual Darwin bzip2/libcurl UAT runs.
Native Windows UAT remains required before closing its timeout finding.

* Use the platform linker for native Linux user programs

The ordinary cc link path forced -fuse-ld=lld, making clean release hosts
depend on a separately installed LLVM linker. Retain platform-compatible
flags and leave compiler/cross LLVM link plans intact. Add a fixture whose
PATH contains only cc, as, ld and nm.

Native GDB at with_exec_argv proves the injected flag; strace proves the
missing ld.lld lookup. Native Linux arm64 full build, stage1/stage2 clean
PATH fixture and release one-liner pass. Missing GL/X11 errors give the
package instructions; the unchanged program links after provisioning.

Fixes #1167

* Preserve Windows library basenames in Conan link metadata

COFF .lib files use their literal basename; only Unix library lookup strips
the lib prefix. The OpenSSL package contains libcrypto.lib and libssl.lib,
but conan_library_name_from_path returned crypto and ssl.

Native LLDB proves the wrong name.slice(3, ...) return at ConanClient.w:543.
The 12-case library-name matrix passes, covering COFF and Unix names.
Real Windows package UAT remains part of release verification.

Fixes #1171

* Record the #1172 root cause and the campaign's state after D43, #1183 and #1184

* Handoff: darwin release UAT green on the combined branch; D44, build speed, next steps

---------

Co-authored-by: Eric Hartford <[email protected]>
@ehartford
ehartford deleted the fix-1172-return-temporary-cleanup branch September 24, 2026 16:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Early return skips owning temporaries in outer statement frames

1 participant