Repository navigation
FileSink: remove Windows UAF diagnostic probes - #32474
Conversation
FileSink::deinit on Windows captured and symbolicated a full backtrace on every destruction (Backtrace::force_capture().to_string()), which forces dbghelp symbol resolution. In standalone-executable builds this segfaults inside std::backtrace_rs::dbghelp::resolve when dbghelp touches an unloaded module during teardown (7 Sentry events on 1.4.0+324c5f01 Windows x64). These probes were forensic instrumentation for a refcount bug that has since been root-caused. Remove them: - magic field and FILESINK_LIVE/FILESINK_DEAD poison constants - FREED_AT backtrace map and its lock/format!/to_string in deinit - FileSink__assertLive extern fn and its calls from generate-jssink.ts - finalize() magic check and Strong-corruption field probe LIVE_COUNT remains; it is the leak-test counter exposed via bun:internal-for-testing, not diagnostic instrumentation.
|
Updated 1:28 AM PT - Jun 18th, 2026
❌ @dylan-conway, your commit 8368ff2 has 4 failures in
🧪 To try this PR locally: bunx bun-pr 32474That installs a local version of the PR into your bun-32474 --bun |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughRemoves the Windows-only FileSink use-after-free detection probe—the ChangesFileSink UAF probe and diagnostic removal
Remove debug raw pointer accessors
Build configuration and test limit cleanup
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
The Strong-corruption probe removed from FileSink::finalize was the only caller of readable_stream::Strong::held_handle_ptr, JSPromise::Strong::handle_ptr, and strong::Optional::handle_ptr. All three were pub/doc(hidden) so the dead-code lint does not flag them.
|
Build 63260 on 220d885 (main merged in) completed: 285 pass / 1 fail. All 34 Windows jobs passed (builds + all test shards on x64, x64-baseline, aarch64). The Azure The single failure is Ready for review. |
…troy Both assertions were forced on in Windows release builds for the FileSink refcount investigation and carried 'remove once root-caused' instructions. Convert to debug_assert to match non-Windows and the existing increment() overflow check.
Cargo.toml claimed the Windows release link was temporarily /OPT:NOICF at flags.ts:778 with a 'restore /OPT:SAFEICF once root-caused' instruction, but flags.ts:1002 is already /OPT:SAFEICF. Keep only the durable panic=abort and SAFEICF rationale.
Removing the #[allow(dead_code)] held_handle_ptr probe helper dropped ReadableStream.rs to 0 escapes; regenerate the ratchet inventory.
There was a problem hiding this comment.
All prior feedback addressed (handle_ptr helpers, || cfg!(windows) gates, NOICF comments, dead-code-escape ratchet) and no new issues found — deferring only because this removes ~290 lines across refcount / GC-finalizer / Strong::destroy paths and changes the Windows FileSink struct layout, while the Windows test lanes still haven't run past Azure provisioning on 6ee4d10.
Extended reasoning...
Overview
Pure-removal cleanup of the #53265 Windows UAF forensic probes now that the underlying refcount bug is reported root-caused. Touches 9 files: FileSink.rs (drops the #[cfg(windows)] magic field, FREED_AT backtrace map, FileSink__assertLive export, the finalize() magic/Strong-corruption probe blocks, and the deinit() backtrace-capture block), generate-jssink.ts (drops the matching extern "C" decl and constructor call sites), Strong.rs/raw_ref_count.rs (restore debug_assert! parity by dropping the || cfg!(windows) release gates), three handle_ptr/held_handle_ptr helper deletions, comment-only edits in Cargo.toml/flags.ts, and the dead-code-escape ratchet update. Net: ~290 lines removed, ~6 added; non-Windows codegen is unchanged except for the two assert!→debug_assert! conversions.
Security risks
None identified. No new code paths are introduced; auth/crypto/permissions are untouched. The only behavioral change is that two cheap defensive asserts (Strong<Impl>* small-pointer floor, refcount-underflow) move from always-on-on-Windows back to debug-only — that restores pre-probe behavior and matches every other platform, so it is a deliberate hardening rollback rather than a new exposure.
Level of scrutiny
Medium-high. Although every hunk is subtractive and self-contained, the surrounding code is memory-safety-critical: FileSink::finalize/deinit run during GC sweep and free the allocation, RawAtomicRefCount::decrement gates destruction, and Strong::Impl::destroy hands a raw pointer to C++. Removing the #[cfg(windows)] magic field changes FileSink's Windows layout (harmless — the struct is not #[repr(C)] and C++ only holds it as an opaque void*, but worth a human glance). The Rust export and both C++ call sites of FileSink__assertLive are removed together, so no link mismatch.
Other factors
I've reviewed this PR four times; each round of feedback was promptly addressed (840a554, 2094b62, e712d45, and now 6ee4d10 for the ratchet JSON). The bug-hunting system found nothing on this revision. cargo check and filesink.test.ts pass per the description. The remaining unknown is that the Windows test runners are still blocked on Azure GalleryImageNotFound provisioning, so the final commit has no Windows test signal — given the diff is Windows-layout-affecting, a human sign-off seems prudent before merge.
There was a problem hiding this comment.
LGTM — clean removal of the temporary #53265 probe instrumentation; all prior feedback addressed and Windows CI is green.
Extended reasoning...
Overview
This PR removes Windows-only forensic instrumentation that was added to root-cause a FileSink UAF (#53265). The deletions span: the magic poison field, FREED_AT backtrace map, and FileSink__assertLive extern (FileSink.rs + generate-jssink.ts); the || cfg!(windows) always-on assert gates in raw_ref_count::decrement and Strong::Impl::destroy (restored to debug_assert!); the orphaned handle_ptr/held_handle_ptr helpers in JSPromise.rs/Strong.rs/ReadableStream.rs; stale NOICF/#53265 comment paragraphs in Cargo.toml and flags.ts; and the dead-code-escape-limits ratchet entry. Every hunk is a deletion or comment trim — no new logic.
Security risks
None. This removes diagnostic instrumentation (backtrace capture, magic-value checks, debug accessors) rather than adding any surface. The debug_assert! conversions restore Windows release builds to the same behavior as Linux/macOS release — they do not weaken any check that exists on other platforms.
Level of scrutiny
Moderate-to-low. While the touched files are memory-management-adjacent (refcount, Strong, finalize/deinit), every change is removing code that was explicitly marked temporary ("Remove once root-caused"). The one semantic change — dropping always-on Windows release asserts back to debug-only — restores the documented pre-probe state and matches the increment() overflow check's existing pattern. The #[cfg(windows)] magic: Cell<u32> field removal changes FileSink's Windows layout, but nothing outside the deleted probe code referenced it.
Other factors
I left four rounds of inline feedback on earlier revisions (orphaned helpers, stale assert gates, stale Cargo.toml/flags.ts comments, ratchet inventory), all of which were addressed and resolved. Build 63249 on 6ee4d10 ran green on all 8 Windows aarch64 test shards and all 9 Windows build jobs; dead-code-escapes.test.ts passes; the 3 darwin failures are unrelated infra flakes (puppeteer download, Docker Hub 429, R2/pty timeouts). The bug hunting system found nothing on this run. LIVE_COUNT (the leak-test counter) is correctly retained.
…fix stale FileSink rc-accounting comments PipeWriter.rs, Blob.rs, Sink.rs still carried CI-build-number references (#53265/#53485/#53781), commit hashes, and NOALIAS_HUNT tags from the debugging campaign. Strip them, keeping only the durable noalias rationale. In FileSink.rs, fix two factually-wrong comments left by the earlier pass: the finalize() doc claimed assign_to_stream takes a per-wrapper +1 (it does not — only to_js/to_js_with_destructor do), and the assign_to_stream controller-ref comment still referenced the reverted df4f2c4 by hash. Strong.rs: use debug_assert! instead of if-cfg-assert (idiomatic; same codegen).
Two tests using fileSinkInternals.liveCount() under Bun.gc(true) pressure: one for Bun.file(fd).writer() (the fs.promises.writeFile async-iterator path), one for Bun.file(path).writer() (owns_fd). Both verify the FileSink LIVE_COUNT returns to baseline after the wrapper is collected — guards against both leak (rc never reaches 0) and over-deref (rc reaches 0 early, which the borrow=ptr fix in 116f9c7/e1187bb addressed).
|
Root-cause bisect proof for why this is safe to remove (the original UAF is fixed; the probe is now the crash source):
Mechanism: with The crashes still landing in Sentry on commits after Pushed two follow-up commits: remaining breadcrumb cleanup in PipeWriter/Blob/Sink + a stale-comment fix in FileSink, and |
) Follow-up to #39326, where @alii asked how we make sure building std without its `backtrace` feature stays safe. The verification itself is written up in #39326 (comment); this PR turns the two invariants it rests on into checks. ### Problem - #39326 passes `-Zbuild-std-features=panic-unwind,default` to release builds, so `std::backtrace::Backtrace` now captures frames it cannot symbolize on the unix targets (std's vendored backtrace crate selects its noop symbolizer when the feature is off), and `RUST_BACKTRACE` no longer does anything. - That is fine today because nothing in the workspace uses `std::backtrace` (the last use, a FileSink probe, went away in #32474), but nothing stopped a new use from coming back and quietly printing bare addresses. - Nothing pinned which build configurations get the flag; the `cfg.release && !cfg.asan` gate in scripts/build/rust.ts:429 was untested. ### Fix - clippy.toml: add `std::backtrace::Backtrace` to `disallowed-types`. The workspace sets `disallowed_types = "deny"` and the rust-lints workflow runs clippy on every PR touching `src/**/*.rs` or clippy.toml, so a new use fails CI with a message pointing at the build flag and at `bun_core::dump_current_stack_trace`. - test/internal/source-lints/build-rust.test.ts: assert the exact `-Zbuild-std*` args per configuration. Release gets `-Zbuild-std=... -Zbuild-std-features=panic-unwind,default` on linux gnu/musl/android, darwin, windows, freebsd x64 and the tier 3 freebsd aarch64; release-asan, debug-asan and tier 3 debug get bare `-Zbuild-std`; plain debug gets neither. - Verified: - `bun test test/internal/source-lints/` (the documented way to run this directory; it never touches the built binary): 172 pass. Also ran build-rust.test.ts through `bun bd test`. - With scripts/build/rust.ts taken from the commit before #39326, the first new test fails; with the `!cfg.asan` guard removed, the second one fails. - The clippy entry was checked against a scratch crate containing `std::backtrace::Backtrace::force_capture()` inline (the shape the FileSink probe had), `use std::backtrace::Backtrace;`, the type in a signature and `Backtrace::capture()`: all four are reported as errors. Scratch code not included. - `cargo clippy -p bun_core -p bun_ptr -p bun_crash_handler --no-deps` is clean with the new entry locally, and the rust-lints workflow's full-workspace `cargo clippy` passed on this PR, so the entry does not fire on any existing code. - Nothing under src/ changes. The test pins scripts/build/rust.ts and the clippy entry is checked by the rust-lints workflow, so the fail/pass evidence for this PR is the pre-#39326 rust.ts run above, not a src diff. The comments at src/bun_core/Global.rs:155 and src/ptr/ref_count.rs:24 still describe a "std::backtrace fallback" that is not in the tree; left for a separate cleanup to keep this PR to the checks. ### Background - `-Zbuild-std` makes cargo compile std from source as part of the build; `-Zbuild-std-features` chooses std's cargo features. Cargo's default set is `panic-unwind,backtrace,default`, and `backtrace` is what compiles the in-process symbolizer (gimli, addr2line, object, miniz_oxide) into std for `std::backtrace` and the default panic hook's `RUST_BACKTRACE` output. - bun never relies on either: `bun_crash_handler::init()` installs its own panic hook as the first thing `main` does, and that hook captures frames with a frame pointer walk and emits a trace string that bun.report symbolizes out of process. - clippy's `disallowed-types` is the repo's existing mechanism for banning specific std items (`std::fs::File`, `std::sync::Mutex`, ...); `disallowed_types` is set to `deny` in the workspace lints, so an entry there is a CI failure, not a warning. <!-- robobun:evidence:begin --> --- **[stamp-90s]** gate passed · iteration 2 · 2 files touched <details><summary>passes on PR (with fix)</summary> ```console Test-only change. Debug/ASAN (expected pass): $ bun bd test 'test/internal/source-lints/build-rust.test.ts' $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/internal/source-lints/build-rust.test.ts bun test v1.4.0 (8326d1b) test/internal/source-lints/build-rust.test.ts: (pass) allRustTargets > is exactly the set of triples .buildkite/ci.mjs builds [31.94ms] (pass) allRustTargets > rust-toolchain.toml preinstalls std for exactly the triples that have a prebuilt one [10.30ms] (pass) allRustTargets > a Tier 3 target builds std from source with the flag rust:check-all shares [101.89ms] (pass) build-std feature set > release builds drop std's `backtrace` feature on every shipped platform family [183.79ms] (pass) build-std feature set > builds that rebuild std for other reasons keep cargo's default feature set [77.06ms] (pass) CPU baseline > arm64 linux, freebsd and windows assume armv8-a+crc tuned for Ampere, like the C++ side [71.72ms] (pass) CPU baseline > arm64 android assumes armv8-a+crc tuned for Cortex-A78, like the C++ side [23.69ms] (pass) CPU baseline > darwin arm64 and x64 name the C++ side's CPU model directly [62.14ms] 8 pass 0 fail 29 expect() calls Ran 8 tests across 1 file. [4.10s] Exit: 0 ``` </details> <details><summary>diff hotspot</summary> ``` clippy.toml | 1 + test/internal/source-lints/build-rust.test.ts | 38 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) ``` </details> **gate history** · 1 passed · 1 rejected · iteration 2 <details><summary>evidence per changed file</summary> ``` file reads edits tests clippy.toml 1 1 0 test/internal/source-lints/build-rust.test.ts 2 2 0 ``` </details> <!-- robobun:evidence:end -->
Problem
FileSink::deinit()on Windows captured and symbolicated a full backtrace on every destruction:.to_string()forcesstd::backtrace_rs::symbolize::dbghelp::resolve, which takes the process-wide dbghelp lock and walks loaded modules. In standalone-executable builds on Windows x64 this segfaults when dbghelp touches an unloaded module / freed region during teardown (heap address with a constant0x25000page offset, varying base).Re-symbolicated stack (see #32468 for why bun.report showed the wrong names):
7 events in ~25 minutes from Windows x64 standalone-executable builds on
1.4.0+324c5f01. Sentry: https://bun-p9.sentry.io/issues/7558990692/Beyond the crash, this also took a mutex, heap-allocated two strings, and ran dbghelp on every single FileSink destruction in Windows release builds, and the
FREED_ATmap was never pruned so it leaked every recorded backtrace for the life of the process.Fix
These were forensic probes for a refcount bug that has since been root-caused. Remove all of it:
magic: Cell<u32>field andFILESINK_LIVE/FILESINK_DEADpoison constantsFREED_ATbacktrace map and the lock/format!/force_capture().to_string()indeinitFileSink__assertLiveextern fn (bothcfgarms) and its calls from the generatedJSFileSink/JSReadableFileSinkControllerconstructors ingenerate-jssink.tsfinalize()magic check and the Strong-corruption field probe|| cfg!(windows)release-build assert gates inraw_ref_count::decrementandStrong::Impl::destroy(restored todebug_assert!)handle_ptr/held_handle_ptrprobe helpers onstrong::Optional,JSPromise::Strong, andreadable_stream::StrongLIVE_COUNTstays; it is the leak-test counter exposed viabun:internal-for-testing, not crash instrumentation.Verification
cargo check -p bun_runtimeon host and--target x86_64-pc-windows-msvc: cleanbun bd test test/js/bun/util/filesink.test.ts: 42 passJSSink.h/JSSink.cppno longer referenceFileSink__assertLiveNo new test: the segfault is Windows-only, inside dbghelp, and requires module-unload timing in a standalone executable; there is no deterministic repro on CI. Existing FileSink tests cover the create/destroy path on the Windows lanes.