Skip to content

FileSink: remove Windows UAF diagnostic probes - #32474

Merged
dylan-conway merged 10 commits into
mainfrom
farm/e4add521/filesink-deinit-backtrace
Jun 18, 2026
Merged

dylan-conway merged 10 commits into
mainfrom
farm/e4add521/filesink-deinit-backtrace

Conversation

@robobun

@robobun robobun commented Jun 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

FileSink::deinit() on Windows captured and symbolicated a full backtrace on every destruction:

m.insert(
    this as usize,
    state + &std::backtrace::Backtrace::force_capture().to_string(),
);

.to_string() forces std::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 constant 0x25000 page offset, varying base).

Re-symbolicated stack (see #32468 for why bun.report showed the wrong names):

FileSink::deinit (FileSink.rs:1302)
  alloc::string::to_string / Result::expect
  std::backtrace_rs::symbolize::dbghelp::resolve
  dbghelp::init / dbghelp::set_optional_options
  std::backtrace::helper::lazy_resolve::{closure}
  std::sync::lazy_lock::LazyLock::force
  Once::call_once_force
  std::backtrace::impl$6::fmt
  sys::sync::once::futex::Once::call

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_AT map 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 and FILESINK_LIVE/FILESINK_DEAD poison constants
  • FREED_AT backtrace map and the lock/format!/force_capture().to_string() in deinit
  • FileSink__assertLive extern fn (both cfg arms) and its calls from the generated JSFileSink / JSReadableFileSinkController constructors in generate-jssink.ts
  • finalize() magic check and the Strong-corruption field probe
  • the || cfg!(windows) release-build assert gates in raw_ref_count::decrement and Strong::Impl::destroy (restored to debug_assert!)
  • the now-orphaned handle_ptr/held_handle_ptr probe helpers on strong::Optional, JSPromise::Strong, and readable_stream::Strong
  • stale probe-referencing comments and a dangling diagnostic header

LIVE_COUNT stays; it is the leak-test counter exposed via bun:internal-for-testing, not crash instrumentation.

Verification

  • cargo check -p bun_runtime on host and --target x86_64-pc-windows-msvc: clean
  • bun bd test test/js/bun/util/filesink.test.ts: 42 pass
  • generated JSSink.h/JSSink.cpp no longer reference FileSink__assertLive

No 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.

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.
@robobun

robobun commented Jun 17, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:28 AM PT - Jun 18th, 2026

❌ @dylan-conway, your commit 8368ff2 has 4 failures in Build #63290 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32474

That installs a local version of the PR into your bun-32474 executable, so you can run:

bun-32474 --bun

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Removes the Windows-only FileSink use-after-free detection probe—the magic field, FILESINK_LIVE/FILESINK_DEAD constants, FREED_AT registry, and FileSink__assertLive export—from FileSink.rs and stops the code generator from emitting corresponding C++ declarations and calls. Weakens conditional runtime asserts to debug-only checks in Strong and RefCount types. Removes debug-only raw pointer accessors from JSPromise.Strong, Strong.Optional, and ReadableStream.Strong. Cleans up Windows diagnostic comments in build configuration.

Changes

FileSink UAF probe and diagnostic removal

Layer / File(s) Summary
Remove Rust probe infrastructure and Windows field
src/runtime/webcore/FileSink.rs
Removes magic: Cell<u32> from the FileSink struct, deletes FILESINK_LIVE/FILESINK_DEAD constants and the FREED_AT backtrace registry, and removes the exported FileSink__assertLive function (including the non-Windows stub). Strips the magic-must-be-first check from finalize(), removes the state-snapshot and magic-poisoning code from deinit(), removes magic initialization from default_fields(), and updates associated diagnostic comments.
Remove generated C++ extern declarations and constructor calls
src/codegen/generate-jssink.ts
Stops emitting the FileSink__assertLive(sinkPtr) call from the generated JS${name} and JSReadable${name}Controller constructors, and removes the extern "C" declaration for FileSink__assertLive from the generated JSSink.h and JSSink.cpp templates.
Weaken conditional asserts to debug-only checks
src/jsc/Strong.rs, src/ptr/raw_ref_count.rs
Changes the corruption-pointer validation in Strong::Impl::destroy from a `cfg!(debug_assertions)

Remove debug raw pointer accessors

Layer / File(s) Summary
Remove raw pointer accessors from Strong types
src/jsc/JSPromise.rs, src/jsc/Strong.rs, src/runtime/webcore/ReadableStream.rs
Removes the doc-hidden handle_ptr(&self) -> *const () debug accessor from JSPromise.Strong, removes the handle_ptr(&self) -> *const () debug accessor from Strong.Optional, and removes the pub(crate) doc-hidden held_handle_ptr(&self) -> *const () accessor from ReadableStream.Strong.

Build configuration and test limit cleanup

Layer / File(s) Summary
Update Windows diagnostic and linker comments; update dead-code limits
Cargo.toml, scripts/build/flags.ts, test/internal/dead-code-escape-limits.json
Replaces the multi-line comment explaining Windows .pdata/.xdata padding rationale with a shorter note in Cargo.toml. Removes the multi-line comment block about Windows /OPT:NOICF investigation from scripts/build/flags.ts. Updates test/internal/dead-code-escape-limits.json by removing the ReadableStream.rs entry and setting the posix_spawn.rs limit to 4.

Suggested reviewers

  • Jarred-Sumner
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title "FileSink: remove Windows UAF diagnostic probes" directly and accurately summarizes the main change—removal of Windows-specific crash diagnostic instrumentation from FileSink.
Description check ✅ Passed The PR description includes all required template sections: "Problem" (explains the crash and performance issue), "Fix" (itemizes all changes), and "Verification" (documents testing approach and results). The description is comprehensive and detailed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread src/runtime/webcore/FileSink.rs Resolved
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.
@robobun

robobun commented Jun 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

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 GalleryImageNotFound issue from earlier builds is resolved and the diff now has full Windows test coverage. Binary size: Windows -41 to -44 KB, non-Windows ±0 KB.

The single failure is test-docker-build-debian.ts on darwin 14 aarch64: Docker Hub 429 Too Many Requests rate limit, unrelated to this diff.

Ready for review.

Comment thread src/runtime/webcore/FileSink.rs Resolved
…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.
Comment thread src/runtime/webcore/FileSink.rs Resolved
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.
Comment thread src/runtime/webcore/ReadableStream.rs Resolved
Removing the #[allow(dead_code)] held_handle_ptr probe helper dropped
ReadableStream.rs to 0 escapes; regenerate the ratchet inventory.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).
@dylan-conway

Copy link
Copy Markdown
Member

Root-cause bisect proof for why this is safe to remove (the original UAF is fixed; the probe is now the crash source):

Build borrow= mode fs-promises-writeFile-async-iterator.test.ts
a6a3bae26c0 (last CI crash, build #53852) mut crashes deterministically, iteration 1
a6a3bae26c0 + cherry-picked 116f9c7+e1187bb+c69582a ptr 50/50 clean
a6a3bae26c0 reverted back mut crashes again, iteration 1
current main ptr 200+/200+ clean (bun-profile.exe)

Mechanism: with borrow=mut the macro expanded to (&mut *parent_ptr).on_write(...) — the &mut FileSink parameter gets LLVM noalias. The WindowsStreamingWriter is a field inside FileSink, so under Stacked Borrows the writer's *mut Self (held by on_write_complete) has its tag popped when the &mut FileSink Unique tag is placed. After on_write returns, the scopeguard's r_deref(this) reads (*this).parent through the invalidated tag → UB → with panic="abort" + LTO, LLVM exploits it. borrow=ptr (already on main since e1187bb0c4e) passes *mut FileSink with no noalias, so the writer's tag stays valid.

The crashes still landing in Sentry on commits after e1187bb are the probe's Backtrace::force_capture().to_string() → dbghelp resolve, which runs on every Windows FileSink teardown — exactly what this PR removes.

Pushed two follow-up commits: remaining breadcrumb cleanup in PipeWriter/Blob/Sink + a stale-comment fix in FileSink, and liveCount-based GC-stress regression tests.

Jarred-Sumner pushed a commit that referenced this pull request Aug 17, 2026
)

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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants