Skip to content

webcore: free Blob's owned content type on drop - #31358

Merged
Jarred-Sumner merged 6 commits into
mainfrom
claude/hardening-fix-pre-110-blob-dupe-and-getstream-small-leaks
May 25, 2026
Merged

Jarred-Sumner merged 6 commits into
mainfrom
claude/hardening-fix-pre-110-blob-dupe-and-getstream-small-leaks

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Blob kept its content type as a raw slice pointer plus an ownership flag, with no drop glue. Consumers that drop a duplicated Blob by value (the file read handler, PathOrBlob, BlobOrStringOrBuffer, AnyBlob, the object-URL registry) relied on an explicit deinit() that several of them never call, so the heap copy made by dupe_with_content_type was stranded on every Bun.file(p, { type }).text() and similar paths.

This adds impl Drop for Blob that frees an owned content type, makes borrowed_view() return a self-owning dupe() instead of aliasing the source's allocation (which would double-free under the new Drop), and hoists the deep copy in dupe_with_content_type ahead of construction. The remaining Blob { .., ..Default::default() } literals are spelled out since functional-record-update is rejected for Drop types.

Adds three tests to test/js/web/fetch/blob.test.ts: an RSS regression test for repeated .text() on a file handle with a large custom type, and two behavioral tests confirming the source handle's type survives reads and Bun.write. Existing content-type ownership tests in that file still pass.

Blob stored its content type as a bare raw slice pointer with an
ownership flag but no drop glue, so any code path that dropped a Blob by
value instead of calling deinit() stranded the heap copy made by
dupe_with_content_type and the other allocating constructors.

Add a Drop impl that releases an owned content type, make borrowed_view
return a self-owning dupe instead of aliasing the source allocation, and
hoist the deep copy in dupe_with_content_type ahead of construction so
no transient value claims the source's buffer. Convert the remaining
functional-record-update Blob literals, which Drop disallows.

Adds regression coverage for repeated reads of a typed file handle and
for content-type preservation across read and write paths.
@robobun

robobun commented May 24, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 11:21 PM PT - May 24th, 2026

✅ @Jarred-Sumner, your commit daa90e97f86536dead7b5ca96c5ed8be44f353c0 passed in Build #57833! 🎉


🧪   To try this PR locally:

bunx bun-pr 31358

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

bun-31358 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Memory leak with file uploads #18608 - Memory leak with file uploads: a Bun developer confirmed the allocation occurs when a Blob is created for the fetch request body. The reproduction involves creating File objects with { type: "text/plain" } and uploading via FormData/fetch — exactly the dupe_with_content_type leak path this PR fixes.

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #18608

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Jarred-Sumner, we couldn't start this review because you've used your available PR reviews for now.

Your plan includes 5 reviews of capacity. Refill in 27 minutes and 26 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more review capacity refills, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 523b22ba-8a7d-4fe3-8658-a0f1f006b71d

📥 Commits

Reviewing files that changed from the base of the PR and between a160948 and daa90e9.

📒 Files selected for processing (10)
  • src/jsc/webcore_types.rs
  • src/runtime/jsc_hooks.rs
  • src/runtime/node/types.rs
  • src/runtime/server/FileRoute.rs
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/Body.rs
  • src/runtime/webcore/ByteBlobLoader.rs
  • src/runtime/webcore/ObjectURLRegistry.rs
  • src/runtime/webcore/blob/read_file.rs
  • test/js/web/fetch/blob.test.ts

Walkthrough

Refactors Blob initialization to use Blob::default() + explicit Cell assignments, makes borrowed_view() return dupe(), pre-copies heap content_type during duplication, and adds impl Drop for Blob so heap-allocated content_type is freed on by-value drops. Tests validate content-type ownership across read/dup/write paths.

Changes

Blob Ownership Refactor

