Skip to content

Do not give Bun classes the JSType of InternalFieldTuple or JSWeakSet - #48869

Open
robobun wants to merge 2 commits into
mainfrom
robobun/d28c9e5d/jsc-owned-jstypes
Open

robobun wants to merge 2 commits into
mainfrom
robobun/d28c9e5d/jsc-owned-jstypes

Conversation

@robobun

@robobun robobun commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • JSC casts to InternalFieldTuple and JSWeakSet by one byte of the cell header, the JSType. Three Bun classes have one of those bytes: ErrorCodeCache (src/jsc/bindings/ErrorCode.cpp:172), InternalModuleRegistry (InternalModuleRegistry.cpp:384), ActiveSpySet (JSMockFunction.cpp:147).
  • An inspector client gets a handle to any cell. stmt.native.run(cache) then writes into the ErrorCodeCache, and the next AbortError is a SIGSEGV. Debug builds abort at ASSERT(canCast == from->JSCell::inheritsSlow(To::info())).
  • No issue reports this. InternalFieldTuple: cast by JSType instead of walking ClassInfo WebKit#410 left the first two classes to Bun.

Fix

  • All three Structures use ObjectType. The release binary changes in 7 bytes and no instruction.
  • Verified: two new tests in test/js/bun/jsc/bun-jsc.test.ts. Bun 1.4.2 and a release build of main fail both. Also the mock, bun:sqlite and buffer suites.
  • Self-reviewed: 5 concerns raised, 5 addressed (Notes).

Background

  • ErrorCodeCache holds a realm's Structures for Node error codes. InternalModuleRegistry holds its internal modules. ActiveSpySet holds the mocks that clearAllMocks() visits.
  • bun:sqlite writes the changes of run() into the InternalFieldTuple it is given. Statement#native exposes that call.
  • bun test: restore spies in the order they were made, and keep mocks in ordered weak lists #48098 asks whether ActiveSpySet stays. This PR changes one token of it.
  • Considered a real JSC::JSWeakSet for the mock sets, a debug assert in Structure::validateFlags, and a source lint. Each needs these edits first.

Downsides

  • util.types.isWeakSet() is now false for a handle to an ActiveSpySet. Only an inspector client has one.
  • Nothing stops a fourth class from taking a JSC-owned JSType. The tests read one fresh realm.
  • An inspector client can still pass a real InternalFieldTuple to stmt.native.run().
Notes

History. oven-sh/WebKit#410 made the cast to InternalFieldTuple a JSType compare, and InternalFieldTuple.h:14 now says that nothing else may create a Structure with that type. Its description left the two ObjectType lines to the Bun PR that bumped WebKit, which was #37728. Another bump (#38013) moved the pin first, and #37728 closed on inactivity with no review. This PR takes its two hunks unchanged and adds the third class and the tests.

Why one token for ActiveSpySet. getWeakSet (WeakSetPrototype.cpp:63) casts by JSType, so with ObjectType the WeakSet functions refuse the cell. The collector is unaffected: the subspace comes from the C++ type (WeakMapImpl::subspaceFor), and Heap.cpp reconciles every cell of vm.weakSetSpace through WeakMapImpl, which the class still is. An earlier cut of this branch replaced the class with JSC::JSWeakSet. That makes WeakSet.prototype.add legal on the sets, which needs a checked downcast in forEachIn and a test for it, and it rewrites the code that #48098 replaces. The storage of the sets is #48098's question (its Question 2).

WebKit side (oven-sh/WebKit at the pinned de043228c294):

Self-review. Five concerns: use the same token at the third site (done), add a fixture for the crash (done, the second test), the inspector test of the earlier cut could not fail on a release build (dropped with the check it tested), the check covered one of two sites (dropped), and the description (rewritten). Not taken: deleting static_assert(std::is_final<ActiveSpySet>...). It still holds, and #48098 deletes the class.

