Skip to content

fix(node:module): don't register native helpers as their own constructors - #31393

Merged
Jarred-Sumner merged 1 commit into
mainfrom
farm/4e0236f3/module-compile-not-a-constructor
May 25, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
farm/4e0236f3/module-compile-not-a-constructor

Conversation

@robobun

@robobun robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a fuzzer-found crash (ASSERTION FAILED: isCell() in JSCJSValue.h, asCell()) triggered by constructing process.mainModule._compile:

Reflect.construct(process.mainModule._compile, []); // ASSERTION FAILED: isCell()

Module.runMain, Module._resolveFilename, module._compile (in src/jsc/modules/NodeModuleModule.cpp) and performance.now (in src/jsc/bindings/webcore/JSPerformance.cpp) were created with their call function also registered as the native construct callback. JSC requires a native construct callback to return an object, but these functions return undefined, a string, or a number — so new fn() / Reflect.construct(fn, …) hit asObject() → ASSERT(isCell()) in debug builds and produce an invalid JSObject* in release builds.

Fix

Create these functions without a native constructor (the JSFunction::create default, callHostFunctionAsConstructor), so constructing them throws a TypeError like other native helper functions — matching performance.now behavior in browsers/Node, while calling them is unchanged.

Related: #31386 fixes the same assertion fingerprint for bun:test mock functions; this PR covers the remaining non-mock instances the fuzzer reached.

How did you verify your code works?

  • The minimized repros (Reflect.construct(module._compile, []), new process.mainModule._compile(), Reflect.construct(Module._resolveFilename, ["fs"]), new Module.runMain(), Reflect.construct(performance.now, [])) assert on current main (debug build) and now throw TypeError with this change.

  • Added regression tests:

    • node-module-module > native module functions are not constructors (test/js/node/module/node-module-module.test.js)
    • performance.now is not a constructor (test/js/web/timers/performance.test.js)

    Both fail on an unfixed build and pass with this change; the full files (29 and 7 tests) pass with the debug build, including the existing tests that call module._compile / Module._resolveFilename.

…tors

Module.runMain, Module._resolveFilename, module._compile, and performance.now
were created with their call function doubling as the native construct
callback. Constructing them (new / Reflect.construct) therefore returned a
non-object, which trips the isCell() assertion in JSC's construct machinery in
debug builds and produces an invalid object pointer in release builds.

Register them without a native constructor so constructing throws a TypeError
like other native helper functions, and add regression tests.
@coderabbitai

coderabbitai Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, we couldn't start this review because you've used your available PR reviews for now.

Your plan includes 5 reviews of capacity. Refill in 28 minutes and 26 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more review capacity refills, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ebcfaeba-6838-4fd9-8d15-6acf3099c730

📥 Commits

Reviewing files that changed from the base of the PR and between a49b308 and fde4cea.

📒 Files selected for processing (4)
  • src/jsc/bindings/webcore/JSPerformance.cpp
  • src/jsc/modules/NodeModuleModule.cpp
  • test/js/node/module/node-module-module.test.js
  • test/js/web/timers/performance.test.js

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

@robobun

robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 8:29 AM PT - May 25th, 2026

@robobun, your commit fde4cea is building: #57947

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

LGTM — straightforward fix dropping the self-as-constructor argument so these helpers throw TypeError instead of crashing; the inline note about other modules is pre-existing and fine for a follow-up.

Extended reasoning...

Overview

This PR removes the trailing native-constructor argument from four JSFunction::create calls (Module.runMain, Module._resolveFilename, module._compile in NodeModuleModule.cpp, and performance.now in JSPerformance.cpp) so they fall back to JSC's default callHostFunctionAsConstructor, which throws TypeError on new/Reflect.construct. Previously the call function was passed as its own construct callback, and since these return primitives, JSC's asObject() → asCell() path asserted in debug and produced an invalid JSObject* in release. Two regression tests are added verifying both that construction now throws and that normal calls still work.

Security risks

None. The change strictly tightens behavior — it converts a crash/UB path into a clean TypeError, matching Node.js and browser semantics. No new surface area, no auth/crypto/permissions code touched.