Layer / File(s) Summary
Blob struct initialization and Drop implementation
src/jsc/webcore_types.rs
Blob::init_with_store, init, and init_empty now build from Blob::default() then set Cell fields explicitly. Blob::borrowed_view() returns self.dupe(). Blob::dupe_with_content_type() pre-copies heap content_type when allocated. Blob::deinit() docs updated and impl Drop for Blob added to call free_content_type() on by-value drops.
Apply refactored initialization in Blob factory methods
src/runtime/webcore/Blob.rs
Factory methods init_with_all_ascii, create_with_bytes_and_allocator, and from_js_without_defer_gc use Blob::default() + explicit Cell setting; early-return paths now use Blob::init_empty(global). Write-path and locked-body comments updated to reflect borrowed_view() => dupe() ownership and cleanup timing.
Drop-based cleanup and deallocation
src/runtime/jsc_hooks.rs, src/runtime/webcore/ObjectURLRegistry.rs, src/runtime/server/FileRoute.rs, src/runtime/webcore/blob/read_file.rs, src/runtime/webcore/Body.rs, src/runtime/webcore/ByteBlobLoader.rs
Removed out-of-band content_type frees in favor of Blob's Drop glue. vm_loader_ctx::blob_deinit and several comment blocks updated to describe Drop-based teardown order and deinit() idempotency; Body/Any docs updated to match.
Regression tests for content-type ownership
test/js/web/fetch/blob.test.ts
Test harness import extended to include isASAN. New regression tests spawn Bun to repeatedly read typed file-backed Blobs, force GC, measure RSS delta for leaks with ASAN-aware thresholds, verify repeated reads don't free source content-type, and check Bun.write() preserves custom content type on destination blobs.
Node runtime comments
src/runtime/node/types.rs
Reworded safety/ownership comments in BlobOrStringOrBuffer Drop and PathOrBlob::from_js_no_copy to clarify borrowed vs duplicated semantics; no behavioral changes.

Possibly related PRs

  • oven-sh/bun#30955: Fixes borrowed_view()'s name cloning to avoid refcount over-dereference during borrowed-blob flows; closely related to borrowed_view/dupe semantics changed here.

