Skip to content

Move name and lastModified from Blob.prototype to File.prototype - #32434

Closed
robobun wants to merge 2 commits into
mainfrom
farm/0605fa29/blob-name-prototype
Closed

robobun wants to merge 2 commits into
mainfrom
farm/0605fa29/blob-name-prototype

Conversation

@robobun

@robobun robobun commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

"name" in new Blob()                                    // true   (expected false)
"lastModified" in new Blob()                            // true   (expected false)
File.prototype === Blob.prototype                       // true   (expected false)
Object.getPrototypeOf(File.prototype) === Blob.prototype // false  (expected true)

Per the W3C File API, name and lastModified belong on File.prototype, not Blob.prototype. Node, Deno, Firefox and Chrome all return false for "name" in new Blob().

Cause

File did not have its own prototype. JSDOMFile.cpp pointed File.prototype directly at the JSBlobPrototype object and used JSBlobStructure() for new File():

// This is not quite right. But we'll fix it if someone files an issue about it.
object->putDirect(vm, vm.propertyNames->prototype, zigGlobal->JSBlobPrototype(), ...);

Because there was no separate File.prototype, the name and lastModified accessors were placed on Blob.prototype in response.classes.ts.

Fix

Add JSDOMFilePrototype ([[Prototype]] = Blob.prototype) carrying the name/lastModified accessors plus Symbol.toStringTag = "File", and a cached m_JSDOMFileStructure on ZigGlobalObject that points instances at it. The File constructor's own [[Prototype]] is now the Blob constructor and File.prototype.constructor === File. The Symbol.hasInstance override on File is removed since the prototype chain now makes default instanceof work.

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.prototype now chains through File.prototype so name/lastModified remain reachable there. Instances remain WebCore::JSBlob cells; only the structure/prototype differs.

The m_name cached WriteBarrier stays on JSBlob (via the values list in the class definition) so the Rust-side name cache continues to work.

Verification

$ bun bd test test/js/web/fetch/blob.test.ts -t "name and lastModified"
(pass) name and lastModified live on File.prototype, not Blob.prototype
$ USE_SYSTEM_BUN=1 bun test test/js/web/fetch/blob.test.ts -t "name and lastModified"
(fail) name and lastModified live on File.prototype, not Blob.prototype
$ bun bd test test/js/web/fetch/blob.test.ts -t "can set lastModified"
(pass) blob: can set lastModified property
$ USE_SYSTEM_BUN=1 bun test test/js/web/fetch/blob.test.ts -t "can set lastModified"
(fail) blob: can set lastModified property

blob: can set lastModified property is the exact scenario from #14257 (assigning lastModified on a Blob and in a Blob subclass constructor now creates an own data property, as in Node; File.prototype.lastModified stays read-only).

Existing tests in blob.test.ts, globals.test.js, FormData.test.ts, structured-clone.test.ts, blob-file-name-ownership.test.ts pass.

Fixes #20700
Fixes #14257

Relationship to #30328

#30328 is the PR landing the prototype split itself (File.prototype distinct from and inheriting Blob.prototype, Symbol.toStringTag, constructor, ordinary instanceof; it resolves #14102 and #25422). #32430 and #31656 were closed in its favor. #30328 keeps name and lastModified on Blob.prototype (while also defining them on File.prototype), so this PR stays open for removing them from Blob.prototype (#20700, #14257). The prototype plumbing here duplicates #30328 and will be dropped once that lands; what remains is the response.classes.ts change plus the question below. #32425 (a setter on Blob.prototype.lastModified) was closed as the narrower alternative to this.