Measurements (linux x64, bun run build:release at b6e7b9c and at this branch, same machine):

  • Release binary: stripped bun is 155,269,392 bytes before and after. Every loaded section has the same size (size -A), and no symbol changes size (nm -S). Seven bytes of .text differ: the JSType operand in ErrorCodeCache::createStructure and InternalModuleRegistry::createStructure (0x66 to 0x22) and in the initializer of activeSpySetStructure (0x5d to 0x22), and four __LINE__ operands in JSMockFunction.cpp (the added comment line).
  • ErrorCodeCache::createStructure and InternalModuleRegistry::createStructure: 59 instructions and 222 bytes each, before and after.
  • First mock in a realm (heapStats().objectTypeCounts delta): +146 cells and +85 Structures, before and after.
  • Instructions added per mock call, internal require, coded error, and per restoreAllMocks() or clearAllMocks() entry: 0.
  • Host functions added: 0. bun:internal-for-testing entries added: 0. Codegen inputs changed: 0.
  • Type-byte test: Bun 1.4.2 and a release build of main fail, listing ErrorCodeCache, InternalModuleRegistry and ActiveSpySet. Reverting one token alone brings back exactly its class.
  • Crash fixture: on Bun 1.4.2 and a release build of main the inspectee ends with SIGSEGV. With only ErrorCode.cpp fixed it fails with "ffi":"number". On a debug build of main it fails by its timeout: the inspectee needs about 7 s to print the assertion's backtrace and abort.
  • New tests on debug+ASAN, 5 runs each: type-byte test 0.55 to 0.70 s (1 child process, 1 heap snapshot). Crash fixture 0.82 to 1.09 s (1 child process with --inspect).

The type-byte test. It takes generateHeapSnapshotForDebugging(), which has each cell's address and class name, and reads JSCell::m_type (offset 5, which JSCell.h pins with a static_assert) with bun:ffi. It reads only the cells that the global object references, because those stay alive between the snapshot and the read.

The crash fixture. It attaches to a child with --inspect after the child prints that its setup is done, takes Heap.snapshot, gets the ErrorCodeCache and the InternalModuleRegistry with Heap.getRemoteObject, and passes each to statement.native.run(). It passes only if each run() returned and inserted its row. run() writes fields 0 and 1. In the cache those are the Structures of ABORT_ERR and ERR_ACCESS_DENIED. In the registry field 1 is bun:ffi, so that half stops testing if a new module sorts before bun/ffi.ts. The type-byte test still covers the registry then.

Suites. bun bd test (debug+ASAN): bun-jsc.test.ts, mock-fn.test.js, spyMatchers.test.ts, mock-disposable.test.ts: 1054 pass. test/js/bun/test/mock/, sqlite.test.js, vi-utils.test.ts, vitest-flavor.test.ts: 1515 pass and 3 failures that this change does not cause: #13082 runs 198 full collections and passes the 5 s timeout, and macros-beside-tests.test.ts fails twice on debug log lines in the child's stdout. The same files and buffer.test.js on the release build of this branch: 3293 pass, 0 fail. Debug builds of main need the include from #48722 to compile. I applied it locally and it is not part of this PR.

Left for later. A debug assert in Structure::validateFlags that JSType and ClassInfo agree with the JSCast.h table would catch a fourth class at creation. It needs a WebKit PR and can land only after this one, because every realm creates the registry's Structure. JSType.h maps InternalFieldTupleType to SpecCellOther although the class is a JSObject.


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/bun/jsc/bun-jsc.test.ts