Level of scrutiny

Low. This is a one-token mechanical edit at each of four call sites, following the established JSC pattern already used elsewhere in the same file (e.g. the onMutate JSFunction in NodeModuleModule.cpp and the lut-table host functions). For performance.now the constructor slot is explicitly set to callHostFunctionAsConstructor (rather than omitted) because the trailing DOMJIT signature is positional — the JIT fast path is preserved. The call path is untouched, and the added tests assert that Module._resolveFilename("fs") and performance.now() still return their expected values.

Other factors

  • No CODEOWNERS cover the modified paths.
  • The single inline finding is explicitly flagged as pre-existing — the same self-as-constructor pattern in _NativeModule.h's putNativeFn, NodeBufferModule.h, and NodeTTYModule.h. It's a useful follow-up pointer but not introduced by this PR and the comment itself says it's fine to land as-is.
  • No prior reviewer comments to address; CI build was triggered.
  • Regression tests cover both new fn() and Reflect.construct(fn, …) for every fixed function.

Comment on lines 1091 to +1094
JSFunction* resolveFilenameFunction = JSFunction::create(
init.vm, init.owner, 2, "_compile"_s,
functionJSCommonJSModule_compile, JSC::ImplementationVisibility::Public,
JSC::NoIntrinsic, functionJSCommonJSModule_compile);
JSC::NoIntrinsic);

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.

🟣 Pre-existing (not introduced by this PR), but the same self-as-constructor pattern still exists in other native modules: the putNativeFn helper in src/jsc/modules/_NativeModule.h:95-97, resolveObjectURL/isAscii/isUtf8 in src/jsc/modules/NodeBufferModule.h:210,214,216, and notimpl in src/jsc/modules/NodeTTYModule.h:20-23. So e.g. new (require('node:buffer').isAscii)(Buffer.alloc(1)) still hits the same asCell() assertion. Since the description says this PR covers 'the remaining non-mock instances', it might be worth dropping the trailing constructor argument at those sites too (same one-token fix), or doing it in a follow-up.

Extended reasoning...

What the bug is

This PR correctly fixes runMain, _resolveFilename, _compile, and performance.now by removing the trailing NativeConstructor argument from JSFunction::create(...), so that constructing them throws TypeError instead of letting a primitive return value flow through JSC's asObject() path. However, the identical pattern — passing the host call function as the construct callback — still exists at three other places in src/jsc/modules/ that this PR doesn't touch:

  • src/jsc/modules/_NativeModule.h:95-97 — the putNativeFn helper lambda calls JSFunction::create(vm, globalObject, 1, name.string(), ptr, ImplementationVisibility::Public, NoIntrinsic, ptr). The same ptr is used for both call and construct, so every export registered via putNativeFn is constructible with its own call body.
  • src/jsc/modules/NodeBufferModule.h:210,214,216 — resolveObjectURL, isAscii, and isUtf8 each pass their host function as the construct callback.
  • src/jsc/modules/NodeTTYModule.h:20-23 — notimpl (jsFunctionNotImplementedYet) is registered the same way; isatty on line 25 is registered via putNativeFn and returns a boolean.

Code path that triggers it

JSC requires a native construct callback to return an object. When a host function that returns a primitive is registered as its own construct callback, new fn(...) / Reflect.construct(fn, [...]) takes the construct-call path inside JSC, which ends in asObject(returnValue) → ASSERT(isCell()) (JSCJSValue.h). isAscii and isUtf8 return jsBoolean(...); resolveObjectURL returns jsUndefined() / a string; tty.isatty (via putNativeFn) returns a boolean. None of these are cells.

Why nothing prevents it

