Skip to content

[JSC] getBytecodeIndex() gives a builtin frame its own bytecode index - #780

Open
robobun wants to merge 1 commit into
mainfrom
robobun/383c5f43/builtin-error-source-text
Open

robobun wants to merge 1 commit into
mainfrom
robobun/383c5f43/builtin-error-source-text

Conversation

@robobun

@robobun robobun commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • A JSC error raised in a Bun builtin module quotes the wrong source text. On a closed dgram socket, s.getSendQueueSize() says null is not an object (evaluating 'kStateSymbol') for this[kStateSymbol].handle.getSendQueueSize(). The position is right.
  • FindFirstCallerFrameWithCodeblockFunctor (runtime/Error.cpp:153), behind getBytecodeIndex(), returns a builtin's code block with bytecode index 0.
  • appendSourceToErrorMessage() quotes the text at that index: the function's first expression, or its head under a debugger.

Fix

  • Under USE(BUN_JSC_ADDITIONS) the functor takes the index from the frame that gives the code block.
  • Correct because appendSourceToErrorMessage() reads info and text from that one code block, like user code. Private builtins get no text (CI: one workflow, planned lanes, toolchain images, and the JavaScriptCore tests #645).
  • Verified: the new stress test fails without the hunk and passes with it in all 18 modes. JSTests/stress --quick: no new failure.
  • Self-reviewed: 7 concerns raised, 6 addressed. No issue tracks the leftovers in Notes.

Background

Downsides

  • Messages change: 160 of 339 engine messages with module source text in Bun 1.4.3.
  • Per error in a builtin: 167 more instructions the first time at an index, 11 fewer after.
  • Still wrong: some TDZ names, frames with private visibility, intrinsic ops (see Notes).
Notes

Repro. const s = require("node:dgram").createSocket("udp4"); s.close(); s.getSendQueueSize(); on Bun 1.4.3-canary.1. Upstream's two gate lines stay as they are under #else.

Supersedes #369. That PR removes the source text for every builtin and gives this gate as its reason. #645 later kept the text for builtins with a source URL and removed it for private builtins only.

Reports with the wrong text. oven-sh/bun#18869 has such a message as its title (null is not an object (evaluating 'http'), the access that failed is response.writeHead). The same function was reported again with other text in oven-sh/bun#39766.

More examples on Bun 1.4.3-canary.1 (release)

call message today code at the reported position
stream.Readable.prototype.read.call(undefined) (evaluating 'n') this._readableState
stream.Writable.prototype.write.call(undefined, "x") (evaluating 'stream') stream._writableState
fs.WriteStream.prototype._write.call(undefined, Buffer.alloc(1), "utf8", () => {}) (evaluating 'kWriteStreamFastPath') this[kWriteStreamFastPath]
net.Server.prototype.close.call(undefined) (evaluating 'kClusterListeningId') this[kClusterListeningId]
new stream.Readable({ read() {} }).pipe(undefined) (evaluating 'src') dest.on
new http.OutgoingMessage().addTrailers() (evaluating 'this._trailer = ""') ObjectKeys(headers), a host function makes the error

net.Socket.prototype.setTimeout.call(undefined, 1) is right today (this.destroyed), because that access is the first expression of the function.

Census. A script calls 744 prototype methods of 33 builtin modules with an undefined receiver. 356 calls end in an engine error whose top frame is a builtin module. 339 messages carry source text: 179 contain the reported column, 160 do not. With BUN_JSC_forceDebuggerBytecodeGeneration=1 (what an attached debugger turns on) every such message quotes the head of its function, the setTimeout one included: (near '...function _write(stream, chunk, enco...').

Why upstream is not affected. Upstream's BytecodeGenerator::emitExpressionInfo returns for every builtin, so hasExpressionInfo() is false and appendSourceToErrorMessage() returns first. The gate is from 87b1e4a822c7 (bug 243103). It mirrors Interpreter::getStackTrace, which gave a builtin frame no bytecode index. This fork already lifted that one under USE(ALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS) (interpreter/Interpreter.cpp:678), which is why the position is right. ExpressionInfo::Decoder::decode maps an index before the first entry to the first entry.

Proof in a debugger. On a debug Bun, bytecodeIndex arrives in appendSourceToErrorMessage() as 0 while the frame is at offset 7, 131 and 49 for the first three rows of the table. With the frame's offset written into the argument, the messages are stream._writableState, this._readableState and this[kWriteStreamFastPath].

The stress test makes builtins with a source URL through the jsc shell's builtinFromBytecodeCache(), from source and from encoded bytecode. It checks two fixed messages through the JIT tiers, that a private builtin keeps no text, and that ten ways to fail give the same message as the same function in user code. On a jsc without the hunk 7 of the 10 differ. The extra debugger-bytecode run uses --forceDebuggerBytecodeGeneration=true.

Test runs. Release jsc (-O2, USE_BUN_JSC_ADDITIONS, ALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS), built at 0c06faa with and without the hunk, and again on this branch. JSTests/stress --quick at 0c06faa: 21,898 pass and 13 fail without the hunk (4 are the new test), 21,903 pass and 8 fail with it. The 8 are memory-limit failures of my machine on both builds. No lane runs JSTests with assertions (lanes.mjs tests the two Linux lto lanes). A jsc of this branch with ENABLE_ASSERTS=ON passes the new test in all 18 modes. I did not run the rest of JSTests with it.

Not run against Bun. No Bun was built with this change. The Bun test below fails on 1.4.3-canary.1 with 'n', 'stream' and 'kWriteStreamFastPath'. Its three expected strings come from the debugger session above. It belongs in the Bun PR that first pins a commit with this change (test/js/bun/jsc/webkit-upgrade-9b02218df6.test.ts, beside the private-builtin case):

test("errors thrown inside Bun's builtin modules quote the expression that failed", () => {
  expect({
    read: messageOf(() => Readable.prototype.read.call(undefined as any)),
    write: messageOf(() => Writable.prototype.write.call(undefined as any, "x")),
    fsWrite: messageOf(() => fs.WriteStream.prototype._write.call(undefined as any, Buffer.alloc(1), "utf8", () => {})),
    // The access that fails is the first expression of setTimeout(), so this one is right today.
    setTimeout: messageOf(() => net.Socket.prototype.setTimeout.call(undefined as any, 1)),
  }).toEqual({
    read: "undefined is not an object (evaluating 'this._readableState')",
    write: "undefined is not an object (evaluating 'stream._writableState')",
    fsWrite: "undefined is not an object (evaluating 'this[kWriteStreamFastPath]')",
    setTimeout: "undefined is not an object (evaluating 'this.destroyed')",
  });
});

Cost, measured (release jsc, --useJIT=0, gdb stepi counts from entry to return)

without with
getBytecodeIndex(), user frame 295 281
getBytecodeIndex(), builtin frame 293 281
appendSourceToErrorMessage(), user frame, first and later error 14,251 / 13,182 14,251 / 13,182
appendSourceToErrorMessage(), builtin frame, first and later error 13,474 / 13,186 13,653 / 13,187
ExpressionInfo::Decoder::decode calls, 4 failing indices in one builtin, then 100 more rounds 2 / 2 24 / 24
calls of getBytecodeIndex / appendSourceToErrorMessage / StackVisitor for 12 engine errors 12 / 12 / 48 12 / 12 / 48
the same for 2,000 calls and 2,000 new Error with no engine error 0 / 0 / 2,000 0 / 0 / 2,000
.text of jsc 27,313,306 B 27,313,242 B
builtinBytecodeSize() of the two test sources 224, 240 B 224, 240 B

The functor differs from upstream by +5/-0 lines. Before this change it was identical to upstream main.

What else changes. slow_path_check_tdz, the other caller, gets the same index. A TDZ error raised in the frame the functor stops at now names the binding of the check (Cannot access 'later' before initialization., it said 'callback'). In a build with assertions a private builtin has expression info, and this reader has no private-builtin rule. A TDZ error in a $vm.createBuiltin() function says 'later' there now (it said 'callback'), and '' in a release build as before. No builtin that ships can fail such a check. An error that a host function or a wasm trap makes while a builtin-module frame is the nearest JS frame now quotes the call in that frame.

What stays wrong

  • TDZ names. slow_path_check_tdz takes the name from the expression info at the check. x++ before let x names an earlier expression, a class field initializer gives '', and the repro of misleading error message 'Cannot access x before initialization' bun#29514 gives ', exists2: '. User code has the same defect, and so does upstream. Error for accessing classes before initialization displays empty name bun#25569 was closed as fixed on 1.4.0 and its repro prints '' again on 1.4.3-canary.1.
  • A crash in the same reader. setTimeout(async (cfg = cfg) => { await null }, 0) ends in Segmentation fault at address 0x38 on Bun 1.4.2 and 1.4.3-canary.1, and in a jsc with or without this change. getBytecodeIndex() skips the async wrapper (private visibility) and returns no code block, and the reader does not check. With a JS caller the name is the caller's call expression.
  • A frame with private visibility. The functor skips it, so an error raised in an async wrapper's parameters or in a class field initializer (Show class field initializers in stack traces and place them on the enclosing source's first line #435) quotes text of the next frame.
  • f.@call(...) and f.@apply(...) in is not a function messages, for example listener.@call is not a function. (In 'listener.@call(this, args[0])', 'listener.@call' is 5) from node:events. That text comes from the Call IC (bytecode/RepatchInlines.h:57), which passes its own index. It is the kind of message appendSourceToErrorMessage: skip builtin code blocks #369 was opened for.
  • Intrinsic ops. Their emitters in bytecompiler/NodesCodegen.cpp give the op no expression info. @arrayPush(c.list, v) with c.list undefined quoted 'o' and now quotes 'v'.

Other open PRs near this code: #642 (wasm trap messages), #721 (setStackFrames). The code frame that Bun prints above these errors skips a line. That is Bun's printer (oven-sh/bun#38244).

An error that JSC raises in a builtin with a source URL (one of the embedder's
modules) quotes the wrong source text. Bun prints
"undefined is not an object (evaluating 'stream')" where the access that failed
is `stream._writableState`. The line and the column of the error are right.

FindFirstCallerFrameWithCodeblockFunctor, behind getBytecodeIndex(), takes the
code block of the frame it stops at, but leaves the bytecode index at 0 when
that code block is a builtin. Upstream never reads that pair: a builtin has no
expression info there. Here a builtin with a source URL has expression info in
every build (BytecodeGenerator::emitExpressionInfo), and
appendSourceToErrorMessage() quotes from it. ExpressionInfo maps an index
before the first entry to the first entry, so the text was that of the first
expression of the function. With debugger hooks in the bytecode it was the
head of the function, as "(near '...')".

The functor now takes the index from the frame that gives the code block, so
both callers get the index of the frame it stops at.
appendSourceToErrorMessage() reads the expression info and the text from that
one code block: its text is now that of the expression that failed, as for
user code. It still returns early for a private builtin.

slow_path_check_tdz gets the same index. A TDZ error raised in the frame the
functor stops at now names the binding of the check, where it named the first
expression of the function. Its other defects stay: it uses a null code block
when the functor finds no frame, it takes the text from its own code block
when the functor stops at another frame, and some checks have no expression
info of their own.
@robobun
robobun requested a review from dylan-conway October 8, 2026 18:34
@robobun

robobun commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Status: open, waits for review.

How I reproduced it (Bun 1.4.3-canary.1+367d939d9, Linux x64):

$ bun -e 'require("node:stream").Writable.prototype.write.call(undefined, "x")'
TypeError: undefined is not an object (evaluating 'stream')
      at _write (internal:streams/writable:217:21)

The code at that position is stream._writableState. A jsc built from the parent of this branch fails the new stress test in all 18 modes. A jsc built from this branch passes it.

@claude claude Bot left a comment

Copy link
Copy Markdown

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. Since it changes the text of every engine error raised inside a Bun builtin module (a user-visible message change that downstream tests may match on), a human look at that product decision would still be worthwhile.

What was reviewed:

  • The Error.cpp hunk against both consumers: ErrorInstance::finishCreation still returns early for private builtins via isPrivateBuiltinFunction() in appendSourceToErrorMessage(), and slow_path_check_tdz on a code block with no expression info decodes an empty entry exactly as it did at index 0.
  • Confirmed BytecodeGenerator::emitExpressionInfo in this fork emits info for non-private builtins in release, so the real index is meaningful; visitor->bytecodeIndex() already maps DFG/FTL frames via code origin, so no per-tier change is needed.
  • Checked that builtinFromBytecodeCache() (jsc.cpp) and $vm.createBuiltin() exist in this fork's shell; the new test is fork-only and does not alter an upstream test, so BUN-TEST-DIFFERENCES.md is not required by the stated rule, though an entry would help triage after the next sync.
Extended reasoning...

The change is a five-line C++ hunk in Source/JavaScriptCore/runtime/Error.cpp (FindFirstCallerFrameWithCodeblockFunctor) gated under USE(BUN_JSC_ADDITIONS) with upstream code preserved in #else, plus a new 93-line JSTests/stress test. It touches no security-sensitive surface; it only affects which source range an error message quotes. The logic is correct and consistent with the fork's existing design (expression info for builtins with a source URL, private-builtin exclusion in appendSourceToErrorMessage). Deferring rather than approving because the change alters a large number of user-visible Bun error messages (the author counts 160 of 339), which is a product-level decision, and because .github/CODEOWNERS lists Source/JavaScriptCore and JSTests under a reviewer group.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 7fc7f9d7-d90d-4127-85d6-2b5415efd3f2
📥 Commits

Reviewing files that changed from the base of the PR and between 7012d42 and b1aafd7.

📒 Files selected for processing (2)
  • JSTests/stress/builtin-with-source-url-error-quotes-failing-expression.js
  • Source/JavaScriptCore/runtime/Error.cpp

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


Walkthrough

Bun builds now record bytecode indices for builtin frames. A new stress test checks error messages for builtins created from source or bytecode cache, including repeated calls, private builtins, and several failing expressions.

Changes

Builtin error source quoting

Layer / File(s) Summary
Record builtin bytecode indices
Source/JavaScriptCore/runtime/Error.cpp
Bun builds now record the bytecode index for builtin frames. Other builds retain the existing behavior.
Exercise builtin error messages
JSTests/stress/builtin-with-source-url-error-quotes-failing-expression.js
The stress test checks errors across repeated calls and source or bytecode-cache creation. It also checks private builtins and compares failing expressions with equivalent user-code errors.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to b1aaf

No actionable issue is established that would prevent merging after normal checks.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: assigning a builtin frame its own bytecode index.
Description check ✅ Passed The description is detailed, relevant, and explains the problem, fix, testing, performance impact, and known limitations. It does not include the required Bugzilla URL, Reviewed by NOBODY line, or a t…
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.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown

Preview build of b1aafd7: autobuild-preview-pr-780-b1aafd71

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant