Repository navigation
Conversation
|
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:
WalkthroughReplaces the previous ChangesJSDOMFile prototype/constructor split and Blob property migration
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Full details: Description checkExplanation The description clearly explains the problem, cause, fix, verification steps, related issues, and implementation impact. It does not use the exact template headings, but it provides the required information and is mostly complete. Comment |
|
Updated 7:58 PM PT - Aug 25th, 2026
❌ @robobun, your commit b639819 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 32434That installs a local version of the PR into your bun-32434 --bun |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
|
Ready for review at One test on The change set has otherwise been stable since the serialization v5 bump and the Deferred as follow-ups per review discussion: the |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/jsc/bindings/JSDOMFile.cpp (2)
177-181:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRelease the ThrowScope on the throwing tail call.
throwTypeErrorleaves a pending exception; return throughRELEASE_AND_RETURNso exception-scope validation sees the intentional throw.Proposed fix
auto scope = DECLARE_THROW_SCOPE(lexicalGlobalObject->vm()); throwTypeError(lexicalGlobalObject, scope, "Class constructor File cannot be invoked without 'new'"_s); - return {}; + RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined()));As per coding guidelines, "
**/*.cpp: Exception checks required after every call that can throw or run user code" and throwing tail calls should use the checked propagation path.🤖 Prompt for 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. In `@src/jsc/bindings/JSDOMFile.cpp` around lines 177 - 181, In the static call method of JSDOMFile.cpp, the throwTypeError function call leaves a pending exception but the function returns with a simple return statement. Replace the return {}; with RELEASE_AND_RETURN(scope, JSValue()); to properly release the ThrowScope and use the checked propagation path for the throwing tail call, ensuring exception-scope validation sees the intentional throw as required by the coding guidelines.Source: Coding guidelines
149-175:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCheck for constructor exceptions before wrapping
ptr.
JSDOMFile__constructparses/coerces constructor arguments and can throw or run JS. The returned native pointer is wrapped withoutRETURN_IF_EXCEPTION, which can trip JSC exception validation or return a value with a pending exception.Proposed fix
auto* globalObject = defaultGlobalObject(lexicalGlobalObject); auto& vm = JSC::getVM(globalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); JSObject* newTarget = asObject(callFrame->newTarget()); auto* constructor = globalObject->JSDOMFileConstructor(); Structure* structure = globalObject->JSDOMFileStructure(); if (constructor != newTarget) { - auto scope = DECLARE_THROW_SCOPE(vm); - auto* functionGlobalObject = defaultGlobalObject( // ShadowRealm functions belong to a different global object. getFunctionRealm(lexicalGlobalObject, newTarget)); - RETURN_IF_EXCEPTION(scope, {}); + RETURN_IF_EXCEPTION(throwScope, {}); structure = InternalFunction::createSubclassStructure(lexicalGlobalObject, newTarget, functionGlobalObject->JSDOMFileStructure()); - RETURN_IF_EXCEPTION(scope, {}); + RETURN_IF_EXCEPTION(throwScope, {}); } void* ptr = JSDOMFile__construct(lexicalGlobalObject, callFrame); + RETURN_IF_EXCEPTION(throwScope, {}); if (!ptr) [[unlikely]] { - return JSValue::encode(JSC::jsUndefined()); + RELEASE_AND_RETURN(throwScope, JSValue::encode(JSC::jsUndefined())); } - return JSValue::encode( - WebCore::JSBlob::create(vm, globalObject, structure, ptr)); + RELEASE_AND_RETURN(throwScope, JSValue::encode( + WebCore::JSBlob::create(vm, globalObject, structure, ptr)));As per coding guidelines, "
**/*.cpp: Exception checks required after every call that can throw or run user code; use RETURN_IF_EXCEPTION or JSError propagation before using results".🤖 Prompt for 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. In `@src/jsc/bindings/JSDOMFile.cpp` around lines 149 - 175, The construct method in JSDOMFile.cpp calls JSDOMFile__construct which can throw or run user code, but the returned ptr value is wrapped in WebCore::JSBlob::create without checking for exceptions. Add a RETURN_IF_EXCEPTION check after the JSDOMFile__construct call and before the JSBlob::create wrapping, using the existing scope variable that was declared in the constructor subclass path. This ensures that if an exception occurs during construction, the method returns early rather than attempting to wrap a potentially invalid pointer.Source: Coding guidelines
🤖 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 `@src/jsc/bindings/JSDOMFile.cpp`:
- Around line 15-17: The File.name property currently has a writable setter
(JSDOMFile__setName) which allows mutation of file metadata, while lastModified
is readonly. To align with the W3C File API specification, remove the
JSDOMFile__setName function declaration and its associated installation at line
69, then apply the ReadOnly attribute to the name property descriptor to match
the immutable pattern used for lastModified.
- Around line 50-51: The JSDOMFile__setName function can throw exceptions during
value coercion or storage, but the code does not validate whether an exception
occurred before using the returned bool result. After the JSDOMFile__setName
call and before the RELEASE_AND_RETURN statement, add an exception check using
RETURN_IF_EXCEPTION or appropriate JSError propagation to ensure any pending
exceptions are properly handled before the result is returned.
In `@src/runtime/webcore/Blob.rs`:
- Around line 2014-2016: The slice() method currently only clears is_jsdom_file
but retains the file-backed store from dupe(), allowing is_bun_file() to promote
it back to a File when to_js() is called later. To fix this and ensure
Bun.file().slice() returns a plain Blob as per the File API spec, either route
the slice result through a plain JSBlob wrapper that strips the file-backed
store entirely, or add an explicit state flag (like is_plain_blob_from_slice)
that prevents the is_bun_file() check in the to_js path from promoting sliced
blobs back to File objects.
---
Outside diff comments:
In `@src/jsc/bindings/JSDOMFile.cpp`:
- Around line 177-181: In the static call method of JSDOMFile.cpp, the
throwTypeError function call leaves a pending exception but the function returns
with a simple return statement. Replace the return {}; with
RELEASE_AND_RETURN(scope, JSValue()); to properly release the ThrowScope and use
the checked propagation path for the throwing tail call, ensuring
exception-scope validation sees the intentional throw as required by the coding
guidelines.
- Around line 149-175: The construct method in JSDOMFile.cpp calls
JSDOMFile__construct which can throw or run user code, but the returned ptr
value is wrapped in WebCore::JSBlob::create without checking for exceptions. Add
a RETURN_IF_EXCEPTION check after the JSDOMFile__construct call and before the
JSBlob::create wrapping, using the existing scope variable that was declared in
the constructor subclass path. This ensures that if an exception occurs during
construction, the method returns early rather than attempting to wrap a
potentially invalid pointer.
🪄 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: 76e87ba3-fff3-4c49-96c2-0bd053015954
📒 Files selected for processing (11)
src/jsc/bindings/JSDOMFile.cppsrc/jsc/bindings/JSDOMFile.hsrc/jsc/bindings/JSS3File.cppsrc/jsc/bindings/ZigGlobalObject.cppsrc/jsc/bindings/ZigGlobalObject.hsrc/jsc/bindings/ZigGlobalObject.lut.txtsrc/jsc/bindings/blob.cppsrc/runtime/webcore/Blob.rssrc/runtime/webcore/response.classes.tstest/js/bun/util/inspect.test.jstest/js/web/fetch/blob.test.ts
💤 Files with no reviewable changes (1)
- test/js/bun/util/inspect.test.js
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 `@src/runtime/webcore/Blob.rs`:
- Around line 4338-4340: Remove the is_bun_file() check from the condition on
line 4338 that determines whether to deserialize as a File. Instead, ensure that
Bun.file() payloads are explicitly marked with a File indicator during
serialization before wrapping. Update the deserialization logic to only promote
to File based on this explicit marker (likely through is_jsdom_file or a similar
explicit flag), not through the is_bun_file() method check. This prevents slices
of Bun.file() blobs (which clear is_jsdom_file but retain the file store) from
being incorrectly promoted back to File, preserving the slice invariant where a
slice of a Blob remains a Blob.
🪄 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: 2de364e9-4cc5-440a-9e10-82c3ec69d4e4
📒 Files selected for processing (2)
src/runtime/webcore/Blob.rstest/js/web/fetch/blob.test.ts
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 `@src/jsc/bindings/DOMFormData.cpp`:
- Around line 160-163: The `set` method that takes a name, blob, and filename
parameters is not applying the same filename sanitization that the `append`
method uses. Instead of directly passing the filename to `blob->setFileName()`,
apply the `replaceUnpairedSurrogatesWithReplacementCharacter()` function to the
filename (handling both null and non-null cases) before calling setFileName,
ensuring consistent behavior between the `set` and `append` methods for filename
sanitization.
🪄 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: e0777294-c33a-4acf-9612-11879b781f6e
📒 Files selected for processing (3)
src/jsc/bindings/DOMFormData.cppsrc/jsc/bindings/blob.cppsrc/runtime/api/Archive.rs
|
Do you need to make it so |
|
Yes, done in f329ef6. if self.is_s3() { return s3_file::to_js_unchecked(...); }
if self.is_jsdom_file.get() { return dom_file_to_js_unchecked(...); }
js::to_js_unchecked(...)To make that hold everywhere, I did not fold One knock-on: now that |
3541162 to
5fb5f36
Compare
|
Rebased onto The only conflict was - File GlobalObject::m_JSDOMFileConstructor CellProperty
crypto GlobalObject::m_cryptoObject CellProperty
...
Crypto GlobalObject::m_JSCrypto ClassStructure
+ File GlobalObject::m_JSDOMFileClassStructure ClassStructure
Re-verified on the rebased tree:
|
5fb5f36 to
6cdb0e7
Compare
|
Rebased onto main (511caaa) and re-verified. Every case from the File/Blob prototype report now matches Node: Added explicit assertions for |
There was a problem hiding this comment.
I reviewed this PR and the bug-hunting pass found no new issues — every finding from the prior ~17 review rounds has been addressed. Given the scope (new File.prototype + structure on ZigGlobalObject, serialization format bump to v5, Bun.file()/Bun.stdin/S3File now inheriting File.prototype) and the open design question the description explicitly flags for maintainers — whether Bun.file() instanceof File should become true or whether a separate BunFile prototype is preferable — a human sign-off is still worthwhile.
What was reviewed: prototype-chain wiring (JSDOMFilePrototype/LazyClassStructure, File.prototype.constructor set via init.setConstructor, S3File chained through File); every File-producing path routes through is_jsdom_file → to_js() (Bun.file, stdio, embedded files, structuredClone, FormData, resolveObjectURL, Archive); every Blob-producing path clears the flag (slice(), new Blob([file]), Body.blob()); m_name WriteBarrier kept on JSBlob via values: and used by the hand-written getter; BUN__createJSDOMFileUnsafely reports extra memory like Blob__create; the v5 gate keeps pre-v5 file-backed payloads File-typed while v5 slices stay Blob.
Extended reasoning...
Overview
This PR splits File.prototype from Blob.prototype and moves the name/lastModified accessors onto File.prototype. It touches 21 files: a new JSDOMFilePrototype + JSDOMFileConstructor + LazyClassStructure on ZigGlobalObject (JSDOMFile.cpp/h, ZigGlobalObject.cpp/h/.lut.txt), the generated-class definition (response.classes.ts drops name/lastModified from Blob's proto but keeps name in values: for the WriteBarrier cache), blob.cpp/DOMFormData.cpp (toJS now routes on null-vs-set fileName), JSS3File.cpp (S3File.prototype now chains through File.prototype), Rust-side plumbing in Blob.rs/Body.rs/BunObject.rs/standalone_graph_jsc.rs/ObjectURLRegistry.rs to set/clear is_jsdom_file at every producer, a serialization format bump (v4→v5) with a back-compat gate, and bun.d.ts (BunFile.slice() now returns Blob). Six test files are updated/extended.
Security risks
None identified. No auth/crypto/permissions surface. The structured-clone deserializer change is a version-gated read of an already-trusted byte; no new untrusted-length arithmetic. The new C++ getters do dynamicDowncast<JSBlob> before dereferencing wrapped() and use RETURN_IF_EXCEPTION.
Level of scrutiny
High. This is user-facing Web API surface (File/Blob prototype identity, instanceof, Symbol.toStringTag), it changes what Bun.file() is an instance of (a documented Bun API), it bumps a persisted serialization format, and it adds a new cached structure to ZigGlobalObject. It has been through many review rounds with a dozen-plus resolved findings (slice/Body.blob/new Blob([file]) File-leak, WebSocket blob promotion, FormData entry wrapping, resolveObjectURL, embeddedFiles/compiled-asset flag consistency, reportExtraMemoryAllocated, DOMAttribute brand check, inspect show_name edge cases, structured-clone version gating, .d.ts drift), all now addressed with tests.
Other factors
The description explicitly leaves a design decision to maintainers: routing Bun.file()/stdio/embedded/S3File through File.prototype (so Bun.file(p) instanceof File === true, a behavior change) versus a separate BunFile prototype. It also notes overlap with #30328 (the prototype-split PR), with the plumbing here to be reworked on top of that once it lands. Jarred asked a design question on the thread earlier. Those are exactly the kinds of calls a human should make; the code itself looks correct for the approach taken.
ac2df5c to
7ab3b5f
Compare
|
Rebased onto This time the conflicts were with #39770 (binary-size trim), which restructured the JSC wiring this PR adds to:
Re-verified on the rebased tree: |
There was a problem hiding this comment.
I reviewed this PR and the bug-hunting pass found no new issues — every finding from the earlier ~20 rounds is resolved in the current diff. A human look is still warranted: the description flags an open design question for maintainers (whether Bun.file()/Bun.stdin/S3File should inherit from File.prototype — flipping Bun.file(path) instanceof File to true — vs. a separate BunFile prototype), and the prototype plumbing overlaps #30328 in a way that needs coordination on landing order.
What was reviewed: the new JSDOMFilePrototype/LazyClassStructure wiring and every File-producing path routed through it (constructor, Bun.file, stdio, embedded files, structuredClone, FormData/toJS(Blob&), S3File, resolveObjectURL); the is_jsdom_file clears on slice(), new Blob([file]), and Body.blob(); the SERIALIZATION_VERSION v5 bump and version < 5 back-compat gate; the m_name WriteBarrier moved to the values list so GC visitation is preserved; and the BunFile.slice(): Blob type update.
Extended reasoning...
Overview
This PR gives File its own prototype (JSDOMFilePrototype, chained through Blob.prototype) and moves the name/lastModified accessors from Blob.prototype to File.prototype, fixing #20700 and #14257. It touches 21 files: C++ JSC bindings (JSDOMFile.cpp rewritten, ZigGlobalObject.{h,cpp,lut.txt}, JSS3File.cpp, blob.cpp, DOMFormData.cpp), Rust runtime (Blob.rs, Body.rs, BunObject.rs, ObjectURLRegistry.rs, standalone_graph_jsc.rs), the class-generator input (response.classes.ts), TypeScript declarations (bun.d.ts), and six test files. Instances remain WebCore::JSBlob cells; only the structure/prototype differs, keyed on the Rust-side is_jsdom_file flag which to_js() now branches on.
Security risks
None identified. No auth/crypto/permissions surface. The structured-clone deserializer change (v5 bump + version < 5 && needs_to_read_file() promotion) was checked for over-promotion of crafted payloads and is bounded to the same set of prototypes reachable pre-PR.
Level of scrutiny
High — this is a user-facing Web API surface change, not a mechanical fix. It reshapes the File/Blob prototype chain, changes what Bun.file() returns (instanceof File flips false→true; fs.openAsBlob inherits that), changes BunFile.slice() from BunFile→Blob, and removes the Symbol.hasInstance override on File. The PR has been through many review rounds and every raised issue is resolved, but two things remain that only a maintainer can decide: (1) the description's explicit "Point for maintainers" about whether Bun.file() should inherit File.prototype vs. a dedicated BunFile prototype, and (2) coordination with #30328, which the description says will land the prototype split independently and after which this PR should be reworked on top of it.
Other factors
Test coverage is extensive and targeted (prototype-chain assertions, structuredClone round-trips including a v4-payload back-compat test, FormData File wrapping, Bun.inspect output, embedded-file compile test, subprocess test for lazy-init ordering of File.prototype.constructor). The known remaining spec gap — FormData's default filename is "" instead of "blob" — is documented as pre-existing, non-regressing, and deferred with an in-test comment. All prior inline findings from this reviewer are marked resolved.
7ab3b5f to
4ccf649
Compare
|
Rebased onto Two small conflicts, both from #40238 (
Re-verified on the rebased tree: |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it introduces a new File prototype/structure in the JSC bindings, bumps the Blob serialization format, and changes Bun.file() instanceof File from false to true — with the description explicitly flagging that BunFile-inherits-File vs. a separate BunFile prototype is an open question, and the prototype plumbing overlapping #30328 — a maintainer sign-off on the API shape is warranted.
Checked: File-producing paths (new File, Bun.file, stdio, embedded files, S3File, FormData entries, structuredClone) all route through JSDOMFileStructure; slice(), new Blob([file]), and Body.blob() reset is_jsdom_file so file-backed Blobs stay Blobs across clone.
Ruled out: the m_name WriteBarrier stays visited via the values: [..., "name"] list on the Blob class, so the File name cache keeps its GC edge.
Ruled out: the toJSNewlyCreated null-fileName early return still hands impl->impl() to Blob__create, so the moved-in Ref<Blob> is consumed on that path too.
Extended reasoning...
Overview
This PR gives File its own prototype (previously File.prototype === Blob.prototype) and moves the name/lastModified accessors off Blob.prototype onto the new File.prototype. It touches 21 files: a new JSDOMFilePrototype/JSDOMFileConstructor and m_JSDOMFileClassStructure in the JSC bindings, routing every File-producing site (new File, Bun.file, Bun.stdin/stdout/stderr, embedded standalone-graph files, S3File, FormData entries, structuredClone deserialization) through the new structure, bumping SERIALIZATION_VERSION 4→5 with a back-compat gate, resetting is_jsdom_file on slice()/new Blob([file])/Body.blob(), and adjusting Bun.inspect and the BunFile type declarations to match.
Security risks
None identified. The change is prototype layout / accessor placement; no new untrusted-input parsing, and the serialization bump only widens the deserializer's promotion gate for pre-v5 file-backed payloads.
Level of scrutiny
High. This is not a mechanical change: it adds a hand-written LazyClassStructure to ZigGlobalObject, changes the S3File prototype chain to go through File, bumps a persisted serialization format, and changes user-visible API behavior — Bun.file(path) instanceof File flips from false to true, and BunFile.slice() now returns a plain Blob. The PR description itself flags the BunFile-prototype question as a point for maintainers, and notes the prototype plumbing duplicates #30328 and will be reworked once that lands. Those are design decisions a human should sign off on.
Other factors
The PR has been through many review rounds; every prior inline finding from this reviewer is resolved, and Jarred's earlier toJS question is addressed by the is_jsdom_file branch in Blob::to_js. Test coverage is thorough (prototype chain, Symbol.toStringTag, subclassing, structuredClone round-trips including a crafted v4 payload, FormData wrapping, Bun.inspect, embedded files in --compile). No bugs were found by the bug-hunting system on the current head. The remaining reason to defer is the open API-shape question and the #30328 overlap, not correctness concerns.
4ccf649 to
fddbb44
Compare
|
Rebased onto One conflict, in Re-verified on the rebased tree: |
There was a problem hiding this comment.
I reviewed this PR and the automated bug-hunting pass found no new issues. Because the PR carries an explicit open design question for maintainers (whether Bun.file() should inherit from File.prototype — flipping Bun.file(path) instanceof File to true — versus a separate BunFile prototype) and overlaps with #30328's prototype split, a human sign-off on that API decision is still warranted.
Checked the new JSDOMFilePrototype/LazyClassStructure wiring and BUN__createJSDOMFileUnsafely — the structure is cached on ZigGlobalObject, visited via FOR_EACH_GLOBALOBJECT_GC_MEMBER, and m_name stays declared in the values list so the WriteBarrier is still visited. The SERIALIZATION_VERSION bump to 5 with the version < 5 && needs_to_read_file() gate keeps pre-v5 file-backed payloads reading as File while v5 slices stay Blob. Also traced is_jsdom_file.set(false) through slice(), new Blob([file]), and both body.blob() sites in Body.rs so structuredClone/resolveObjectURL don't over-promote.
Extended reasoning...
Overview
This PR splits File.prototype from Blob.prototype (previously the same object) and moves the name/lastModified accessors from Blob.prototype to the new File.prototype. It touches 21 files across JSC C++ bindings (JSDOMFile.cpp, ZigGlobalObject.{h,cpp,lut.txt}, JSS3File.cpp, blob.cpp, DOMFormData.cpp), Rust runtime (Blob.rs, Body.rs, BunObject.rs, ObjectURLRegistry.rs, standalone_graph_jsc.rs), the class-generator input (response.classes.ts), published types (bun.d.ts), and six test files. The change bumps the Blob structured-clone serialization version from 4 to 5.
Security risks
None identified. The new getters brand-check via dynamicDowncast<JSBlob> and are marked DOMAttribute so incompatible receivers throw TypeError. No new user input reaches native code without validation. The serialization-version gate is defensive (widens, not narrows, what deserializes as a File) and only affects Bun-to-Bun payloads.
Level of scrutiny
High. This is a user-visible API-surface change with several downstream behavioral shifts: Bun.file() instanceof File becomes true, BunFile.slice() now returns a plain Blob (types updated), S3File.prototype re-parented through File.prototype, and FormData Blob entries now report name === "" instead of undefined. The PR description explicitly flags an open question for maintainers about whether the Bun.file() → File.prototype route is preferred over a dedicated BunFile prototype, and notes the prototype plumbing overlaps with the still-open #30328. That is exactly the kind of design decision the approval guidelines say to defer on.
Other factors
The PR has been through ~20 review iterations; every prior automated finding is resolved and covered by a targeted test (structuredClone over-promotion, inspect show_name edge cases, cross-version deserialize, .d.ts drift). Test coverage is thorough. The remaining reason for human review is not correctness but the API-design choice the author explicitly asked maintainers to weigh in on, plus coordination with #30328.
`"name" in new Blob()` returned true because `File.prototype` and `Blob.prototype` were the same object: `File` was an InternalFunction with a patched `Symbol.hasInstance`, not a real class with its own prototype. Give `File` a real `JSDOMFilePrototype` / `JSDOMFileConstructor` pair registered through `LazyClassStructure`, so `Object.getPrototypeOf(File.prototype) === Blob.prototype` and `name` / `lastModified` live only on `File.prototype`. `is_jsdom_file` is now the single source of truth for which prototype a Blob's JS wrapper gets: `Blob::to_js()` routes to the File structure when it is set (alongside the existing `is_s3()` branch), so call sites no longer pick the structure themselves. `Bun.file()`, `Bun.stdin/stdout/ stderr`, embedded assets and archive entries set the flag at creation; `slice()`, `new Blob()` and `Body.blob()` clear it. Structured-clone deserialize honors the serialized flag for every payload version that carries it. Blob serialization moves to v5. Bun.file() now serializes is_jsdom_file=1; payloads older than v5 wrote 0 for it, so file-backed stores in those are promoted to File on read, while v5 keeps the byte authoritative so a slice() round-trips as a Blob. Side effects: - `File.prototype.name` returns "" instead of undefined when there is no backing path (`Bun.file(fd)`, `new File([], "")`). File.name is a USVString, so this matches Node and browsers and makes `structuredClone(Bun.file(fd)).name` round-trip. - `Bun.inspect` no longer prints a redundant `name:` line for a FileRef header that already shows the path; a File constructed over a BunFile with its own name still shows it. - bun-types: BunFile.slice() returns Blob. Fixes #20700 Fixes #14257 Fixes #14102
fddbb44 to
b7ea2e0
Compare
|
Rebased onto One conflict, in Two follow-on adjustments from #40374 ( Re-verified on the rebased tree: |
Body.blob() returns a plain Blob, so the File's name is not reachable from (await fetch(url)).blob(). resolveObjectURL hands back the registered File through the same registry dupe, which is the cross-thread string path this test guards. A fetch of each URL stays in the loop so that path is still exercised.
…text (#42520) ### Problem - `class Upload extends File {}` inside a `node:vm` context crashes on `new Upload(...)`: `panic(main thread): Segmentation fault at address 0x28`. `class S extends fs.Stats {}`, `BigIntStats`, and `Reflect.construct(File, args, fnFromContext)` crash the same way. Node v26.3.0 constructs the object. - These constructors do `static_cast<Zig::GlobalObject*>(getFunctionRealm(lexicalGlobalObject, newTarget))` (`JSDOMFile.cpp:75`, `NodeFSStatBinding.cpp:843`, `NodeFSStatFSBinding.cpp:372`). For a function from a context the realm is a `NodeVMGlobalObject`, which is not a `Zig::GlobalObject`. `JSBlobStructure()` and `getStructure<isBigInt>()` then read a `LazyClassStructure` past the end of the cell. ### Fix - The three sites call `defaultGlobalObject(getFunctionRealm(...))`. It returns the realm when it is a Bun global, and the default Bun global when it is not. - The other native constructors already do this (`generate-classes.ts:2387`, `JSDOMWrapperCache.cpp:42`, `NodeDirent.cpp:177`). - The `StatFs` constructor is not reachable from JS, so that site has no test. - Verified: `test/js/node/vm/vm.test.ts`, four new cases. All four exit with SIGSEGV on 1.4.3-canary.1. Also ran the `fs.Stats`, `Blob`, and globals suites. ### Background - `newTarget` is the constructor that `new` was applied to. In `new Upload()`, `File` runs with `newTarget === Upload`. - `getFunctionRealm(newTarget)` returns the global object the function was created in. A native constructor takes its base `Structure` from that global. `createSubclassStructure` then applies `newTarget.prototype`. - A `node:vm` context has its own global, `NodeVMGlobalObject`. It and `Zig::GlobalObject` (the Bun global) are sibling subclasses of `Bun::GlobalScope`. Only `Zig::GlobalObject` holds the structures of Bun classes. - A ShadowRealm global is a `Zig::GlobalObject`. The comment at these sites names that case, and the cast was valid for it. <details><summary>Notes</summary> Repro (`bun f.js file`, `bun f.js stats`, `bun f.js bigint`): ```js const vm = require("vm"), fs = require("fs"); const ctx = vm.createContext({ File, Stats: fs.Stats }); const which = process.argv[2] || "file"; try { if (which === "file") console.log("ok", vm.runInContext(`class Upload extends File {}; new Upload(["a"], "a.txt")`, ctx).name); if (which === "stats") console.log("ok", typeof vm.runInContext(`class S extends Stats {}; new S()`, ctx).isFile); if (which === "bigint") console.log("ok", typeof Reflect.construct(fs.statSync(".", { bigint: true }).constructor, [], vm.runInContext("(function(){})", ctx))); } catch (e) { console.log("threw", e.message); } console.log("survived"); ``` | | `file` | `stats` | `bigint` | | --- | --- | --- | --- | | 1.4.3-canary.1 | segfault at 0x28 | segfault at 0x28 | segfault at 0x28 | | this branch | `ok a.txt` | `ok function` | `threw Invalid argument type in ToBigInt operation` | | node v26.3.0 | `ok a.txt` | `ok function` | `threw Cannot mix BigInt and other types` | ASAN on main with `Malloc=1` in the environment. `heap-buffer-overflow`, `READ of size 8`, "located 3776 bytes after 4184-byte region" (`File`), 896 bytes after (`Stats`), 912 bytes after (`BigIntStats`). The region is the `NodeVMGlobalObject` cell. ``` #0 JSC::LazyProperty<JSC::JSGlobalObject, JSC::Structure>::getInitializedOnMainThread LazyProperty.h:95 #1 JSC::LazyClassStructure::getInitializedOnMainThread LazyClassStructure.h:104 #2 Zig::GlobalObject::JSBlobStructure() ZigGeneratedClasses+lazyStructureHeader.h:7 #3 JSDOMFile::construct src/jsc/bindings/JSDOMFile.cpp:79 #5 llint_op_super_construct_varargs ``` ``` #1 JSC::LazyClassStructure::getInitializedOnMainThread LazyClassStructure.h:104 #2 Bun::getStructure<false>(Zig::GlobalObject*) src/jsc/bindings/NodeFSStatBinding.cpp:167 (<true>: line 164) #3 Bun::constructJSStatsObject<false>(JSGlobalObject*, CallFrame*) src/jsc/bindings/NodeFSStatBinding.cpp:847 #4 Bun::constructStats src/jsc/bindings/NodeFSStatBinding.cpp:915 ``` Without `Malloc=1` the debug build of main reads zero there and stops at `Structure.h:415: runtime error: member call on null pointer of type 'const JSC::Structure *'`. Fail-before and pass-after, same test file: - `USE_SYSTEM_BUN=1 bun test test/js/node/vm/vm.test.ts -t "belongs to a context"`: 0 pass, 4 fail (`exitCode: 139`, `signalCode: "SIGSEGV"`). - Debug ASAN build of main with only the test added: 0 pass, 4 fail (`exitCode: 1`). - Debug ASAN build of this branch: 4 pass. The whole file: 285 pass, 0 fail. Other cases checked by hand on this branch: - A newTarget that is a plain function, a bound function, or a Proxy from the context. The new test covers these. A bound function has no `prototype`, so the object gets the prototype of the constructor. - A revoked Proxy from the context throws `TypeError: Cannot get function realm from revoked Proxy`. - A newTarget whose `prototype` is not an object falls back to `File.prototype` or `fs.Stats.prototype`. - `class X extends File {}` inside a `ShadowRealm` still works. `File` and `X` both belong to the ShadowRealm global there. - An instance of the context subclass works with `FormData`, `.text()`, and a forced GC. Suites run on the debug build: `test/js/node/vm/vm.test.ts`, `test/js/node/fs/fs-stats-constructor.test.ts`, `test/js/node/fs/fs-stats-truncate.test.ts`, `test/js/node/fs/fs.test.ts -t Stats`, `test/js/bun/globals.test.js`, `test/js/web/fetch/blob.test.ts`, and the Node tests `test-fs-stat.js`, `test-fs-stat-bigint.js`, `test-fs-statfs.js`, `test-fs-watchfile.js`. Related: - #32434 changes the `File` cast to `defaultGlobalObject` as one line of a larger `File.prototype` change. It does not touch `fs.Stats`. - #42514 fixes the same kind of cast at another site (`UtilInspect.cpp`). - `new BigIntStats(...)` stores `atimeMs` as a Number where Node stores a BigInt, so `.atime` throws. That is a separate bug and is not part of this PR. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/vm/vm.test.ts <!-- robobun:evidence:end -->
…text (oven-sh#42520) ### Problem - `class Upload extends File {}` inside a `node:vm` context crashes on `new Upload(...)`: `panic(main thread): Segmentation fault at address 0x28`. `class S extends fs.Stats {}`, `BigIntStats`, and `Reflect.construct(File, args, fnFromContext)` crash the same way. Node v26.3.0 constructs the object. - These constructors do `static_cast<Zig::GlobalObject*>(getFunctionRealm(lexicalGlobalObject, newTarget))` (`JSDOMFile.cpp:75`, `NodeFSStatBinding.cpp:843`, `NodeFSStatFSBinding.cpp:372`). For a function from a context the realm is a `NodeVMGlobalObject`, which is not a `Zig::GlobalObject`. `JSBlobStructure()` and `getStructure<isBigInt>()` then read a `LazyClassStructure` past the end of the cell. ### Fix - The three sites call `defaultGlobalObject(getFunctionRealm(...))`. It returns the realm when it is a Bun global, and the default Bun global when it is not. - The other native constructors already do this (`generate-classes.ts:2387`, `JSDOMWrapperCache.cpp:42`, `NodeDirent.cpp:177`). - The `StatFs` constructor is not reachable from JS, so that site has no test. - Verified: `test/js/node/vm/vm.test.ts`, four new cases. All four exit with SIGSEGV on 1.4.3-canary.1. Also ran the `fs.Stats`, `Blob`, and globals suites. ### Background - `newTarget` is the constructor that `new` was applied to. In `new Upload()`, `File` runs with `newTarget === Upload`. - `getFunctionRealm(newTarget)` returns the global object the function was created in. A native constructor takes its base `Structure` from that global. `createSubclassStructure` then applies `newTarget.prototype`. - A `node:vm` context has its own global, `NodeVMGlobalObject`. It and `Zig::GlobalObject` (the Bun global) are sibling subclasses of `Bun::GlobalScope`. Only `Zig::GlobalObject` holds the structures of Bun classes. - A ShadowRealm global is a `Zig::GlobalObject`. The comment at these sites names that case, and the cast was valid for it. <details><summary>Notes</summary> Repro (`bun f.js file`, `bun f.js stats`, `bun f.js bigint`): ```js const vm = require("vm"), fs = require("fs"); const ctx = vm.createContext({ File, Stats: fs.Stats }); const which = process.argv[2] || "file"; try { if (which === "file") console.log("ok", vm.runInContext(`class Upload extends File {}; new Upload(["a"], "a.txt")`, ctx).name); if (which === "stats") console.log("ok", typeof vm.runInContext(`class S extends Stats {}; new S()`, ctx).isFile); if (which === "bigint") console.log("ok", typeof Reflect.construct(fs.statSync(".", { bigint: true }).constructor, [], vm.runInContext("(function(){})", ctx))); } catch (e) { console.log("threw", e.message); } console.log("survived"); ``` | | `file` | `stats` | `bigint` | | --- | --- | --- | --- | | 1.4.3-canary.1 | segfault at 0x28 | segfault at 0x28 | segfault at 0x28 | | this branch | `ok a.txt` | `ok function` | `threw Invalid argument type in ToBigInt operation` | | node v26.3.0 | `ok a.txt` | `ok function` | `threw Cannot mix BigInt and other types` | ASAN on main with `Malloc=1` in the environment. `heap-buffer-overflow`, `READ of size 8`, "located 3776 bytes after 4184-byte region" (`File`), 896 bytes after (`Stats`), 912 bytes after (`BigIntStats`). The region is the `NodeVMGlobalObject` cell. ``` #0 JSC::LazyProperty<JSC::JSGlobalObject, JSC::Structure>::getInitializedOnMainThread LazyProperty.h:95 oven-sh#1 JSC::LazyClassStructure::getInitializedOnMainThread LazyClassStructure.h:104 oven-sh#2 Zig::GlobalObject::JSBlobStructure() ZigGeneratedClasses+lazyStructureHeader.h:7 oven-sh#3 JSDOMFile::construct src/jsc/bindings/JSDOMFile.cpp:79 oven-sh#5 llint_op_super_construct_varargs ``` ``` oven-sh#1 JSC::LazyClassStructure::getInitializedOnMainThread LazyClassStructure.h:104 oven-sh#2 Bun::getStructure<false>(Zig::GlobalObject*) src/jsc/bindings/NodeFSStatBinding.cpp:167 (<true>: line 164) oven-sh#3 Bun::constructJSStatsObject<false>(JSGlobalObject*, CallFrame*) src/jsc/bindings/NodeFSStatBinding.cpp:847 oven-sh#4 Bun::constructStats src/jsc/bindings/NodeFSStatBinding.cpp:915 ``` Without `Malloc=1` the debug build of main reads zero there and stops at `Structure.h:415: runtime error: member call on null pointer of type 'const JSC::Structure *'`. Fail-before and pass-after, same test file: - `USE_SYSTEM_BUN=1 bun test test/js/node/vm/vm.test.ts -t "belongs to a context"`: 0 pass, 4 fail (`exitCode: 139`, `signalCode: "SIGSEGV"`). - Debug ASAN build of main with only the test added: 0 pass, 4 fail (`exitCode: 1`). - Debug ASAN build of this branch: 4 pass. The whole file: 285 pass, 0 fail. Other cases checked by hand on this branch: - A newTarget that is a plain function, a bound function, or a Proxy from the context. The new test covers these. A bound function has no `prototype`, so the object gets the prototype of the constructor. - A revoked Proxy from the context throws `TypeError: Cannot get function realm from revoked Proxy`. - A newTarget whose `prototype` is not an object falls back to `File.prototype` or `fs.Stats.prototype`. - `class X extends File {}` inside a `ShadowRealm` still works. `File` and `X` both belong to the ShadowRealm global there. - An instance of the context subclass works with `FormData`, `.text()`, and a forced GC. Suites run on the debug build: `test/js/node/vm/vm.test.ts`, `test/js/node/fs/fs-stats-constructor.test.ts`, `test/js/node/fs/fs-stats-truncate.test.ts`, `test/js/node/fs/fs.test.ts -t Stats`, `test/js/bun/globals.test.js`, `test/js/web/fetch/blob.test.ts`, and the Node tests `test-fs-stat.js`, `test-fs-stat-bigint.js`, `test-fs-statfs.js`, `test-fs-watchfile.js`. Related: - oven-sh#32434 changes the `File` cast to `defaultGlobalObject` as one line of a larger `File.prototype` change. It does not touch `fs.Stats`. - oven-sh#42514 fixes the same kind of cast at another site (`UtilInspect.cpp`). - `new BigIntStats(...)` stores `atimeMs` as a Number where Node stores a BigInt, so `.atime` throws. That is a separate bug and is not part of this PR. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/vm/vm.test.ts <!-- robobun:evidence:end -->
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-26. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Repro
Per the W3C File API,
nameandlastModifiedbelong onFile.prototype, notBlob.prototype. Node, Deno, Firefox and Chrome all returnfalsefor"name" in new Blob().Cause
Filedid not have its own prototype.JSDOMFile.cpppointedFile.prototypedirectly at theJSBlobPrototypeobject and usedJSBlobStructure()fornew File():Because there was no separate
File.prototype, thenameandlastModifiedaccessors were placed onBlob.prototypeinresponse.classes.ts.Fix
Add
JSDOMFilePrototype([[Prototype]]=Blob.prototype) carrying thename/lastModifiedaccessors plusSymbol.toStringTag = "File", and a cachedm_JSDOMFileStructureonZigGlobalObjectthat points instances at it. The File constructor's own[[Prototype]]is now the Blob constructor andFile.prototype.constructor === File. TheSymbol.hasInstanceoverride onFileis removed since the prototype chain now makes defaultinstanceofwork.All File-producing paths route through the new structure:
new File()and subclasses,Bun.file(), structuredClone of Files, FormData file entries (WebCore::toJS/toJSNewlyCreated).S3File.prototypenow chains throughFile.prototypesoname/lastModifiedremain reachable there. Instances remainWebCore::JSBlobcells; only the structure/prototype differs.The
m_namecachedWriteBarrierstays onJSBlob(via thevalueslist in the class definition) so the Rust-side name cache continues to work.Verification
blob: can set lastModified propertyis the exact scenario from #14257 (assigninglastModifiedon aBloband in aBlobsubclass constructor now creates an own data property, as in Node;File.prototype.lastModifiedstays read-only).Existing tests in
blob.test.ts,globals.test.js,FormData.test.ts,structured-clone.test.ts,blob-file-name-ownership.test.tspass.Fixes #20700
Fixes #14257
Relationship to #30328
#30328 is the PR landing the prototype split itself (
File.prototypedistinct from and inheritingBlob.prototype,Symbol.toStringTag,constructor, ordinaryinstanceof; it resolves #14102 and #25422). #32430 and #31656 were closed in its favor. #30328 keepsnameandlastModifiedonBlob.prototype(while also defining them onFile.prototype), so this PR stays open for removing them fromBlob.prototype(#20700, #14257). The prototype plumbing here duplicates #30328 and will be dropped once that lands; what remains is theresponse.classes.tschange plus the question below. #32425 (a setter onBlob.prototype.lastModified) was closed as the narrower alternative to this.Point for maintainers: once the accessors leave
Blob.prototype, something has to keep the documentedBun.file().name/.lastModifiedworking. This PR does that by havingBun.file(),Bun.stdin/stdout/stderr, embedded files andS3Fileinherit fromFile.prototype, which also makesBun.file(path) instanceof Filetrue (it is false today, and #30328 leaves it false). An alternative would be a separate BunFile prototype carrying those two accessors.no test proof · iteration 16 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/structured-clone-blob-file.test.ts, test/js/web/html/FormData-multipart-serialization.test.ts, test/js/web/fetch/blob.test.ts, test/js/bun/util/inspect.test.js, test/bundler/bundler_compile.test.ts