JSC casts to InternalFieldTuple (since oven-sh/WebKit#410) and to
JSWeakSet by the JSType byte of a cell alone, the table in JSCast.h. A
cell of another class that has one of those bytes passes for one.

ErrorCodeCache and InternalModuleRegistry created their Structures with
InternalFieldTupleType, and ActiveSpySet with JSWeakSetType. None of
them is the class that owns the type. All three now use ObjectType.

bun:sqlite writes the changes of a run() into the InternalFieldTuple it
is given. With a handle to the ErrorCodeCache, which an inspector
client can get, that write replaced the Structure of ABORT_ERR, and the
next AbortError crashed.
@robobun

robobun commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

Status: ready for review.

Reproduction: run the two new tests of test/js/bun/jsc/bun-jsc.test.ts (-t 'JSType of InternalFieldTuple|Statement#native.run'). Bun 1.4.2 and a release build of main fail both. The type-byte test lists ErrorCodeCache, InternalModuleRegistry and ActiveSpySet. In the crash fixture the inspectee ends with SIGSEGV. Both tests pass on this branch, on a debug+ASAN build and on a release build.

@robobun

robobun commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:47 PM PT - Nov 13th, 2026

✅ @robobun, your commit 397b1b10b84b58c8f9fe385f56b2c166d7d785c6 passed in Build #141222! 🎉


🧪   To try this PR locally:

bunx bun-pr 48869

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

bun-48869 --bun

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Three JSC structure definitions now use ObjectType instead of specialized type bytes. Two regression tests check heap-snapshot type bytes and inspector-driven calls to Statement#native.run().

Changes

JSC Cell-Type Handling

Layer / File(s) Summary
Structure type assignments
src/jsc/bindings/ErrorCode.cpp, src/jsc/bindings/InternalModuleRegistry.cpp, src/jsc/bindings/JSMockFunction.cpp
ErrorCodeCache, InternalModuleRegistry, and ActiveSpySet now use ObjectType when creating their structures. A comment notes JSC’s JSWeakSet cast behavior for ActiveSpySet.
Type-byte regression tests
test/js/bun/jsc/bun-jsc.test.ts
Tests check the JSType bytes of observed heap-snapshot cells. An inspector-driven test passes ErrorCodeCache and InternalModuleRegistry cells to Statement#native.run() and checks that both calls return, ABORT_ERR remains intact, bun:ffi remains loadable, and two rows were inserted.

Suggested reviewers: jarred-sumner, dylan-conway

Merge Risk: Minimal · up to 397b1

This change stops three internal Bun classes from being mistaken for JSC's InternalFieldTuple and JSWeakSet. That mix-up could cause memory corruption when an inspector client passes a handle to a native call. The change is small and is covered by new tests, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: Bun classes no longer receive the JSType of InternalFieldTuple or JSWeakSet. The raw summary confirms that ErrorCodeCache, InternalModuleRegistry, and ActiveSpySet now…
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 follows the repository template, which has two sections: "What does this PR do?" and "How did you verify your code works?". The Problem and Fix sections cover the first section. The Fi…
Full details: Title check

Explanation

The title names the main change: Bun classes no longer receive the JSType of InternalFieldTuple or JSWeakSet. The raw summary confirms that ErrorCodeCache, InternalModuleRegistry, and ActiveSpySet now use ObjectType. The title is specific and matches the changeset.

Full details: Description check

Explanation

The description follows the repository template, which has two sections: "What does this PR do?" and "How did you verify your code works?". The Problem and Fix sections cover the first section. The Fix section and the Notes block cover the verification details: the two new tests, the failing runs on Bun 1.4.2 and a release build of main, the debug+ASAN and release suite results, and the measured binary size and instruction changes. The description states the root cause, the three changed Structures, the reasoning for using ObjectType, and the downsides. Two gaps remain. First, the PR evidence section says the bun-jsc.test.ts file did not run on the author's machine and defers to CI. Second, the debug build of main needs an include from another PR (#48722) to compile, and the author applied that include only locally. These gaps do not make the description incomplete, but the verification status for the main test file is not confirmed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 6b9b286 and 397b1b1.

Files selected for processing: 1

  • test/js/bun/jsc/bun-jsc.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

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

Beyond the inline findings, I also checked for other Bun classes borrowing a JSC built-in JSType: the only remaining TypeInfo(JSFunctionType, ...) sites (src/jsc/bindings/JSFFIFunction.h:73, src/jsc/bindings/napi.h:967, src/jsc/bindings/sqlite/JSSQLStatement.h:73) are all final subclasses of JSC::JSFunction, so they are not the same defect. The two ActiveSpySet users in JSMockFunction.cpp (lines 941 and 1177) use uncheckedDowncast, so the type-byte change does not affect them. Not done here: the claim that JSCast.h casts InternalFieldTuple/JSWeakSet by the JSType byte alone could not be checked against WebKit sources (not vendored in this checkout), and no tests were run.

Extended reasoning...

The change is three one-token JSType edits in createStructure for ErrorCodeCache, InternalModuleRegistry and ActiveSpySet (InternalFieldTupleType/JSWeakSetType to ObjectType) plus two new subprocess tests in bun-jsc.test.ts; it touches no auth, crypto or input-parsing surface, and no CODEOWNERS entry covers the changed files. The two inline findings concern test robustness (a discarded callFunctionOn reply and an unordered Heap.snapshot after inspectee startup), which is why a human look remains worthwhile rather than approving outright.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread test/js/bun/jsc/bun-jsc.test.ts Resolved
Comment thread test/js/bun/jsc/bun-jsc.test.ts Resolved
…hat run() returned

The inspector takes commands before the inspectee has run its module. The
fixture now waits for a line that the inspectee prints when its setup is
done, so the heap snapshot has the ErrorCodeCache and the statement exists.

The fixture also reads each reply of Runtime.callFunctionOn and counts the
rows that the statement inserted. It passes only if run() returned for both
cells.

@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 re-reviewed after 397b1b1: both inline points from my earlier pass (asserting that run() actually returned, and ordering the snapshot after the inspectee's setup via a readiness line) are addressed in the current test, and I found no bugs in this version. Because the change alters the JSType of cells that live in every realm (InternalModuleRegistry is read by $getInternalField from every builtin) and leaves an ObjectType cell in vm.weakSetSpace, a human familiar with the JSC side should still take a look.

What was reviewed:

  • Searched src/ for any other Structure::create/createClassStructure using InternalFieldTupleType, JSWeakSetType or JSWeakMapType — none remain; the remaining JSFunctionType/InternalFunctionType/FinalObjectType sites belong to classes of those bases.
  • Confirmed nothing in src/ downcasts ErrorCodeCache/InternalModuleRegistry to InternalFieldTuple or ActiveSpySet to JSWeakSet (all ActiveSpySet uses are uncheckedDowncast<ActiveSpySet>), and that putChanges in JSSQLStatement.cpp:1374 is the write the fixture exercises (fields 0 and 1 = ABORT_ERR / ERR_ACCESS_DENIED in ErrorCode.ts).
  • Not done here: running the new tests or the mock/sqlite suites, and checking the WebKit side (Heap.cpp's weakSetSpace finalization, JSCast.h table) — the WebKit sources are not in this checkout, so the claim that the collector is unaffected by ActiveSpySet no longer carrying JSWeakSetType rests on the PR's own measurements.
Extended reasoning...

The diff changes one token in each of three createStructure calls (src/jsc/bindings/ErrorCode.cpp, InternalModuleRegistry.cpp, JSMockFunction.cpp) from InternalFieldTupleType/JSWeakSetType to ObjectType, plus one explanatory comment, and adds two tests to test/js/bun/jsc/bun-jsc.test.ts: a heap-snapshot plus bun:ffi type-byte scan, and an inspector-protocol fixture that passes the two cells to Statement#native.run(). It touches no injection, auth or data-exposure surface; the bug it fixes is only reachable by an inspector client. The follow-up commit addressed both of my earlier inline findings, there is no CHANGES_REQUESTED review, and the changed paths have no CODEOWNER. Deferring rather than approving because the engine-level consequences (an ObjectType cell in weakSetSpace, DFG speculation on the registry) could not be verified against WebKit sources from this checkout and no tests were run in this review.

This branch has not been deployed

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

2 participants