These functions are exported on built-in module namespaces, so they're directly reachable from user JS — there's no wrapper that strips constructibility. Because the construct callback is the call callback, JSC treats the function as constructible (it doesn't fall back to callHostFunctionAsConstructor), and there's no return ensureObject(...) shim around the return value.

Step-by-step proof

  1. const { isAscii } = require('node:buffer');
  2. isAscii was created at NodeBufferModule.h:214 with jsBufferConstructorFunction_isAscii as both call and construct callback.
  3. new isAscii(Buffer.alloc(1)) enters JSC's construct path → calls jsBufferConstructorFunction_isAscii, which validates the argument and returns JSValue::encode(jsBoolean(true)).
  4. JSC's construct epilogue does asObject(decode(result)) → asCell() → ASSERT(isCell()) fails on a boolean, exactly the assertion fingerprint this PR fixes for module._compile.
  5. Same for require('node:tty').isatty (registered via putNativeFn) and any other putNativeFn export that returns a primitive.

The notimpl case in NodeTTYModule.h is weaker — jsFunctionNotImplementedYet throws, so the asObject path may not be reached — but putNativeFn and the buffer helpers definitely hit it.

Impact

Same as the cases fixed in this PR: ASSERTION FAILED: isCell() in debug builds, and an invalid JSObject* (UB / heap corruption potential) in release builds, all reachable from one line of user JS. It's the same fuzzer bug class.

Fix

Mechanically identical to what this PR already does: drop the trailing constructor argument so JSFunction::create defaults to callHostFunctionAsConstructor, which throws TypeError. For putNativeFn that's deleting the final , ptr; for the three explicit sites in NodeBufferModule.h and the one in NodeTTYModule.h it's deleting the duplicated function name. This is pre-existing (none of these files are in the diff) — flagging it because the PR description says it covers 'the remaining non-mock instances the fuzzer reached', and these are additional reachable instances of the same class. Fine to land this PR as-is and address these in a follow-up.

@robobun

robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator Author

CI status for fde4cea (build #57947): all 72 platform build/test job statuses are green on this commit — including test/js/node/module/node-module-module.test.js and test/js/web/timers/performance.test.js which contain the new regression tests. The red Buildkite roll-up comes from a flaky job attempt that was retried to green (same pattern as #31386's build); no failure is related to this change. Not pushing a retrigger since every reporting job already passed — a Buildkite-side rebuild can green the roll-up if desired.

@Jarred-Sumner
Jarred-Sumner merged commit e262c99 into main May 25, 2026
78 of 79 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/4e0236f3/module-compile-not-a-constructor branch May 25, 2026 23:53
springmin pushed a commit to springmin/bun that referenced this pull request May 26, 2026
* oven/main (10 new commits):
  Optimize TextEncoder.encode: restore SIMD ASCII fast paths lost in the Rust port (oven-sh#31385)
  js_parser: sanitize auto-generated default export name for digit-named modules (oven-sh#31403)
  fetch: run checkServerIdentity before writing the request (oven-sh#31325)
  ffi: avoid copying the threadsafe callback wrapper on the calling thread (oven-sh#31332)
  install: gate the exit-callback cache teardown to the main thread (oven-sh#31376)
  fix(node:module): don't register native helpers as their own constructors (oven-sh#31393)
  css: escape custom pseudo-class/element names when printing (oven-sh#31404)
  Deepen the lots-of-for-loop fixture so the transpiler stack-overflow tests throw on Windows (oven-sh#31382)
  Hardening: input validation and bounds tightening across 36 subsystems (round 4) (oven-sh#31339)
  Speed up FormData multipart serialization (oven-sh#31379)

Auto-merged: src/install/PackageManager.rs, src/runtime/cli/upgrade_command.rs, src/runtime/webcore/Blob.rs, src/sys/lib.rs
robobun added a commit that referenced this pull request Sep 26, 2026
Five registration sites passed a plain call function as the native
[[Construct]] handler too. A construct then ran the call function and
read its boolean, number or string result as an object. Array.of,
Array.from, every Symbol.species path and Reflect.construct construct
their callee, so this one line killed a release build:

    Array.of.call(require("util").types.isDate, 1, 2, 3);

The sites now pass no constructor, so JSC's default throws a TypeError:

- putNativeFn in _NativeModule.h (node:util/types, bun:jsc)
- node:buffer isUtf8, isAscii, transcode and resolveObjectURL
- utf-8-validate
- node:sqlite backup
- Zig::JSFFIFunction::create, which now uses its nativeConstructor
  parameter (the native node:os functions), and createForFFI (bun:ffi)

The same remedy as #31393.
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