Repository navigation
InternalFieldTuple: cast by JSType instead of walking ClassInfo - #410
Conversation
InternalFieldTuple has had its own JSType (InternalFieldTupleType) but was not listed in FOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD, so every dynamicDowncast<InternalFieldTuple> went through JSCell::inherits: decode the StructureID, load the Structure, load its ClassInfo, then chase parentClass until InternalFieldTuple::s_info or null. The non-tuple case, which is the common one, walks the whole chain. This cast sits on the promise reaction / await resumption path (AsyncContextSwapScope:: unwrapContextTuple, used by the JSMicrotask.cpp jobs and Interpreter.cpp), so every reaction paid for it. Add the overload so the cast becomes a compare of the type byte in the cell header. Every InternalFieldTuple is created with the Structure from InternalFieldTuple::createStructure, which is the only place JSC uses InternalFieldTupleType, so the JSType identifies the class exactly; the class is now final to keep it that way. While here, make create(vm, structure, a, b) construct the cell and store a and b directly instead of going through create(vm, structure), which stored undefined into both fields first (four barriered stores per tuple instead of two). create(vm, structure) keeps its behaviour of initialising both fields to undefined.
|
Warning Review limit reached
Next review available in: 1 minute Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
Comment |
…leType Both classes copied their Structure setup from InternalFieldTuple, including its JSType. oven-sh/WebKit#410 makes dynamicDowncast<InternalFieldTuple> check that JSType instead of walking ClassInfo, which requires the type to mean InternalFieldTuple and nothing else. Create these two structures with ObjectType instead, which is what the other internal-field objects in this directory (JSNextTickQueue, JSSocketHandlers, ModuleLoader, BunStreamSource) already use. Neither object is ever handed to a site that casts to InternalFieldTuple, so nothing observable changes; this keeps the JSType mapping exact before the WebKit bump lands.
There was a problem hiding this comment.
LGTM — mechanical addition to the JSType cast overload list plus a small create() cleanup.
What was reviewed:
- Confirmed
InternalFieldTupleTypeis exclusive toInternalFieldTuple::createStructurein this tree;finalnow enforces no subclassing. protected→privateis safe:DECLARE_VISIT_CHILDREN_WITH_MODIFIERresets access internally, andfinishCreation/ctor are only used by the in-classcreate().create()refactor is behaviorally identical (DECLARE_DEFAULT_FINISH_CREATIONdoes not touch internal fields), just drops the two redundant barriered stores.
Extended reasoning...
Overview
Two-file header-only change. JSCast.h gains one line adding InternalFieldTuple to FOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD_FORWARD_DECLARED, so InheritsTraits<InternalFieldTuple> is specialized to a single JSType byte compare instead of the generic ClassInfo chain walk. InternalFieldTuple.h marks the class final, moves the ctor block to private, adds a comment tying InternalFieldTupleType exclusivity to the cast, and inverts the two create overloads so the 4-arg form does the allocation and the 2-arg form delegates with jsUndefined().
Security risks
None. This is a type-dispatch optimization on an internal Bun-only helper class. The JSType-based cast path already carries a debug ASSERT(canCast == inheritsSlow(info())) in inheritsJSTypeImpl, so any future structure that reused InternalFieldTupleType without inheriting the class would trip debug/ASAN builds. Grep confirms the only TypeInfo(InternalFieldTupleType, ...) in this repo is InternalFieldTuple::createStructure (InternalFieldTuple.cpp:21), and no class derives from InternalFieldTuple. The author correctly flagged the two Bun-side classes that borrow this JSType and is fixing them in the paired Bun bump PR; that is outside this repo.
Level of scrutiny
Low-to-moderate. The pattern is identical to the ~50 other entries in the same macro list (e.g. JSGenerator, JSArrayIterator, WebAssemblyGCObjectBase on the line directly above). The create refactor is a trivial reordering — I checked DECLARE_DEFAULT_FINISH_CREATION (JSCell.h:81) and it only calls Base::finishCreation plus a debug assert, so writing a/b after it (rather than undefined then a/b) is equivalent. The access-specifier change from protected to private looked like it could affect visitChildren, but DECLARE_VISIT_CHILDREN_WITH_MODIFIER (SlotVisitorMacros.h:61) explicitly emits private:/public: labels internally, so visitChildren stays public regardless and CREATE_METHOD_TABLE in the .cpp is unaffected.
Other factors
The PR description includes before/after -O2 disassembly and a compile check against Bun's consuming TUs with ASSERT_ENABLED=1. No prior human reviews or outstanding comments on the timeline (only a rate-limited CodeRabbit placeholder). Small, self-contained, and follows an established pattern with a debug safety net.
Preview Builds
|
|
The Bun side of this is oven-sh/bun#48869. Bun's pin moved past this commit through another bump, without the two |
InternalFieldTuplehas its ownJSType(InternalFieldTupleType) but is not inFOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD, sodynamicDowncast<InternalFieldTuple>falls back toJSCell::inherits(): decode the StructureID, load the Structure, load its ClassInfo, then walkparentClassuntil it hitsInternalFieldTuple::s_infoor null. For the common case (the value is not a tuple) that is the full walk. The cast is on the promise reaction path:AsyncContextSwapScope::unwrapContextTuple(runtime/AsyncContextSwapScope.h) runs it for every reaction job inJSMicrotask.cpp(AsyncFunctionResume, then reactions, async generator steps, finally jobs) and inInterpreter.cpp, so everyawaitresumption in Bun pays for it.Change
JSCast.h: addmacro(InternalFieldTuple, JSType::InternalFieldTupleType, JSType::InternalFieldTupleType)to the forward-declared overload list, so the cast is a compare of the type byte in the cell header.InternalFieldTuple.h: the class isfinal, and a comment says whyInternalFieldTupleTypehas to stay exclusive to it. The ctor section becomesprivatesince nothing can derive any more.InternalFieldTuple::create(vm, structure, a, b)constructs the cell and storesaandbdirectly instead of callingcreate(vm, structure)first, which storedundefinedinto both fields and then overwrote them (four barriered stores per tuple instead of two).create(vm, structure)still initialises both fields toundefined.Why the JSType mapping is exact
In this tree
InternalFieldTupleTypeis only used byInternalFieldTuple::createStructure, nothing derives fromInternalFieldTuple, and everycreate()call site (here and in Bun) passesJSGlobalObject::internalFieldTupleStructure(), which comes from thatcreateStructure.inheritsJSTypeImplassertscanCast == inheritsSlow(info())on every cast in debug builds, so a future violation would fail loudly in Bun's debug/ASAN lanes.Bun itself has two classes (
ErrorCodeCache,InternalModuleRegistry) that reuseInternalFieldTupleTypefor their own structures. Neither is ever handed to a site that casts toInternalFieldTuple, but with this change they would pass the cast, so the Bun PR that bumps to this commit switches them toObjectType(what Bun's other internal-field objects already use).Verification
Compiled Bun's seven translation units that create,
dynamicDowncastoruncheckedDowncastInternalFieldTuple(AsyncContextFrame.cpp,JSSQLStatement.cpp,ReadableStreamOperations.cpp,JSReadRequest.cpp,NodeHTTP.cpp,ErrorCode.cpp,InternalModuleRegistry.cpp) against these headers with Bun's debug flags (ASSERT_ENABLED=1, so the asserting path is instantiated too); all compile.InheritsTraits<InternalFieldTuple>::typeRangeis now engaged (static_asserted in a probe TU; the same assert fails on the unmodified headers).-O2codegen ofdynamicDowncast<InternalFieldTuple>(JSValue)before and after, x86_64:before (ClassInfo walk)
after (JSType compare)
Bun's test suite will run against this PR's preview tarballs from the Bun bump PR; I will link it here.
Side note (not changed here)
JSType.hmapsInternalFieldTupleTypetoSpecCellOther, but the class is aJSObject, and every comparable JSC internal-field type (and the default for unlisted types inspeculatedTypeMapping) isSpecObjectOther. Bun's builtins only ever use these values as@getInternalField/@putInternalFieldoperands, so nothing observes it today; flagging it in case we want to fix it separately.