Repository navigation
jsc: delete javascript_core_c_api.rs and remove all JSC C API usage from Rust - #33731
Conversation
Every call site now uses bun_jsc equivalents: - JSObjectGetPropertyAtIndex/JSObjectSetPropertyAtIndex -> JSValue::get_index/put_index - JSObjectGetPrototype -> JSValue::get_prototype - JSObjectMakeDate -> JSValue::from_date_number - JSValueGetType -> is_undefined/is_null/... chain (server.fetch type error) - JSObjectGetProxyTarget -> new Bun__JSValue__getProxyTarget (handles both JSGlobalProxy and ProxyObject) - JSObjectGetTypedArrayBuffer/ByteOffset -> new Bun__JSValue__getArrayBufferViewBuffer/ByteOffset - JSObjectMakeTypedArrayWithArrayBuffer -> new Bun__createTypedArrayForCopy (single-allocation copy, fixes Float16 falling through to kJSTypedArrayTypeNone) - JSObjectCallAsFunctionReturnValueHoldingAPILock -> Bun__JSValue__callReturnValueHoldingAPILock (same body, EncodedJSValue args) The JSTypedArrayBytesDeallocator typedef moves to bun_jsc::array_buffer and is re-exported at the crate root. MacroMap now stores JSValue instead of JSObjectRef. CallbackTask and ArgumentsSlice::from are deleted (both unused). The JSValue::c/as_ref/ as_object_ref bridging methods are deleted.
|
Warning Review limit reached
Next review available in: 27 minutes 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: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (22)
Comment |
|
Updated 5:09 AM PT - Jul 8th, 2026
❌ @robobun, your commit ec9f091 has 5 failures in
🧪 To try this PR locally: bunx bun-pr 33731That installs a local version of the PR into your bun-33731 --bun |
Adds coverage for every string-selectable typed-array binaryType and documents the float16array segfault that the C-API removal fixes (TypedArrayType::TypeFloat16 used to map to kJSTypedArrayTypeNone, so JSObjectMakeTypedArrayWithArrayBuffer returned null and the data handler dereferenced it).
Jarred-Sumner
left a comment
There was a problem hiding this comment.
Check for existing functions for each of these bindings.
Drops the dedicated Bun__JSValue__callReturnValueHoldingAPILock binding; the macro caller composes VirtualMachine::run_with_api_lock + JSValue::call + JSGlobalObject::try_take_exception, all of which already exist.
|
Checked each new binding against
|
There was a problem hiding this comment.
No bugs found, but this replaces an entire FFI surface with four new C++ bindings and reworks call semantics across macros, N-API, ReadableStream, and the console formatter — worth a human pass on the exception-scope and GC-safety details in the new Bun__* externs.
Extended reasoning...
Overview
This PR deletes src/jsc/javascript_core_c_api.rs (~225 lines, the deprecated bun_jsc::c_api module) and migrates every remaining call site to either existing JSValue methods or four new C++ bindings added to bindings.cpp / ZigGlobalObject.cpp (Bun__JSValue__getProxyTarget, Bun__JSValue__getArrayBufferViewBuffer, Bun__JSValue__getArrayBufferViewByteOffset, Bun__createTypedArrayForCopy). Twenty-two files are touched across the JSC binding layer, macro execution, N-API, ReadableStream, the console/pretty-format formatters, Bun.serve fetch, and FFI. Along the way it fixes a real segfault (binaryType: "float16array" on UDP/TCP/h2 data callbacks) and adds a subprocess-based test covering every typed-array binaryType.
Security risks
No auth/crypto/permission surfaces are involved. The risk profile here is memory safety and exception-scope correctness in the new C++ externs — e.g. Bun__createTypedArrayForCopy opens a DECLARE_THROW_SCOPE, calls ArrayBuffer::tryCreateUninitialized, memcpys, then dispatches through FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW with RELEASE_AND_RETURN; Bun__JSValue__getArrayBufferViewBuffer calls possiblySharedBuffer() and m_typedArrayController->toJS(...) without a throw scope. These look correct at a glance but are exactly the kind of thing CLAUDE.md flags as the most-blocked review category.
Level of scrutiny
High. This is an architectural cleanup of a core FFI boundary that:
- Adds hand-written C++ bindings that must satisfy JSC's exception-check and GC-rooting invariants.
- Changes macro-invocation semantics:
JSObjectCallAsFunctionReturnValueHoldingAPILock(which built aMarkedArgumentBufferand defaultedthistoglobalThis()) is replaced byvm.run_with_api_lock(|| callback.call(global, JSValue::ZERO, args))— a subtle behavioral change (thisis nowZERO, args no longer routed throughMarkedArgumentBuffer). - Changes error propagation:
pretty_formatandReadableStreamnow useget_index/put_indexwhich returnJsResultand?-propagate, whereas the old C-API calls swallowed exceptions via a nullExceptionRef. - Touches N-API entry points (
napi_get_prototype,napi_get_typedarray_info,napi_get_dataview_info,napi_create_date).
Other factors
The PR description shows relevant test suites were run and rust:check-all passes on all 10 targets. The bug-hunting system found no issues, and the author already iterated once (deleting Bun__JSValue__callReturnValueHoldingAPILock in favor of composing existing helpers per the robobun follow-up). Still, the combination of new C++ FFI, changed this-binding in macro calls, and altered exception propagation across multiple subsystems puts this well outside the "simple/mechanical" bar for auto-approval.
|
A couple of corrections to the extended reasoning above:
Correct observation; it is intentional. The old path passed |
|
CI is green on everything this diff touches (udp_socket, macro, inspect, napi, serve.fetch all pass on every lane). The single hard failure is |
… like Node (#39418) ### Problem - `napi_get_prototype` on a Proxy runs the Proxy's `getPrototypeOf` trap. Node does not: V8's `Object::GetPrototype`, which Node's `napi_get_prototype` wraps, cannot run JS and returns `null` for any Proxy (verified with Node 26.3, output in the details below). - Running the trap also makes the failure mode wrong: when the trap throws (or returns a non-object, or the proxy is revoked) the call returns `napi_ok`, writes a NULL `napi_value` into `*result`, and leaves the exception pending without telling the addon. Current canary on the new fixture: `trap throws: status=0 pending=true result=null handle exception=the trap's error`. - This is an unreleased regression from #33731 (86caf6e): `napi_get_prototype` used to call the JSC C API's `JSObjectGetPrototype`, which is `getPrototypeDirect()`, and JSC creates Proxy structures with a null prototype, so 1.3.14 already returned `null` for a Proxy without running anything. #33731 replaced it with `JSValue::get_prototype`, JSC's full `[[GetPrototypeOf]]` (traps included), which returned a bare `JSValue` that is empty (encoded 0, i.e. a NULL handle) when it threw, so the call site in `src/runtime/napi/napi_body.rs` could not tell success from failure. Affects 1.4.0 canary only; the `napi_get_prototype` line in the #36801 audit ("already avoids the trap") describes the pre-#33731 state. - The other `getPrototype` exception-handling sites found by the same reading (the inspect property walk, `napi_get_all_property_names`, `util.isError`) are separate fixes in #29642, #32263 and #37202; this PR merges cleanly in either order with them. ### Fix - `napi_get_prototype` returns `null` for a `ProxyObject` without touching its handler, the same result Node produces and the same result 1.3.14 produced. Every other object type's `[[GetPrototypeOf]]` in JSC is a plain read (`JSGlobalProxy` forwards to the global object, `ImportMetaObject` returns null, primitives get their wrapper prototype), so the function no longer runs JS for any input, like Node's. - `JSValue::get_prototype` (`src/jsc/JSValue.rs`) now returns `JsResult<JSValue>` through `host_fn::from_js_host_call`, the wrapper `JSValue::call` and `unwrap_boxed_primitive` already use for JSC calls that return empty exactly when they threw. This is what let the empty value reach `*result`, and the remaining callers (`ConsoleObject.rs`, `pretty_format.rs`, `ScopeFunctions.rs`, all already returning `JsResult`) now propagate with `?` instead of holding a possibly-empty value. They only ever see ordinary objects (the formatters print a Proxy's target), so their output is unchanged. In `napi_get_prototype` the `Err` arm maps to `napi_pending_exception` as the generic Node-API protocol; with the Proxy case handled above it is not reachable with today's object types. - Test: `test/napi/napi.test.ts` (`napi_get_prototype`) runs fixture `test_napi_get_prototype_proxy` (`napi-app/module.js`) through `checkSameOutput`, so the output is compared byte for byte with Node, and then pins the lines. The helper `perform_get_prototype` (`napi-app/js_test_helpers.cpp`) pre-fills `*result` with a sentinel so the output distinguishes a real `null` from "not written" and from a NULL handle. Cases: proxy without traps, callable proxy, a trap that counts its calls (must stay 0), a trap that throws, a trap returning a number, a revoked proxy, plus plain / null-prototype objects and an object whose prototype is a proxy (returned as-is, only the object itself is special-cased). - Fails under `USE_SYSTEM_BUN=1` (1.4.0-canary.1: 7 of 11 lines differ from Node, see details), passes with `bun bd test test/napi/napi.test.ts`. - Also run on the debug build: the rest of `test/napi/napi.test.ts`, Node's own `test_general` suite (`test/napi/node-napi-tests/.../test_general/do.test.ts`, which asserts `napi_get_prototype` matches `Object.getPrototypeOf` for ordinary objects), `test/js/bun/util/inspect.test.js`, `test/js/bun/test/printing/diffexample.test.ts`, `jest-each.test.ts`, `describe.test.ts`, `pretty-format-overflow.test.ts`, `console-table.test.ts`; plus a script formatting classes, functions, null-prototype objects and proxies, and a `bun test` file exercising `describe.each` / `test.each` / `skipIf` and class-instance `toEqual` diffs, both clean under `BUN_JSC_validateExceptionChecks=1`. - Noted while reviewing the other Proxy-receiver paths, not changed here (different function and file): `napi_remove_wrap` on a Proxy or on `globalThis` reports success but leaves the wrap attached, because `src/jsc/bindings/napi.cpp` removes it with the virtual `deleteProperty` (which `ProxyObject` refuses for private names and `JSGlobalProxy` forwards to its target) while `napi_wrap` / `napi_unwrap` use `putDirect` / `getDirect`; Node removes it. Probe output is in the second details block. ### Background - `[[GetPrototypeOf]]` is the spec operation behind `Object.getPrototypeOf`. For ordinary objects it reads a field and cannot fail; a Proxy implements it by calling its handler's `getPrototypeOf` trap, so it can run arbitrary JS and throw. V8's `Object::GetPrototype` returns a plain `Local<Value>` rather than a `MaybeLocal`, so it cannot run a trap, and it reports `null` for a Proxy; that is the behavior Node-API addons are written against. - `getPrototypeDirect()` is JSC's raw read of the prototype stored in an object's Structure, bypassing any override; `getPrototype()` is the full operation that dispatches to `ProxyObject`'s trap. The JSC C API's `JSObjectGetPrototype` is the former. - JSC signals a throw from a value-returning operation by returning the empty `JSValue` (encoding 0) and leaving the exception on the VM. `host_fn::from_js_host_call` maps that to `Err(JsError::Thrown)` and, in debug builds, asserts the value is empty if and only if an exception is pending. - A `napi_value` is an encoded `JSValue`, so storing the empty value hands the addon a NULL handle. - `napi_pending_exception` is the status a Node-API call returns when JS it ran threw; the exception stays pending for `napi_get_and_clear_last_exception` and out-params are left unwritten. <details> <summary>Fixture output: Node 26.3 (and this branch, identical) vs current canary</summary> Node v26.3.0, and this branch: ``` plain object: status=0 pending=false result=Object.prototype exception=none null prototype: status=0 pending=false result=null exception=none proxy without traps: status=0 pending=false result=null exception=none callable proxy: status=0 pending=false result=null exception=none trap returns Array.prototype: status=0 pending=false result=null exception=none getPrototypeOf trap calls: 0 trap throws: status=0 pending=false result=null exception=none trap returns a number: status=0 pending=false result=null exception=none revoked proxy: status=0 pending=false result=null exception=none object whose prototype is a proxy: status=0 pending=false result=the proxy exception=none plain object again: status=0 pending=false result=Object.prototype exception=none ``` Bun 1.4.0-canary.1 (`USE_SYSTEM_BUN=1`): ``` plain object: status=0 pending=false result=Object.prototype exception=none null prototype: status=0 pending=false result=null exception=none proxy without traps: status=0 pending=false result=Array.prototype exception=none callable proxy: status=0 pending=false result=Function.prototype exception=none trap returns Array.prototype: status=0 pending=false result=Array.prototype exception=none getPrototypeOf trap calls: 1 trap throws: status=0 pending=true result=null handle exception=the trap's error trap returns a number: status=0 pending=true result=null handle exception=TypeError revoked proxy: status=0 pending=true result=null handle exception=TypeError object whose prototype is a proxy: status=0 pending=false result=the proxy exception=none plain object again: status=0 pending=false result=Object.prototype exception=none ``` </details> <details> <summary>napi_remove_wrap follow-up: probe output (existing try_wrap / try_remove_wrap / try_unwrap helpers from napi-app, wrapping the number 6, then trying to re-wrap with 7)</summary> Node v26.3.0: ``` plain: wrap=true remove=6 unwrap_after=undefined rewrap=true proxy: wrap=true remove=6 unwrap_after=undefined rewrap=true callable proxy: wrap=true remove=6 unwrap_after=undefined rewrap=true globalThis: wrap=true remove=6 unwrap_after=undefined rewrap=true ``` Bun (this branch, unchanged in this respect): ``` plain: wrap=true remove=6 unwrap_after=undefined rewrap=true proxy: wrap=true remove=6 unwrap_after=6 rewrap=false callable proxy: wrap=true remove=6 unwrap_after=6 rewrap=false globalThis: wrap=true remove=6 unwrap_after=6 rewrap=false ``` </details> <details> <summary>Earlier version of this PR</summary> The first revision kept running the trap and changed only the failure report: `napi_pending_exception` with `*result` untouched when the trap threw, tested on Bun alone since Node never reaches that path. Review asked to match Node instead and not run JS, which is the current shape; the `JsResult` change to `JSValue::get_prototype` is unchanged from that revision. </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
Deletes
src/jsc/javascript_core_c_api.rs(thebun_jsc::c_api/bun_jsc::C/bun_jsc::cmodule) and routes every former call site through existingbun_jsc::JSValuemethods or small new bindings inbindings.cpp.Call-site migrations
JSObjectGetPropertyAtIndexJSValue::get_indexJSObjectSetPropertyAtIndexJSValue::put_indexJSObjectGetPrototypeJSValue::get_prototypeJSObjectMakeDateJSValue::from_date_numberJSValueGetTypefetch_type_error_string(JSValue)(directis_*checks)JSObjectGetProxyTargetJSValue::get_proxy_target(Bun__JSValue__getProxyTarget, handlesJSGlobalProxyandProxyObject)JSObjectGetTypedArrayBuffer/ByteOffsetJSValue::get_array_buffer_view_buffer/_byte_offset(Bun__JSValue__getArrayBufferView*)JSObjectMakeTypedArrayWithArrayBufferBun__createTypedArrayForCopy(single allocation)JSObjectCallAsFunctionReturnValueHoldingAPILockvm.run_with_api_lock(|| callback.call(..).unwrap_or_else(|_| global.try_take_exception()..))(no new binding; C++ impl deleted)JSTypedArrayBytesDeallocatorbun_jsc::array_buffer, re-exported asbun_jsc::JSTypedArrayBytesDeallocatorBugfix:
binaryType: "float16array"no longer segfaultsBinaryType::to_jsused to go throughTypedArrayType::to_c(), which mappedTypeFloat16tokJSTypedArrayTypeNone(the C API enum predates Float16).JSObjectMakeTypedArrayWithArrayBufferthen returned null and the UDP / TCP / h2 data callback crashed dereferencing it:Bun__createTypedArrayForCopytakes the internalTypedArrayTypedirectly, so Float16 works. A test intest/js/bun/udp/udp_socket.test.tscovers every string-selectable typed-arraybinaryType.Deleted (no remaining callers)
JSValue::c/JSValue::as_ref/JSValue::as_object_ref(C-API bridging)ArgumentsSlice::from(&[JSValueRef])(unused)CallbackTask/CallbackTaskOptioninnode::types(unused)TypedArrayType::to_c()and theJSTypedArrayTypeenumFETCH_TYPE_ERROR_NAMES/FETCH_TYPE_ERROR_STRING_VALUES(replaced byfetch_type_error_string)JSObjectCallAsFunctionReturnValueHoldingAPILock(composed from existingholdAPILock+call+tryTakeException)MacroMapnow storesJSValueinstead ofJSObjectRefEvery symbol that was declared in
javascript_core_c_api.rsbut never referenced (JSGarbageCollect,JSValueMakeNull,JSValueToNumber,JSValueToObject,JSObjectCallAsFunction,JSObjectIsConstructor,JSObjectCallAsConstructor,JSObjectMakeTypedArray*,JSObjectGetTypedArray{BytesPtr,Length,ByteLength},JSObjectGetArrayBuffer*,JSRemoteInspector*,JSPropertyAttributes,JSClassAttributes,JSType,Private,Generic) is gone.Verification