Repository navigation
webcore: free Blob's owned content type on drop - #31358
Jarred-Sumner merged 6 commits into
Conversation
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.
|
Updated 11:21 PM PT - May 24th, 2026
✅ @Jarred-Sumner, your commit daa90e97f86536dead7b5ca96c5ed8be44f353c0 passed in 🧪 To try this PR locally: bunx bun-pr 31358That installs a local version of the PR into your bun-31358 --bun |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
WalkthroughRefactors 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. ChangesBlob Ownership Refactor
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
src/jsc/webcore_types.rssrc/runtime/jsc_hooks.rssrc/runtime/node/types.rssrc/runtime/server/FileRoute.rssrc/runtime/webcore/Blob.rssrc/runtime/webcore/ObjectURLRegistry.rssrc/runtime/webcore/blob/read_file.rstest/js/web/fetch/blob.test.ts
There was a problem hiding this comment.
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 heapcontent_type— a deliberate tradeoff for soundness, but a hot-path reviewer may want to confirm that's acceptable.
Jarred-Sumner
left a comment
There was a problem hiding this comment.
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)
|
Done in daa90e9. Removed every comment line this PR added (the ownership notes, the PORT NOTEs on the On the content-type interning: the dupe path already only deep-copies when |
There was a problem hiding this comment.
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.
* 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
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 explicitdeinit()that several of them never call, so the heap copy made bydupe_with_content_typewas stranded on everyBun.file(p, { type }).text()and similar paths.This adds
impl Drop for Blobthat frees an owned content type, makesborrowed_view()return a self-owningdupe()instead of aliasing the source's allocation (which would double-free under the new Drop), and hoists the deep copy indupe_with_content_typeahead of construction. The remainingBlob { .., ..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 andBun.write. Existing content-type ownership tests in that file still pass.