Point for maintainers: once the accessors leave Blob.prototype, something has to keep the documented Bun.file().name / .lastModified working. This PR does that by having Bun.file(), Bun.stdin/stdout/stderr, embedded files and S3File inherit from File.prototype, which also makes Bun.file(path) instanceof File true (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

@coderabbitai

coderabbitai Bot commented Jun 16, 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

Replaces the previous JSDOMFile InternalFunction + Symbol.hasInstance implementation with a split JSDOMFilePrototype/JSDOMFileConstructor pair registered via LazyClassStructure. Moves name and lastModified from Blob.prototype to File.prototype, rewires all C++ and Rust FFI bindings accordingly, updates S3File's prototype chain, and adjusts tests to match the new behavior.

Changes

JSDOMFile prototype/constructor split and Blob property migration

Layer / File(s) Summary
JSDOMFile C++ prototype/constructor and ABI entry points
src/jsc/bindings/JSDOMFile.h, src/jsc/bindings/JSDOMFile.cpp
Declares new Zig ABI functions for name/lastModified, implements JSDOMFilePrototype with custom property getters/setters, implements JSDOMFileConstructor using JSDOMFileStructure(), adds initJSDOMFileClassStructure and BUN__createJSDOMFileUnsafely, removes createJSDOMFileConstructor and JSDOMFile__hasInstance. Header replaces createJSDOMFileConstructor declaration with initJSDOMFileClassStructure.
GlobalObject lazy class structure wiring
src/jsc/bindings/ZigGlobalObject.h, src/jsc/bindings/ZigGlobalObject.cpp, src/jsc/bindings/ZigGlobalObject.lut.txt
Replaces the m_JSDOMFileConstructor GC lazy member with m_JSDOMFileClassStructure (LazyClassStructure), updates JSDOMFileConstructor() accessor to derive from the class structure, adds JSDOMFileStructure() accessor, replaces the initLater call, and switches the lut.txt File entry from CellProperty to ClassStructure.
Rust/C++ FFI rewiring and Blob-to-JS routing
src/jsc/bindings/blob.cpp, src/runtime/webcore/Blob.rs
Renames the extern-C binding from Blob__create to BUN__createJSDOMFileUnsafely in blob.cpp and updates both call sites. In Blob.rs, introduces BUN__createJSDOMFileUnsafely FFI, dom_file_to_js_unchecked helper, host ABI functions for File.prototype.name/lastModified, early routing in to_js for is_jsdom_file/is_bun_file blobs, clears is_jsdom_file on slice, removes the JSDOMFile__hasInstance export, and updates Bun.file() to use dom_file_to_js_unchecked.
Blob class definition and S3File prototype chain
src/runtime/webcore/response.classes.ts, src/jsc/bindings/JSS3File.cpp
Adds "name" to Blob's values list for instance caching and removes name/lastModified proto entries from Blob. JSS3File::createStructure switches superPrototype from JSBlobPrototype() to JSDOMFileStructure()->storedPrototypeObject().
FormData, Archive, BunObject, and Body integration
src/jsc/bindings/DOMFormData.cpp, src/runtime/api/Archive.rs, src/runtime/api/BunObject.rs, src/runtime/webcore/Body.rs
Updates DOMFormData::append and DOMFormData::set to normalize null filenames as emptyString and apply unpaired-surrogate replacement only for non-null filenames. Updates Archive.files() FilesContext, BunObject.get_embedded_files, and stdio_stores.make_blob to route through dom_file_to_js_unchecked for proper File wrapper creation. Updates Body.resolve and Body.get_blob_with_this_value to clear is_jsdom_file so converted blobs are treated as plain Blobs.
Test updates for File/Blob property split
test/js/bun/util/inspect.test.js, test/js/web/fetch/blob.test.ts
Removes Blob name field assertions from inspect test. Updates two existing assertions to expect numeric own-property assignment on Blob.name. Adds tests verifying name/lastModified live on File.prototype not Blob.prototype, slice returns plain Blob, and Bun.file().constructor resolves to File before the File global is otherwise touched.

Possibly related PRs

  • oven-sh/bun#31579: Both PRs touch src/runtime/webcore/Blob.rs in the jsdom/file wrapping path—main PR adds/rewires dom_file_to_js_unchecked and File.prototype accessors, while the other PR refactors how File/Blob filename data (stored_name/PathLike::String) is represented after deleting PathString—so they are directly connected at the code level.

Suggested reviewers

  • alii
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description check ✅ Passed 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 infor…
Title check ✅ Passed The title clearly and concisely identifies the primary change: moving name and lastModified from Blob.prototype to File.prototype.
Full details: Description check

Explanation

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 @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:58 PM PT - Aug 25th, 2026

❌ @robobun, your commit b639819 has 1 failures in Build #106018 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32434

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

bun-32434 --bun

@robobun robobun mentioned this pull request Jun 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. BunFile should extend Web File #16850 - PR makes Bun.file() return instanceof File with proper File.prototype chain, directly addressing the request for BunFile to extend Web File
  2. api to check if value is an instance of BunFile #10481 - PR enables instanceof File checks for BunFile instances, providing the requested API for checking if a value is a BunFile

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

Fixes #16850
Fixes #10481

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Give File its own prototype with Symbol.toStringTag "File" #32430 - Same architectural fix (separate JSDOMFilePrototype inheriting from Blob.prototype), fixes File symbol is Blob instead of File #14102; explicitly superseded by this PR
  2. fix(File): set Symbol.toStringTag to "File" #31656 - Fixes the same issue (File symbol is Blob instead of File #14102) by setting Symbol.toStringTag = "File" per-instance rather than via prototype
  3. Give File its own prototype that inherits from Blob.prototype #30328 - Fixes instanceof File behavior via patched customHasInstance; this PR's prototype restructuring makes that workaround unnecessary

🤖 Generated with Claude Code

@robobun

robobun commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Ready for review at b639819 (rebased onto current main, MERGEABLE, all review threads resolved).

One test on main needed adapting after the latest rebase: worker_blob.test.ts (from #40436) read a File's name off (await fetch(blobUrl)).blob(). Body.blob() returns a plain Blob under this PR, matching the Fetch spec and browsers, so the test now gets the registered File via resolveObjectURL instead. Both paths go through the same registry dupe, so the cross-thread name-string scenario that test guards is unchanged, and a fetch() of each URL stays in the loop. See commit b639819.

The change set has otherwise been stable since the serialization v5 bump and the BunFile.slice(): Blob types fix; the rebases since only adapted to refactors on main. CI on this head (build 106018): 181 passed, 1 failed. The failure is test/cli/run/require-cache.test.ts on Windows 2019 x64, an RSS-threshold test for transpiled require() output (173 MB vs a 64 MB limit); this PR touches no transpiler or module-cache code. Reported to main-break triage. Every other lane is green, including worker_blob.test.ts after the adaptation above.

Deferred as follow-ups per review discussion: the File.prototype.name brand check accepts plain Blob receivers (no distinct File ClassInfo to key on), and FormData defaults a nameless Blob entry to "" rather than the spec "blob" (needs the Blob/File bit threaded into DOMFormData).

Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/jsc/bindings/JSDOMFile.cpp Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved

@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: 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 win

Release the ThrowScope on the throwing tail call.

throwTypeError leaves a pending exception; return through RELEASE_AND_RETURN so 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 win

Check for constructor exceptions before wrapping ptr.

JSDOMFile__construct parses/coerces constructor arguments and can throw or run JS. The returned native pointer is wrapped without RETURN_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

📥 Commits

Reviewing files that changed from the base of the PR and between 91ce3b4 and 4d7252d.

📒 Files selected for processing (11)
  • src/jsc/bindings/JSDOMFile.cpp
  • src/jsc/bindings/JSDOMFile.h
  • src/jsc/bindings/JSS3File.cpp
  • src/jsc/bindings/ZigGlobalObject.cpp
  • src/jsc/bindings/ZigGlobalObject.h
  • src/jsc/bindings/ZigGlobalObject.lut.txt
  • src/jsc/bindings/blob.cpp
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/response.classes.ts
  • test/js/bun/util/inspect.test.js
  • test/js/web/fetch/blob.test.ts
💤 Files with no reviewable changes (1)
  • test/js/bun/util/inspect.test.js

Comment thread src/jsc/bindings/JSDOMFile.cpp Resolved
Comment thread src/jsc/bindings/JSDOMFile.cpp Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/jsc/bindings/blob.cpp Resolved

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d7252d and 8b03308.

📒 Files selected for processing (2)
  • src/runtime/webcore/Blob.rs
  • test/js/web/fetch/blob.test.ts

Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/jsc/bindings/blob.cpp Resolved
Comment thread src/runtime/webcore/response.classes.ts Resolved

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b03308 and 1f3ea85.

📒 Files selected for processing (3)
  • src/jsc/bindings/DOMFormData.cpp
  • src/jsc/bindings/blob.cpp
  • src/runtime/api/Archive.rs

Comment thread src/jsc/bindings/DOMFormData.cpp Resolved
Comment thread src/runtime/webcore/response.classes.ts Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/jsc/bindings/JSDOMFile.cpp Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/api/BunObject.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/api/BunObject.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/jsc/bindings/JSDOMFile.cpp Resolved
Comment thread test/js/web/fetch/blob.test.ts Resolved
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Do you need to make it so toJS on Blob when is_jsdom_file creates the File object instead of the Blob ojbect?

@robobun

robobun commented Jun 20, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, done in f329ef6. to_js() now branches on is_jsdom_file (after the existing is_s3() check) and routes to the File structure, so is_jsdom_file is the single source of truth for which prototype a wrapper gets:

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, construct_bun_file and stdio_stores::make_blob now set is_jsdom_file = true on creation (previously they only called dom_file_to_js_unchecked directly, so the JS prototype was right but the Rust flag was still false). With the flag set at the source, structuredClone / resolveObjectURL / Bun.inspect all see the same state the wrapper has, and the per-call-site is_jsdom_file || is_bun_file() branches in deserialize and ObjectURLRegistry are gone.

I did not fold is_bun_file() into the to_js() check because Response(Bun.file(path)).blob() returns a blob that still shares the Data::File store (so is_bun_file() is true) but must be Blob.prototype per the Fetch spec; keying on is_jsdom_file alone and clearing it in Body.blob() keeps that path correct.

One knock-on: now that Bun.file(fd) and new File([], "") are File-prototyped and is_jsdom_file=true, File.prototype.name returns "" instead of undefined when there is no backing path (File.name is a USVString in the spec, so this also brings new File([], "").name in line with Node and browsers). Updated the two FormData assertions that checked for undefined on a File-wrapped entry.

@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (273 commits of drift) and squashed the 17 WIP commits into one. Head is now 5fb5f36; the net diff is unchanged apart from one conflict resolution.

The only conflict was src/jsc/bindings/ZigGlobalObject.lut.txt. It looked like a whole-file conflict because main converted the file from CRLF to LF, so every line showed as changed. I took main's version and re-applied my single line, moving the File entry out of the CellProperty block and into the ClassStructure block where it now belongs:

-  File                            GlobalObject::m_JSDOMFileConstructor                 CellProperty
   crypto                          GlobalObject::m_cryptoObject                         CellProperty
 ...
   Crypto                          GlobalObject::m_JSCrypto                             ClassStructure
+  File                            GlobalObject::m_JSDOMFileClassStructure              ClassStructure

main also moved under ZigGlobalObject.cpp/h, Blob.rs, Body.rs, BunObject.rs, Archive.rs and three of the test files; those all merged cleanly and I verified each of my hunks is still present and correct against the new base.

Re-verified on the rebased tree:

  • blob.test.ts, inspect.test.js, FormData.test.ts, FormData-multipart-serialization.test.ts: 237 pass, 0 fail
  • body.test.ts, structured-clone.test.ts, structured-clone-blob-file.test.ts, bun-file.test.ts, archive.test.ts, structuredClone-classes.test.ts: 762 pass, 0 fail
  • compile/Bun.embeddedFiles: pass
  • cargo clippy -p bun_runtime: clean
  • USE_SYSTEM_BUN=1 still fails the new name and lastModified live on File.prototype test, as expected

@robobun

robobun commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (511caaa) and re-verified. Every case from the File/Blob prototype report now matches Node:

File.prototype === Blob.prototype           false
f.constructor.name                          File
"name" in new Blob(["b"])                   false
"lastModified" in new Blob(["b"])           false
File.prototype.x = 7; new Blob(["b"]).x     undefined
structuredClone(f).constructor.name         File
new Blob(["b"]) instanceof File             false
Object.getPrototypeOf(File.prototype) === Blob.prototype   true
Object.prototype.toString.call(f)           [object File]
f.slice().constructor.name                  Blob

Added explicit assertions for file.constructor, Object.prototype.toString.call(file), and the prototype-patch isolation case to test/js/web/fetch/blob.test.ts.

Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
@robobun
robobun requested a review from alii as a code owner August 16, 2026 21:18

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

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.

@robobun
robobun force-pushed the farm/0605fa29/blob-name-prototype branch from ac2df5c to 7ab3b5f Compare August 21, 2026 00:40
@robobun

robobun commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main again (151 commits); head is 7ab3b5f, still one squashed commit.

This time the conflicts were with #39770 (binary-size trim), which restructured the JSC wiring this PR adds to:

  • ZigGlobalObject.cpp: the per-member initLater lambdas became offset tables. The m_JSDOMFileClassStructure init is now an entry in lazyClassStructureInits (same shape as the Dirent entry), and main's converted entry for the removed m_JSDOMFileConstructor is deleted from lazyObjectInits. Net diff in that file is the one three-line table entry plus that removal.
  • ZigGlobalObject.lut.txt: generated classes moved into m_generatedLazyClasses[...]; File is hand-written so it keeps its own m_JSDOMFileClassStructure slot, inserted into main's block.
  • JSDOMFile.cpp: main's one-line change was to the old class this PR deletes. Dropped it, and switched this PR's own createStructure / reifyStaticProperties / toStringTag calls to the Bun::createClassStructure / reifyStaticPropertyTable / putToStringTagWithoutTransition helpers Trim ~2 MB from the release binary without touching hot paths #39770 introduced, so the new code follows the convention main now uses. These are thin wrappers with identical semantics; File.prototype[Symbol.toStringTag], File.prototype.constructor, and the S3File chain were re-checked directly.

Re-verified on the rebased tree: blob, inspect, FormData, FormData-multipart-serialization, structured-clone-blob-file, archive (498 pass), compile/Bun.embeddedFiles, bun-types integration (15 pass), and the headline test still fails against the released binary.

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

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.

@robobun
robobun force-pushed the farm/0605fa29/blob-name-prototype branch from 7ab3b5f to 4ccf649 Compare August 24, 2026 04:52
@robobun

robobun commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main again (147 commits); head is 4ccf649, still one squashed commit.

Two small conflicts, both from #40238 (bun_core::String now owns its WTF ref):

  • blob.cpp: Blob__setAsFile takes const BunString* on main. Kept main's signature alongside the BUN__createJSDOMFileUnsafely extern this PR adds.
  • BunObject.rs (Bun.embeddedFiles): main replaced .dupe_ref() with .clone() on the name copy. Took main's lines as-is; this PR no longer needs a change there since file_blob() tags the cached blob and dupe() carries the flag.

Re-verified on the rebased tree: blob, inspect, FormData, FormData-multipart-serialization, structured-clone-blob-file, archive (499 pass), compile/Bun.embeddedFiles, bun-types integration (17 pass), and the headline test still fails against the released binary.

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

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.

@robobun
robobun force-pushed the farm/0605fa29/blob-name-prototype branch from 4ccf649 to fddbb44 Compare August 25, 2026 06:33
@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main again (20 commits); head is fddbb44, still one squashed commit.

One conflict, in JSDOMFile.cpp, from #40410 (jsc-exception-lint): on main it hoisted the throw scope to the top of the old JSDOMFile::construct and added a RETURN_IF_EXCEPTION after JSDOMFile__construct. Both of those merged into this PR's JSDOMFileConstructor::construct cleanly; the conflict was only the now-redundant inner scope declaration, which I removed to match. Also hand-checked the rest of this file against the lint's rule: every call that can throw (JSDOMFile__getName / __getLastModified / __construct, getFunctionRealm, createSubclassStructure) is followed by a RETURN_IF_EXCEPTION or a RELEASE_AND_RETURN.

Re-verified on the rebased tree: blob, inspect, FormData, FormData-multipart-serialization, structured-clone-blob-file, archive (499 pass), compile/Bun.embeddedFiles, bun-types integration (17 pass), the new File() throw and subclass paths directly, and the headline test still fails against the released binary.

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

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
@robobun
robobun force-pushed the farm/0605fa29/blob-name-prototype branch from fddbb44 to b7ea2e0 Compare August 26, 2026 02:27
@robobun

robobun commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main again (19 commits); head is b7ea2e0, still one squashed commit.

One conflict, in standalone_graph_jsc.rs: #40436 restructured file_blob into a process-wide template_blob() that each VM dupes and stamps. The is_jsdom_file flag this PR adds now sits on the template (right after Blob::default()), so every per-VM dupe inherits it. Net diff in that file is two lines.

Two follow-on adjustments from #40374 (Utf8Bytes<'a> lifetimes) in Blob.rs, both in the Bun.inspect name-line check: get_file_name() now prefers blob.name over the store path, so comparing against it would have hidden the name of new File([bunFile], "custom.txt"); switched to the new store_path(), which is exactly what the FileRef header prints. The existing inspect test caught this.

Re-verified on the rebased tree: blob, inspect, FormData, FormData-multipart-serialization, structured-clone-blob-file, archive (500 pass), compile/Bun.embeddedFiles (exercises the new template path), bun-types integration (17 pass), and the headline test still fails against the released binary.

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.

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

Code review found no issues

No high-confidence issues detected in this change.

Jarred-Sumner pushed a commit that referenced this pull request Sep 14, 2026
…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 -->
usrbinkat pushed a commit to usrbinkat/bun that referenced this pull request Sep 15, 2026
…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 -->
@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@robobun robobun closed this Nov 17, 2026
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.

Blob has name Blob LastModified incompatibility with Node File symbol is Blob instead of File

2 participants