Suggested reviewers

  • dylan-conway
  • RiskyMH
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, solution, and adds three tests, but does not follow the repository's required template with 'What does this PR do?' and 'How did you verify your code works?' sections. Restructure the description to follow the required template with explicit 'What does this PR do?' and 'How did you verify your code works?' sections, while preserving the detailed technical content already provided.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the primary change: implementing a Drop impl for Blob to properly free owned content types, which is the core objective of this PR.
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.

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/web/fetch/blob.test.ts`:
- Around line 366-369: Assert the subprocess stderr is empty before parsing
stdout and making other assertions: check that the captured stderr (variable
stderr) is an empty string (or matches the repository convention for empty
diagnostics) with expect(stderr).toBe('') or equivalent immediately after
awaiting proc outputs, then parse stdout (JSON.parse(stdout)) and continue with
the existing assertions on deltaMiB and exitCode; update the test around the
variables stdout, stderr, exitCode so stderr is asserted first to surface any
child-process diagnostics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c95b0aca-295c-40e8-bbaf-81549888ae5d

📥 Commits

Reviewing files that changed from the base of the PR and between 49c97de and faa8eaa.

📒 Files selected for processing (8)
  • src/jsc/webcore_types.rs
  • src/runtime/jsc_hooks.rs
  • src/runtime/node/types.rs
  • src/runtime/server/FileRoute.rs
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/ObjectURLRegistry.rs
  • src/runtime/webcore/blob/read_file.rs
  • test/js/web/fetch/blob.test.ts

Comment thread test/js/web/fetch/blob.test.ts Resolved
Comment thread test/js/web/fetch/blob.test.ts Resolved
Comment thread src/runtime/node/types.rs Resolved
Comment thread src/jsc/webcore_types.rs Resolved
Comment thread src/jsc/webcore_types.rs Resolved

@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 is addressed and I didn't find any remaining issues, but adding Drop to Blob and changing borrowed_view() semantics is a core memory-ownership change that deserves a human pass — particularly the deinit() → heap::take → Drop re-entry path and whether any remaining call site still bitwise-aliases an owned content_type.

Extended reasoning...

Overview

This PR adds impl Drop for Blob to free a heap-allocated content_type on by-value drops, fixing a leak on every Bun.file(p, {type}).text() and similar paths. To make that sound it also changes borrowed_view() from aliasing the source's content_type pointer to returning a full dupe(), hoists the deep copy in dupe_with_content_type() ahead of construction so no transient Blob ever claims the source's allocation, and rewrites the Blob { ..Default::default() } literals (E0509 once Blob: Drop). The remaining ~200 lines across 8 files are comment updates at every dupe()/borrowed_view()/deinit() call site to reflect the new ownership model, plus three regression tests in blob.test.ts.

Security risks

None in the conventional sense — no auth, parsing, or untrusted-input handling changes. The risk profile here is memory-safety: adding Drop to a type that previously had none, where the freed resource is tracked by a raw *const [u8] + bool flag rather than an owning type. A missed aliasing site would be a double-free (ASAN-visible); the PR's borrowed_view() change and the hoisted copy in dupe_with_content_type() are specifically there to prevent that, and free_content_type() is idempotent so the layered deinit() → Drop path is safe.

Level of scrutiny

High. Blob is the payload type behind File, Bun.file, Response/Request bodies, FormData parts, S3 blobs, the object-URL registry, and the HTTP server's file routes. Adding drop glue to it changes the implicit contract at every by-value drop site across the runtime. The change is well-reasoned and the author swept all the "no Drop" comments across four follow-up commits, but this is exactly the kind of ownership-model shift where someone familiar with the Zig→Rust port's Blob lifecycle should confirm (a) no remaining site bitwise-copies a Blob with content_type_allocated=true, and (b) the deinit() path that does drop(heap::take(self)) re-entering Drop::drop mid-deinit is sound.

Other factors

  • Four rounds of my inline feedback (test hygiene + stale-comment sweep) were all addressed; the author did a final grep sweep in a160948 and documented which sites were deliberately left alone.
  • The bug-hunting system found nothing on the current revision.
  • New tests cover the leak (RSS + LSAN), and that the source handle's type survives reads/writes (i.e. the deep-copy isn't accidentally freeing the source).
  • robobun flagged CI failures on intermediate commit b9f586d; the latest commit (a160948) is comment-only so likely unrelated, but worth confirming green before merge.
  • borrowed_view() now allocates on every call where the source has a heap content_type — a deliberate tradeoff for soundness, but a hot-path reviewer may want to confirm that's acceptable.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Remove all code commetns. Make sure we're not cloning the content_type when it's not needed (i.e. it should remain interned for the static ones)

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

Done in daa90e9. Removed every comment line this PR added (the ownership notes, the PORT NOTEs on the Default::default() spellings, the Drop-impl doc block, and the test prose). Where the PR had rewritten the tail of a pre-existing comment, the now-dangling fragment was trimmed back to the last complete sentence rather than left mid-word.

On the content-type interning: the dupe path already only deep-copies when content_type_allocated is set (webcore_types.rs dupe_with_content_type). Static MIME-table entries keep content_type_allocated == false, so the dupe carries the same interned &'static [u8] pointer with no allocation, and free_content_type/Drop never free it — only genuinely heap-owned content types (registry misses / user-supplied strings) are copied and owned by the dupe.

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

No issues found and all prior feedback is addressed — deferring only because adding Drop to Blob and switching borrowed_view() to a self-owning dupe() is a broad ownership-semantics change across the webcore/server/node layers that's worth a human pass.

Extended reasoning...

Overview

This PR fixes a memory leak by adding impl Drop for Blob (calling free_content_type()), changes borrowed_view() from aliasing the source's content_type allocation to returning a self-owning dupe() (required to avoid double-free under the new Drop), hoists the deep copy in dupe_with_content_type ahead of construction, and rewrites every Blob { .., ..Default::default() } literal as Blob::default() + Cell setters since FRU is rejected for Drop types. Ten files are touched across src/jsc, src/runtime/{webcore,server,node}, plus three new tests in blob.test.ts. A large fraction of the diff is comment deletion/rewording at ~12 call sites whose ownership notes referenced the pre-Drop model.

Security risks

None identified. This is internal memory-ownership plumbing with no auth, crypto, input parsing, or permission surface. The relevant risk class is memory safety (double-free / UAF), which I traced through the key paths: free_content_type() is idempotent (checks and clears content_type_allocated), so the layered deinit() → Drop and explicit-call → variant-replace sequences are safe; borrowed_view() no longer aliases, so the new Drop cannot free the source's allocation; the full-field struct literal in dupe_with_content_type is fine for a Drop type (only FRU is rejected).

Level of scrutiny

Moderate-to-high. Blob is load-bearing across fetch bodies, Bun.file, FormData, server routing, and the object-URL registry. Adding Drop to a previously Drop-less type changes semantics at every by-value drop site, and borrowed_view() → dupe() is a behavioral change (now heap-allocates a fresh content_type when the source's is heap-owned). The author confirmed static MIME-table entries keep content_type_allocated == false so the common case stays allocation-free, but the blast radius still warrants a maintainer's eyes rather than a bot approval.

Other factors

I left four rounds of inline feedback on earlier revisions (test hygiene, three batches of stale ownership comments); all were addressed and resolved, and the author did a final worktree-wide grep sweep in a160948 plus a comment-trimming pass in daa90e9. The bug-hunting system found nothing on the current revision. The new tests cover the leak (RSS delta on 1024 reads of a 64 KiB-typed file blob), source-type survival across reads, and Bun.write preserving the destination's type. I'm deferring rather than approving solely because of the scope and subtlety of the ownership change, not because of any outstanding concern.

Comment thread src/jsc/webcore_types.rs Resolved
@Jarred-Sumner
Jarred-Sumner merged commit a49b308 into main May 25, 2026
78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the claude/hardening-fix-pre-110-blob-dupe-and-getstream-small-leaks branch May 25, 2026 07:42
springmin pushed a commit to springmin/bun that referenced this pull request May 25, 2026
* oven/main (20 new commits):
  webcore: free Blob's owned content type on drop (oven-sh#31358)
  Support cross-compiling macOS binaries from Linux (oven-sh#31303)
  test: forward keep-alive requests in proxy.test.ts's mock proxy (oven-sh#31352)
  Port Bun.stringWidth to C++ with explicit SIMD (oven-sh#31351)
  Fix quadratic hang reporting duplicate-binding parse errors in the transpiler (oven-sh#31341)
  shell: don't abort when a glob's directory prefix doesn't exist (oven-sh#31367)
  Error instead of crashing on deeply nested statements in the transpiler (oven-sh#31333)
  Fix JSX transform panic when a bare `key` prop precedes `key` with a value (oven-sh#31350)
  Cap ANSI markdown indentation so deeply nested lists render in linear time (oven-sh#31366)
  css: bound selector-list expansion when compiling nesting for older targets (oven-sh#31277)
  node:http2: reassemble HEADERS+CONTINUATION before HPACK decoding (oven-sh#31323)
  Fix `await using` expression printing `using` as `await` (oven-sh#31324)
  Parenthesize `async` when it starts a for-of loop initializer (oven-sh#31326)
  Print Infinity and negative numeric property keys as computed properties (oven-sh#31328)
  css: keep required grouping parens in @container conditions when minifying (oven-sh#31330)
  Fix panic on anonymous export default class with an auto-accessor field (oven-sh#31331)
  node:http2: send GOAWAY frames on stream 0 (oven-sh#31353)
  parser: fix Scope mismatch while visiting panic from decorators on dropped class members (oven-sh#31340)
  webcrypto: reject oversized BufferSource inputs instead of aborting (oven-sh#31356)
  Error instead of crashing on deeply nested TypeScript types in the transpiler (oven-sh#31361)

Resolved conflicts:
  - scripts/build.ts: kept both OHOS and macOS-cross argv entries
  - scripts/build/config.ts: kept both OHOS and macOS-cross config fields
  - scripts/build/deps/webkit.ts: kept OHOS fno-pic exclusion, adopted upstream -flto=thin
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.

2 participants