Repository navigation
fix(node:module): don't register native helpers as their own constructors - #31393
Conversation
…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.
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
Comment |
There was a problem hiding this comment.
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'sputNativeFn,NodeBufferModule.h, andNodeTTYModule.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()andReflect.construct(fn, …)for every fixed function.
| JSFunction* resolveFilenameFunction = JSFunction::create( | ||
| init.vm, init.owner, 2, "_compile"_s, | ||
| functionJSCommonJSModule_compile, JSC::ImplementationVisibility::Public, | ||
| JSC::NoIntrinsic, functionJSCommonJSModule_compile); | ||
| JSC::NoIntrinsic); |
There was a problem hiding this comment.
🟣 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— theputNativeFnhelper lambda callsJSFunction::create(vm, globalObject, 1, name.string(), ptr, ImplementationVisibility::Public, NoIntrinsic, ptr). The sameptris used for both call and construct, so every export registered viaputNativeFnis constructible with its own call body.src/jsc/modules/NodeBufferModule.h:210,214,216—resolveObjectURL,isAscii, andisUtf8each pass their host function as the construct callback.src/jsc/modules/NodeTTYModule.h:20-23—notimpl(jsFunctionNotImplementedYet) is registered the same way;isattyon line 25 is registered viaputNativeFnand 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
const { isAscii } = require('node:buffer');isAsciiwas created atNodeBufferModule.h:214withjsBufferConstructorFunction_isAsciias both call and construct callback.new isAscii(Buffer.alloc(1))enters JSC'sconstructpath → callsjsBufferConstructorFunction_isAscii, which validates the argument and returnsJSValue::encode(jsBoolean(true)).- JSC's construct epilogue does
asObject(decode(result))→asCell()→ASSERT(isCell())fails on a boolean, exactly the assertion fingerprint this PR fixes formodule._compile. - Same for
require('node:tty').isatty(registered viaputNativeFn) and any otherputNativeFnexport 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.
|
CI status for fde4cea (build #57947): all 72 platform build/test job statuses are green on this commit — including |
* 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
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.
What does this PR do?
Fixes a fuzzer-found crash (
ASSERTION FAILED: isCell()inJSCJSValue.h,asCell()) triggered by constructingprocess.mainModule._compile:Module.runMain,Module._resolveFilename,module._compile(insrc/jsc/modules/NodeModuleModule.cpp) andperformance.now(insrc/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 returnundefined, a string, or a number — sonew fn()/Reflect.construct(fn, …)hitasObject()→ASSERT(isCell())in debug builds and produce an invalidJSObject*in release builds.Fix
Create these functions without a native constructor (the
JSFunction::createdefault,callHostFunctionAsConstructor), so constructing them throws aTypeErrorlike other native helper functions — matchingperformance.nowbehavior in browsers/Node, while calling them is unchanged.Related: #31386 fixes the same assertion fingerprint for
bun:testmock 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 throwTypeErrorwith 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.