Skip to content

napi: align symbol/buffer/coercion/reference/tsfn semantics with Node.js - #36801

Closed
robobun wants to merge 7 commits into
mainfrom
farm/d4378f5e/napi-node26-semantic-fixes
Closed

robobun wants to merge 7 commits into
mainfrom
farm/d4378f5e/napi-node26-semantic-fixes

Conversation

@robobun

@robobun robobun commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Superseded. Kept open as a draft, at a maintainer's request, as the reference for the full audit. It will not be rebased; the content landed via the split PRs below and the remaining diff is tracked in #36850.

Dropped after review: the TSFN kMaxIterationCount cap (no issue motivating it).


What

A set of N-API functions whose observable behaviour (not just return status) differed from Node.js. Each was verified by running the same native addon under both node v26 and bun; the new tests use checkSameOutput so Bun's stdout is compared byte-for-byte with Node's.

Function Before (Bun) Node.js / after
napi_set_named_property(env, obj, "", v) napi_invalid_arg napi_ok (sets obj[""])
napi_create_symbol(env, <js undefined/null>, &r) napi_ok, Symbol() napi_string_expected
napi_create_symbol(env, <js "">, &r) .description === undefined .description === ""
node_api_create_external_string_latin1(env, NULL, 0, ...) napi_invalid_arg napi_ok (empty string)
node_api_create_external_string_{latin1,utf16}(env, p, INT_MAX+1, ...) crash (truncated static_cast<unsigned> span) napi_invalid_arg
napi_get_buffer_info(env, <ArrayBuffer>, ...) napi_ok napi_invalid_arg (HasInstance = IsArrayBufferView)
napi_define_properties / napi_object_freeze / napi_object_seal / node_api_set_prototype on a number napi_object_expected, no exception napi_ok (ToObject-coerced)
... on null / undefined napi_object_expected, no exception napi_object_expected, pending TypeError
napi_type_tag_object / napi_check_object_type_tag on a number napi_object_expected, no exception napi_ok
... on null napi_object_expected, no exception napi_pending_exception
napi_new_instance / napi_get_named_property / napi_has_named_property when the underlying JS throws writes *result, then napi_pending_exception napi_pending_exception, *result untouched
node_api_get_module_file_name on the napi_module_register path writes NULL writes ""
napi_reference_ref after the weak referent is collected increments (returns 1, 2, ...) returns 0, does not increment
TSFN call_js_cb when created with func == NULL js_callback is encoded undefined (non-null) js_callback == NULL
TSFN dispatch loop unbounded 1000-iteration cap then re-schedule (kMaxIterationCount)

Why

These are the cases where a correct N-API addon observes a different answer under Bun than under Node.js, for the same sequence of calls. The external-string length overflow is a crash in practice (the truncated unsigned is used as a span length over the caller's buffer). The js_callback != NULL check is how napi-rs and similar decide whether to invoke the JS function inside call_js_cb; the encoded undefined value is a non-zero pointer, so addons were calling napi_call_function on it and panicking with "expect Function, got: Undefined".

Fixes #13771
Closes #30543 (subsumed; same TSFN js_callback fix)

Two items from the originating audit were dropped after empirical verification: napi_set_property / _element do not need a put-return check (V8's Object::Set never returns Just(false), so Node's napi_generic_failure branch is unreachable and Bun already matches), and napi_get_prototype already avoids the Proxy getPrototypeOf trap in Bun.

The napi_get_typedarray_info / napi_get_dataview_info type gate and the napi_add_finalizer teardown guarantee are already covered by #34132 and #32912 respectively.

Verification

New checkSameOutput tests in test/napi/napi.test.ts (-t "semantic parity with Node") compare Bun against Node.js and fail under the released Bun:

$ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "semantic parity"
(fail) ... matches Node for symbol description, ToObject coercion, ...
(fail) ... napi_reference_ref returns 0 after the referent is collected
(fail) ... threadsafe function call_js receives NULL js_callback ...

$ bun bd test test/napi/napi.test.ts -t "semantic parity"
(pass) ... (all three)

The vendored Node.js js-native-api/test_symbol, test_object, test_properties, test_reference, and node-api/test_threadsafe_function suites continue to pass.


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

@github-actions github-actions Bot added the claude label Aug 3, 2026
@robobun

robobun commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:23 AM PT - Aug 3rd, 2026

❌ @robobun, your commit 2cd35e8 has 1 failures in Build #88054 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 36801

That installs a local version of the PR into your bun-36801 executable, so you can run:

bun-36801 --bun

Comment thread src/jsc/bindings/NapiRef.cpp Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Found 4 issues this PR may fix:

  1. napi panic crash #17285 - TSFN panic with "get_named_property error" matches the napi_get_named_property exception-pending guard and TSFN dispatch fixes
  2. not save to data - NAPI Failed to convert return value in ThreadsafeFunction callback into Rust value #22759 - TSFN callback crash at threadsafe_function.rs:749 matches the NULL js_callback handling and dispatch loop cap fixes
  3. Panic with vite+lightningcss when using visitors #13771 - TSFN panic "expect Function, got: Undefined" matches the fix to pass NULL for js_callback when created with func==NULL
  4. Prisma crashing when logging is enabled #15291 - Prisma TSFN "FunctionExpected" crash matches the NULL js_callback handling fix

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #17285
Fixes #22759
Fixes #13771
Fixes #15291

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The N-API bindings now propagate VM exceptions and apply updated coercion, string, symbol, buffer, and module filename behavior. Reference and thread-safe-function handling now covers collected values, null callbacks, and bounded dispatch. Tests cover Node.js semantic parity and these runtime cases.

Changes

N-API behavior alignment

Layer / File(s) Summary
Exception-aware N-API bindings
src/jsc/bindings/napi.cpp
Property access, object conversion, external strings, symbols, constructors, type tags, prototypes, and module filename retrieval now follow updated N-API behavior.
Reference and callback runtime behavior
src/jsc/bindings/NapiRef.cpp, src/runtime/napi/napi_body.rs
Collected references keep a zero count. Buffer info rejects bare ArrayBuffer values. Thread-safe-function dispatch limits each tick to 1,000 callbacks and passes null callbacks to native code.
Node.js semantic parity coverage
test/napi/napi-app/standalone_tests.cpp, test/napi/napi.test.ts
Tests cover status codes, exceptions, coercion, empty values, strings, buffers, type tags, prototypes, result writes, and module filenames.
Reference and null-callback validation
test/napi/napi-app/module.js, test/napi/napi-app/standalone_tests.cpp, test/napi/napi.test.ts
Drivers and tests cover collected-reference operations, null JavaScript callbacks, and thread-safe functions that drain more than 1,000 queued items.

Suggested reviewers: jarred-sumner, cirospaciari

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes symbol, buffer, coercion, reference, exception, and module-filename changes that are unrelated to the linked TSFN issues. Separate unrelated N-API semantic changes into dedicated pull requests or link issues that explicitly cover those changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR fixes the linked TSFN null-callback panic, passes NULL to call_js_cb, and adds regression tests for Node.js compatibility [#13771, #30543].
Title check ✅ Passed The title clearly summarizes the main N-API semantic alignment changes and names the key affected areas.
Description check ✅ Passed The description explains the changes, motivation, affected behaviors, linked issues, and verification results, despite using different section headings.

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

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/napi/napi_body.rs`:
- Around line 2541-2550: Update the documentation for schedule_dispatch to
clarify that holding self_.lock is required only when called by addon-thread
callers, while JS-thread callers such as this iteration-yield path and
env_teardown may call it without the lock. Keep the existing scheduling behavior
unchanged.
- Around line 2045-2049: Update the validation guard in napi_get_buffer_info to
reject bare SharedArrayBuffer values as well as bare ArrayBuffer values by
checking array_buf.shared alongside array_buf.typed_array_type. Preserve
acceptance of ArrayBufferView values, including shared typed arrays and
DataView.

In `@test/napi/napi-app/module.js`:
- Around line 1397-1401: Update both drivers in test/napi/napi-app/module.js: in
lines 1397-1401, replace the unconditional gcUntil predicate with a non-printing
native accessor that reports whether the weak referent was collected; in lines
1405-1411, replace the fixed ten-turn setImmediate loop with a bounded poll of
the recorded tsfn_nullcb_was_null state, stopping once call_js has run. Add or
reuse accessors without printf so checkSameOutput remains unchanged.

In `@test/napi/napi.test.ts`:
- Line 1564: Update the assertion in the relevant N-API test to match each of
the three result_written diagnostics separately, associating the expected value
with new_instance(throws), get_named_property(throws), and
has_named_property(throws). Keep checkSameOutput as the authoritative
full-output assertion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 45f754fc-f919-48a2-8bf9-f4ace8809522

📥 Commits

Reviewing files that changed from the base of the PR and between 52af832 and 67d06ce.

📒 Files selected for processing (6)
  • src/jsc/bindings/NapiRef.cpp
  • src/jsc/bindings/napi.cpp
  • src/runtime/napi/napi_body.rs
  • test/napi/napi-app/module.js
  • test/napi/napi-app/standalone_tests.cpp
  • test/napi/napi.test.ts

Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread test/napi/napi-app/module.js Resolved
Comment thread test/napi/napi.test.ts Resolved
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. napi: pass NULL js_callback to call_js_cb when no func was provided #30543 - Both fix TSFN call_js_cb to pass NULL napi_value (instead of encoded undefined) when created with func == NULL; napi: align symbol/buffer/coercion/reference/tsfn semantics with Node.js #36801 subsumes this as fix Copy source code contents of .bun files when bun build  #12 of its 13-fix bundle

🤖 Generated with Claude Code

Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread test/napi/napi-app/module.js Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread test/napi/napi-app/standalone_tests.cpp Resolved
Comment thread src/jsc/bindings/NapiRef.cpp Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/jsc/bindings/napi.cpp Resolved
Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread src/jsc/bindings/napi.cpp Resolved
Comment thread src/jsc/bindings/napi.cpp Resolved

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

All prior findings (TSFN yield-path UAF, external-string zero-length ownership, gcUntil predicate, dead test locals, kMaxIterationCount coverage) look addressed and nothing new turned up on this pass. Still deferring to a human: this is ~13 independent N-API behavioral changes across the C++ bindings and the Rust TSFN dispatch/refcount paths, and it needed two memory-safety fixes during review — worth a maintainer's eyes on the final shape.

What was reviewed:

  • TSFN on_dispatch yield: re-checked the closing == Closed guard against maybe_queue_finalizer/schedule_dispatch — the finalizer-already-queued path now returns before re-enqueue.
  • node_api_create_external_string_{latin1,utf16}: zero-length branch now returns napi_ok unconditionally after doFinalizer; length <= INT_MAX gate precedes the unsigned cast.
  • ToObject coercion sites (define_properties/freeze/seal/set_prototype/type_tag): each is under a throw scope that RETURN_IF_EXCEPTION reads.
  • NapiRef::ref() collected-referent check is scoped to refCount == 0 && !weakValueRef.isClear(), so strong/eternal refs are unaffected.
Extended reasoning...

Overview

Thirteen distinct N-API semantic-parity fixes spread across src/jsc/bindings/napi.cpp (symbol description, external-string arg validation, ToObject coercion for define/freeze/seal/set_prototype/type_tag, result-write ordering on exception, empty named key, module filename), src/jsc/bindings/NapiRef.cpp (napi_reference_ref after collection), and src/runtime/napi/napi_body.rs (TSFN js_callback NULL, kMaxIterationCount yield, napi_get_buffer_info ArrayBuffer gate). Test coverage lands in test/napi/napi-app/standalone_tests.cpp, module.js, and four new checkSameOutput cases in napi.test.ts.

Security risks

No auth/crypto/permission surface. The risk axis is memory safety in native code: TSFN task double-schedule after finalizer enqueue, and external-string ownership on the zero-length + pending-exception path. Both were flagged in earlier passes and have targeted fixes plus a 1200-item TSFN drain test that runs under ASAN.

Level of scrutiny

High. Per REVIEW.md this is the most-blocked category (native memory safety, refcounts, cross-thread TSFN lifecycle). The PR already required two correctness corrections mid-review (a UAF and an ownership/double-free), which is exactly why a maintainer should sign off on the final state rather than a bot.

Other factors

  • All earlier inline threads are resolved; the current bug-hunt pass found nothing new.
  • The test_tsfn_many_items fixture (1200 items, release, bounded poll) covers both the yield re-schedule and the Closed early-return under ASAN, closing the coverage gap I flagged.
  • checkSameOutput pins every changed status/pending/result-written line against Node v26, so behavioral regressions surface as byte diffs.
  • Breadth (13 functions in one PR) and the removal of a previously load-bearing pending-exception guard in the external-string path are the kind of design-shaped choices a human should confirm.

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

@robobun rebase

robobun added 5 commits August 3, 2026 07:54
A grab-bag of N-API functions whose observable behaviour (not just
return status) differed from Node.js v26, each verified by running the
same native addon under both runtimes:

- napi_set_named_property: accept the empty string as a property key
  (Node's CHECK_NEW_FROM_UTF8 only rejects nullptr).
- napi_create_symbol: only a nullptr description yields a symbol with
  no description; JS undefined/null return napi_string_expected, and an
  empty-string description produces Symbol('').description === ''.
- node_api_create_external_string_latin1/_utf16: accept (nullptr, 0)
  like Node's CHECK_NEW_STRING_ARGS, and reject length > INT_MAX with
  napi_invalid_arg instead of truncating into a wild pointer (crash).
- napi_get_buffer_info: reject a bare ArrayBuffer (Node gates on
  node::Buffer::HasInstance which is IsArrayBufferView).
- napi_define_properties / napi_object_freeze / napi_object_seal /
  napi_type_tag_object / napi_check_object_type_tag /
  node_api_set_prototype: ToObject-coerce primitives and leave the
  TypeError pending for null/undefined, instead of an unconditional
  napi_object_expected without an exception.
- napi_new_instance / napi_get_named_property / napi_has_named_property:
  check for an exception before writing *result so a failed call leaves
  the caller's out-param untouched.
- node_api_get_module_file_name: return "" instead of a null pointer
  when the env was created on a path that did not set a filename.
- NapiRef::ref(): when the weak referent has already been collected,
  leave the refcount at 0 (Node's Reference::Ref returns 0 once the
  persistent is empty).
- ThreadSafeFunction: when created without a JS func, pass a null
  napi_value to call_js_cb (addons test js_callback != NULL); cap the
  per-tick dispatch loop at 1000 iterations and re-schedule the
  remainder so a fast producer cannot starve the event loop.

Intentionally not changed: napi_set_property/_element put-return
(V8's Object::Set always returns Just(true), so Node's
napi_generic_failure branch is unreachable and Bun already matches),
and napi_get_prototype (Bun already avoids the Proxy trap).
Only return 0 when we held a weak handle that GC has since cleared; a
reference whose weak handle was never set (can_be_weak=false primitives)
keeps its previous ref() behaviour.
…rify schedule_dispatch lock contract

- Test drivers now poll test_weak_ref_is_collected /
  test_tsfn_null_js_callback_ran instead of assuming a fixed amount of
  event-loop progress.
- Spot-check each result_written line separately.
- schedule_dispatch doc: lock is only needed by addon-thread callers.
If the 1000th dispatch_one() in a tick drains the final item with
thread_count == 0 it enqueues the finalizer task and transitions
closing -> Closed before returning true. Re-scheduling from the yield
path then would enqueue a second on_dispatch on the same pointer, which
runs on freed memory after the finalizer task destroy()s it. Check the
closing state before re-scheduling.

Also tighten a few review-flagged comments and drop unused locals from
the new parity test.
… TSFN yield path

node_api_create_external_string_{latin1,utf16}: after adopting a
zero-length buffer and running its finalizer, return napi_ok directly.
The previous NAPI_RETURN_SUCCESS_UNLESS_EXCEPTION tail could observe an
exception that doFinalizer promoted from a pre-existing napi_throw and
report napi_pending_exception after the buffer had already been freed,
inviting a caller double-free. Node has no pending-exception gate here
and returns napi_ok.

Also add a test that enqueues 1200 TSFN items so the kMaxIterationCount
yield and re-schedule runs under ASAN and cannot silently stall or
double-dispatch.
@robobun
robobun force-pushed the farm/d4378f5e/napi-node26-semantic-fixes branch from f67c47f to 5b847ee Compare August 3, 2026 07:58
@robobun

robobun commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (aaf5e8a). The conflict was in test/napi/napi-app/standalone_tests.cpp where #36804 landed test_napi_status_codes_node26 at the same insertion point; both test functions are kept. Rebuilt and re-ran both suites locally.

Comment thread test/napi/napi-app/standalone_tests.cpp Resolved
… ASAN

With 1200 items the 1000th dispatch still has 200 queued, so the
closing == Closed early-return is never taken. 2000 (a multiple of the
cap) makes the second tick's 1000th dispatch the final item: the
finalizer is queued inside dispatch_one() and the yield path then hits
the guard.

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/runtime/napi/napi_body.rs (1)

3179-3183: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Synchronize the debug ownership checks with env_teardown.

env_teardown writes self.event_loop = None while holding func.lock. These addon-thread debug checks read the same non-atomic field without that lock. This can cause a data race during teardown.

  • src/runtime/napi/napi_body.rs#L3179-L3183: Hold func.lock while reading func.event_loop.
  • src/runtime/napi/napi_body.rs#L3200-L3204: Hold func.lock while reading func.event_loop.
Proposed fix
 #[cfg(debug_assertions)]
- if let (Some(loop_), Some(env)) = (func.event_loop.as_ref(), unsafe { env_.as_ref() }) {
-     debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js()));
+ if let Some(env) = unsafe { env_.as_ref() } {
+     let _g = func.lock.lock_guard();
+     if let Some(loop_) = func.event_loop.as_ref() {
+         debug_assert!(core::ptr::eq(loop_.global.unwrap().as_ptr(), env.to_js()));
+     }
  }

As per coding guidelines, “synchronize shared state.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/napi/napi_body.rs` around lines 3179 - 3183, Synchronize both
debug ownership checks in src/runtime/napi/napi_body.rs at lines 3179-3183 and
3200-3204 with env_teardown by acquiring func.lock before reading
func.event_loop. Keep the existing assertions and null/environment handling
unchanged; both sites require the lock while accessing the shared field.

Source: Coding guidelines

src/jsc/bindings/napi.cpp (1)

3012-3018: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Return unconditionally after throwing the out-of-memory error.

The guard depends on RETURN_IF_EXCEPTION to leave the function. If throwOutOfMemoryError does not leave an exception pending, control reaches JSBigInt::createFromWords with the oversized word_count, which is the read the guard exists to prevent. Make the early return explicit.

♻️ Proposed change
     if (word_count > jscBigIntMaxWords) {
         JSC::throwOutOfMemoryError(globalObject, scope);
-        RETURN_IF_EXCEPTION(scope, napi_set_last_error(env, napi_pending_exception));
+        return napi_set_last_error(env, napi_pending_exception);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/jsc/bindings/napi.cpp` around lines 3012 - 3018, Update the
oversized-word guard before JSBigInt::createFromWords to return unconditionally
after throwOutOfMemoryError, rather than relying on RETURN_IF_EXCEPTION;
preserve the existing pending-exception handling while ensuring oversized
word_count never reaches JSC::tryCreateFromWords.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/jsc/bindings/napi.cpp`:
- Around line 1457-1462: Update node_api_create_external_string_latin1 in
src/jsc/bindings/napi.cpp:1457-1462 to resolve NAPI_AUTO_LENGTH with strlen(str)
first, then validate length <= INT_MAX without exempting NAPI_AUTO_LENGTH before
the unsigned cast. Apply the same ordering and validation change in
node_api_create_external_string_utf16 at src/jsc/bindings/napi.cpp:1503-1508,
using std::char_traits<char16_t>::length(str); both sites require direct
changes.

In `@test/napi/napi-app/module.js`:
- Around line 1405-1421: Make both bounded polling drivers fail when their
expected completion condition is not met: in test_tsfn_null_js_callback_driver,
throw if test_tsfn_null_js_callback_ran() remains false after 1,000 iterations;
in test_tsfn_many_items_driver, throw unless test_tsfn_many_items_count() equals
exactly 2,000. Only invoke each corresponding result function after the
validation succeeds.

In `@test/napi/napi.test.ts`:
- Around line 1645-1649: Strengthen the first output assertion in the test
“napi_reference_ref returns 0 after the referent is collected” by matching the
complete first-line prefix, including “get_reference_value is undefined=” before
“reference_ref count=0”. Keep the second assertion targeting the separate
“second reference_ref count=0” line.

---

Outside diff comments:
In `@src/jsc/bindings/napi.cpp`:
- Around line 3012-3018: Update the oversized-word guard before
JSBigInt::createFromWords to return unconditionally after throwOutOfMemoryError,
rather than relying on RETURN_IF_EXCEPTION; preserve the existing
pending-exception handling while ensuring oversized word_count never reaches
JSC::tryCreateFromWords.

In `@src/runtime/napi/napi_body.rs`:
- Around line 3179-3183: Synchronize both debug ownership checks in
src/runtime/napi/napi_body.rs at lines 3179-3183 and 3200-3204 with env_teardown
by acquiring func.lock before reading func.event_loop. Keep the existing
assertions and null/environment handling unchanged; both sites require the lock
while accessing the shared field.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2ccda1e5-315a-47da-8bf7-a29ffb3e157c

📥 Commits

Reviewing files that changed from the base of the PR and between 67d06ce and 1033af6.

📒 Files selected for processing (6)
  • src/jsc/bindings/NapiRef.cpp
  • src/jsc/bindings/napi.cpp
  • src/runtime/napi/napi_body.rs
  • test/napi/napi-app/module.js
  • test/napi/napi-app/standalone_tests.cpp
  • test/napi/napi.test.ts

Comment thread src/jsc/bindings/napi.cpp Resolved
Comment thread test/napi/napi-app/module.js Resolved
Comment thread test/napi/napi.test.ts Resolved
@robobun

robobun commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI on 2cd35e8 (build 88054): the N-API tests pass on all lanes. The failures are unrelated to this diff:

  • test/cli/install/bun-add.test.ts on ubuntu 25.04 x64: git SSH infra (Permission denied (publickey) cloning github.com:mishoo/UglifyJS.git); the same test is retry-flaky on four other lanes
  • everything else is tagged flaky (passed on retry or in the isolated run)

Ready for review.

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

No new issues found — the earlier concerns (TSFN yield-path UAF, external-string zero-length ownership, and coverage for the closing == Closed guard) are all addressed in the current revision. Deferring to a human because this touches ~15 distinct N-API entry points across the C++ bindings and the Rust TSFN dispatch loop, several of which are memory-ownership boundaries.

What was reviewed:

  • TSFN on_dispatch iteration cap: verified the 2000-item test now hits the Closed early-return, and schedule_dispatch without the lock is JS-thread-only so it can't race env_teardown for event_loop.
  • node_api_create_external_string_* zero-length branch: confirmed both variants now unconditionally return napi_ok after doFinalizer, matching the non-zero path's ownership contract.
  • NAPI_CHECK_TO_OBJECT adoption in freeze/seal/define_properties/set_prototype/type_tag matches the existing macro pattern used by the element/property functions.
  • NapiRef::ref() collected-referent guard: !weakValueRef.isClear() && !weakValueRef.get() correctly distinguishes "was set, now collected" from "never set".
Extended reasoning...

Overview

This PR aligns ~15 N-API functions with Node.js v26 semantics: napi_set_named_property (empty key), napi_create_symbol (undefined/null/empty description), node_api_create_external_string_{latin1,utf16} (null str with len=0, INT_MAX overflow guard, zero-length ownership), napi_get_buffer_info (reject bare ArrayBuffer), ToObject coercion for napi_define_properties/napi_object_freeze/napi_object_seal/node_api_set_prototype/napi_type_tag_object/napi_check_object_type_tag, result-write ordering for napi_new_instance/napi_{get,has}_named_property, node_api_get_module_file_name non-null, napi_reference_ref after collection, TSFN js_callback NULL when created without a func, and the TSFN kMaxIterationCount yield. Files: src/jsc/bindings/NapiRef.cpp, src/jsc/bindings/napi.cpp, src/runtime/napi/napi_body.rs, plus checkSameOutput tests in test/napi/.

Security risks

No auth/crypto surface. The relevant risk class is memory safety at the FFI boundary: the external-string ownership contract (double-free on non-ok return), the TSFN dispatch re-schedule (UAF on a finalized pointer), and the static_cast<unsigned> span-length overflow. All three were examined during review — the first two were flagged and fixed in-PR, the third is the crash the PR itself fixes with the INT_MAX guard.

Level of scrutiny

High. N-API is the native-addon ABI; every function here is called from third-party C/C++ with caller-owned memory. The TSFN change edits a concurrent dispatch loop with atomic state and a finalizer that heap-frees self. Two memory-safety issues were found and fixed during the review cycle, which is a signal that the change class is non-trivial. The schedule_dispatch doc-comment change relaxes a lock precondition — I verified the new JS-thread-only caller can't race the only writer of event_loop (env_teardown, also JS-thread), but a maintainer sign-off on that reasoning would be valuable.

Other factors

Every behavioral change ships with a checkSameOutput test that byte-compares Bun against Node, which is strong coverage. All prior review threads (mine, CodeRabbit, comment-cop) are resolved; the only human interaction was a rebase request. The PR went through five fix commits responding to review, and the final state looks correct to me — but the breadth (15 entry points, two languages, refcounting + concurrency) puts it outside the bar for bot-only approval.

@robobun

robobun commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Split into five smaller PRs per review feedback, each with Node.js source links:

Leaving this draft open as the reference for the full audit.

dylan-conway pushed a commit that referenced this pull request Aug 3, 2026
Split from #36801 (1/5).

## What

When the threadsafe function was created with `func == NULL`, pass
`js_callback = NULL` to `call_js_cb` instead of an encoded `undefined`.

## Why (fixes #13771, closes #30543)

Node's `DispatchOne`
([src/node_api.cc#L452-L462](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L452-L462)):

```cpp
napi_value js_callback = nullptr;
if (!ref.IsEmpty()) {
  v8::Local<v8::Function> js_cb = v8::Local<v8::Function>::New(env->isolate, ref);
  js_callback = v8impl::JsValueFromV8LocalValue(js_cb);
}
env->CallbackIntoModule<false>(
    [&](napi_env env) { call_js_cb(env, js_callback, context, data); });
```

When `ref` is empty (the caller passed `func = NULL` to
`napi_create_threadsafe_function`), `js_callback` stays `nullptr`. Bun
was passing `napi_value::create(env,
cb_js.get().unwrap_or(JSValue::UNDEFINED))`, which is the encoded
`undefined` value (a non-zero pointer). Addons such as napi-rs and
lightningcss test `if (js_callback != NULL)` and, seeing a non-null
value, try to `napi_call_function` it:

```
thread '<unnamed>' panicked at napi/src/threadsafe_function.rs:235:57:
called `Result::unwrap()` on an `Err` value: Error { status: InvalidArg, reason: "expect Function, got: Undefined" }
```

## Verification

New `checkSameOutput` test fails under the released Bun:

```
$ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "passes NULL js_callback"
- "js_callback == NULL: 1
+ "js_callback == NULL: 0
```

The `kMaxIterationCount` cap that was in the first revision of this PR
has been dropped: no issue has been filed about the unbounded dispatch
loop, and the cap as written did not yield to setImmediate/timers anyway
(`enqueue_task_concurrent` is drained inside the same `tick()`).

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 3 · 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 -->
springmin pushed a commit to springmin/bun that referenced this pull request Aug 3, 2026
…#36845)

Split from oven-sh#36801 (1/5).

## What

When the threadsafe function was created with `func == NULL`, pass
`js_callback = NULL` to `call_js_cb` instead of an encoded `undefined`.

## Why (fixes oven-sh#13771, closes oven-sh#30543)

Node's `DispatchOne`
([src/node_api.cc#L452-L462](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L452-L462)):

```cpp
napi_value js_callback = nullptr;
if (!ref.IsEmpty()) {
  v8::Local<v8::Function> js_cb = v8::Local<v8::Function>::New(env->isolate, ref);
  js_callback = v8impl::JsValueFromV8LocalValue(js_cb);
}
env->CallbackIntoModule<false>(
    [&](napi_env env) { call_js_cb(env, js_callback, context, data); });
```

When `ref` is empty (the caller passed `func = NULL` to
`napi_create_threadsafe_function`), `js_callback` stays `nullptr`. Bun
was passing `napi_value::create(env,
cb_js.get().unwrap_or(JSValue::UNDEFINED))`, which is the encoded
`undefined` value (a non-zero pointer). Addons such as napi-rs and
lightningcss test `if (js_callback != NULL)` and, seeing a non-null
value, try to `napi_call_function` it:

```
thread '<unnamed>' panicked at napi/src/threadsafe_function.rs:235:57:
called `Result::unwrap()` on an `Err` value: Error { status: InvalidArg, reason: "expect Function, got: Undefined" }
```

## Verification

New `checkSameOutput` test fails under the released Bun:

```
$ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "passes NULL js_callback"
- "js_callback == NULL: 1
+ "js_callback == NULL: 0
```

The `kMaxIterationCount` cap that was in the first revision of this PR
has been dropped: no issue has been filed about the unbounded dispatch
loop, and the cap as written did not yield to setImmediate/timers anyway
(`enqueue_task_concurrent` is drained inside the same `tick()`).

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 3 · 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 -->
dylan-conway pushed a commit that referenced this pull request Aug 3, 2026
…e_tag/set_prototype (#36846)

Split from #36801 (2/5).

## What

`napi_define_properties`, `napi_object_freeze`, `napi_object_seal`,
`napi_type_tag_object`, `napi_check_object_type_tag`, and
`node_api_set_prototype` now ToObject-coerce a primitive `object`
argument (succeeding) and leave a `TypeError` pending for
`null`/`undefined`, instead of returning `napi_object_expected` with no
exception for any non-object.

| Input | Before (Bun) | Node.js / after |
|---|---|---|
| number/string/bool | `napi_object_expected`, no exception | `napi_ok`
(ToObject-coerced) |
| `null`/`undefined` (define_properties/freeze/seal/set_prototype) |
`napi_object_expected`, no exception | `napi_object_expected`, pending
`TypeError` |
| `null`/`undefined` (type_tag_object/check_object_type_tag) |
`napi_object_expected`, no exception | `napi_pending_exception` |

## Node.js source

All six use `CHECK_TO_OBJECT` or `CHECK_TO_OBJECT_WITH_PREAMBLE`, which
is `ToObject()` coercion
([src/js_native_api_v8.h#L245-L274](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.h#L245-L274)):

- `napi_define_properties`:
[src/js_native_api_v8.cc#L1426](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1426)
- `napi_object_freeze` / `napi_object_seal`:
[src/js_native_api_v8.cc#L1502](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1502),
[#L1519](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1519)
- `napi_type_tag_object` / `napi_check_object_type_tag`:
[src/js_native_api_v8.cc#L2728](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2728),
[#L2767](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2767)
(`_WITH_PREAMBLE` → `napi_pending_exception`)
- `node_api_set_prototype`:
[src/js_native_api_v8.cc#L1584](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1584)

`CHECK_TO_TYPE` returns the supplied status (`napi_object_expected`) on
failure; `CHECK_TO_TYPE_WITH_PREAMBLE` returns `napi_pending_exception`
when an exception was caught, which is why the two `type_tag` functions
report a different status on `null`.

## Verification

New `checkSameOutput` test compares Bun against Node byte-for-byte.
Fails under the released Bun (e.g. `define_properties(number): status=2
pending=0` vs Node's `status=0 pending=0`).

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
dylan-conway pushed a commit that referenced this pull request Aug 3, 2026
…ng, module_file_name (#36849)

Split from #36801 (4/5).

## What

| Function | Before (Bun) | Node.js / after |
|---|---|---|
| `napi_set_named_property(env, obj, "", v)` | `napi_invalid_arg` |
`napi_ok` (sets `obj[""]`) |
| `napi_create_symbol(env, <js undefined/null>, &r)` | `napi_ok`,
`Symbol()` | `napi_string_expected` |
| `napi_create_symbol(env, <js "">, &r)` | `.description === undefined`
| `.description === ""` |
| `napi_new_instance` / `napi_get_named_property` /
`napi_has_named_property` when underlying JS throws | writes `*result`,
then `napi_pending_exception` | `napi_pending_exception`, `*result`
untouched |
| `node_api_get_module_file_name` on the `napi_module_register` path |
writes `NULL` | writes `""` |

## Node.js source

- `napi_set_named_property` uses `CHECK_NEW_FROM_UTF8`, which only
rejects `nullptr`: [src/js_native_api_v8.cc#L25-L41,
#L1262-L1283](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L25-L41)
- `napi_create_symbol` special-cases only `description == nullptr`; any
non-null non-string is `napi_string_expected`:
[src/js_native_api_v8.cc#L1925-L1944](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1925-L1944)
- `napi_new_instance` / `napi_get_named_property` /
`napi_has_named_property` check the `Maybe` before writing `*result`:
[src/js_native_api_v8.cc#L3026-L3029](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L3026-L3029),
[#L1327-L1331](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1327-L1331),
[#L1303-L1306](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1303-L1306)
- `node_api_get_module_file_name` returns `filename.c_str()` from a
`std::string`, which is never `NULL`:
[src/node_api.cc#L1456-L1464](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1456-L1464),
[src/node_api_internals.h#L39-L41](https://github.com/nodejs/node/blob/v26.x/src/node_api_internals.h#L39-L41)

## Verification

New `checkSameOutput` test compares Bun against Node byte-for-byte;
fails under the released Bun.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
springmin pushed a commit to springmin/bun that referenced this pull request Aug 3, 2026
…e_tag/set_prototype (oven-sh#36846)

Split from oven-sh#36801 (2/5).

## What

`napi_define_properties`, `napi_object_freeze`, `napi_object_seal`,
`napi_type_tag_object`, `napi_check_object_type_tag`, and
`node_api_set_prototype` now ToObject-coerce a primitive `object`
argument (succeeding) and leave a `TypeError` pending for
`null`/`undefined`, instead of returning `napi_object_expected` with no
exception for any non-object.

| Input | Before (Bun) | Node.js / after |
|---|---|---|
| number/string/bool | `napi_object_expected`, no exception | `napi_ok`
(ToObject-coerced) |
| `null`/`undefined` (define_properties/freeze/seal/set_prototype) |
`napi_object_expected`, no exception | `napi_object_expected`, pending
`TypeError` |
| `null`/`undefined` (type_tag_object/check_object_type_tag) |
`napi_object_expected`, no exception | `napi_pending_exception` |

## Node.js source

All six use `CHECK_TO_OBJECT` or `CHECK_TO_OBJECT_WITH_PREAMBLE`, which
is `ToObject()` coercion
([src/js_native_api_v8.h#L245-L274](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.h#L245-L274)):

- `napi_define_properties`:
[src/js_native_api_v8.cc#L1426](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1426)
- `napi_object_freeze` / `napi_object_seal`:
[src/js_native_api_v8.cc#L1502](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1502),
[#L1519](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1519)
- `napi_type_tag_object` / `napi_check_object_type_tag`:
[src/js_native_api_v8.cc#L2728](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2728),
[#L2767](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L2767)
(`_WITH_PREAMBLE` → `napi_pending_exception`)
- `node_api_set_prototype`:
[src/js_native_api_v8.cc#L1584](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1584)

`CHECK_TO_TYPE` returns the supplied status (`napi_object_expected`) on
failure; `CHECK_TO_TYPE_WITH_PREAMBLE` returns `napi_pending_exception`
when an exception was caught, which is why the two `type_tag` functions
report a different status on `null`.

## Verification

New `checkSameOutput` test compares Bun against Node byte-for-byte.
Fails under the released Bun (e.g. `define_properties(number): status=2
pending=0` vs Node's `status=0 pending=0`).

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
springmin pushed a commit to springmin/bun that referenced this pull request Aug 3, 2026
…ng, module_file_name (oven-sh#36849)

Split from oven-sh#36801 (4/5).

## What

| Function | Before (Bun) | Node.js / after |
|---|---|---|
| `napi_set_named_property(env, obj, "", v)` | `napi_invalid_arg` |
`napi_ok` (sets `obj[""]`) |
| `napi_create_symbol(env, <js undefined/null>, &r)` | `napi_ok`,
`Symbol()` | `napi_string_expected` |
| `napi_create_symbol(env, <js "">, &r)` | `.description === undefined`
| `.description === ""` |
| `napi_new_instance` / `napi_get_named_property` /
`napi_has_named_property` when underlying JS throws | writes `*result`,
then `napi_pending_exception` | `napi_pending_exception`, `*result`
untouched |
| `node_api_get_module_file_name` on the `napi_module_register` path |
writes `NULL` | writes `""` |

## Node.js source

- `napi_set_named_property` uses `CHECK_NEW_FROM_UTF8`, which only
rejects `nullptr`: [src/js_native_api_v8.cc#L25-L41,
#L1262-L1283](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L25-L41)
- `napi_create_symbol` special-cases only `description == nullptr`; any
non-null non-string is `napi_string_expected`:
[src/js_native_api_v8.cc#L1925-L1944](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1925-L1944)
- `napi_new_instance` / `napi_get_named_property` /
`napi_has_named_property` check the `Maybe` before writing `*result`:
[src/js_native_api_v8.cc#L3026-L3029](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L3026-L3029),
[#L1327-L1331](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1327-L1331),
[#L1303-L1306](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L1303-L1306)
- `node_api_get_module_file_name` returns `filename.c_str()` from a
`std::string`, which is never `NULL`:
[src/node_api.cc#L1456-L1464](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1456-L1464),
[src/node_api_internals.h#L39-L41](https://github.com/nodejs/node/blob/v26.x/src/node_api_internals.h#L39-L41)

## Verification

New `checkSameOutput` test compares Bun against Node byte-for-byte;
fails under the released Bun.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
Jarred-Sumner pushed a commit that referenced this pull request Aug 4, 2026
…_NEW_STRING_ARGS (#36847)

Split from #36801 (3/5).

## What

`node_api_create_external_string_latin1` / `_utf16`:

- Accept `(str = NULL, length = 0)` and return the empty string
- Reject `length > INT_MAX` with `napi_invalid_arg` (previously the
`static_cast<unsigned int>(length)` truncated into a wild span over the
caller's buffer and **crashed**)
- Zero-length branch returns `napi_ok` directly after running the
finalizer, so a pre-existing `napi_throw_*` that `doFinalizer` promotes
to the VM cannot cause a non-ok status after the buffer has already been
freed

| Input | Before (Bun) | Node.js / after |
|---|---|---|
| `(NULL, 0)` | `napi_invalid_arg` | `napi_ok` (empty string) |
| `(ptr, INT_MAX+1)` | **crash** | `napi_invalid_arg` |

## Node.js source

`CHECK_NEW_STRING_ARGS`
([src/js_native_api_v8.cc#L43-L52](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L43-L52)):

```cpp
#define CHECK_NEW_STRING_ARGS(env, str, length, result)                        \
  do {                                                                         \
    CHECK_ENV_NOT_IN_GC((env));                                                \
    if ((length) > 0) CHECK_ARG((env), (str));                                 \
    CHECK_ARG((env), (result));                                                \
    RETURN_STATUS_IF_FALSE(                                                    \
        (env),                                                                 \
        ((length) == NAPI_AUTO_LENGTH) || (length) <= INT_MAX,                 \
        napi_invalid_arg);                                                     \
  } while (0)
```

Used by `NewExternalString` at
[src/js_native_api_v8.cc#L107-L137](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L107-L137).
No pending-exception gate.

## Verification

New `checkSameOutput` test in `test/napi/napi.test.ts`. The released Bun
returns `status=1` for `(NULL,0)` and crashes on `(ptr, INT_MAX+1)`.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
springmin pushed a commit to springmin/bun that referenced this pull request Aug 4, 2026
…_NEW_STRING_ARGS (oven-sh#36847)

Split from oven-sh#36801 (3/5).

## What

`node_api_create_external_string_latin1` / `_utf16`:

- Accept `(str = NULL, length = 0)` and return the empty string
- Reject `length > INT_MAX` with `napi_invalid_arg` (previously the
`static_cast<unsigned int>(length)` truncated into a wild span over the
caller's buffer and **crashed**)
- Zero-length branch returns `napi_ok` directly after running the
finalizer, so a pre-existing `napi_throw_*` that `doFinalizer` promotes
to the VM cannot cause a non-ok status after the buffer has already been
freed

| Input | Before (Bun) | Node.js / after |
|---|---|---|
| `(NULL, 0)` | `napi_invalid_arg` | `napi_ok` (empty string) |
| `(ptr, INT_MAX+1)` | **crash** | `napi_invalid_arg` |

## Node.js source

`CHECK_NEW_STRING_ARGS`
([src/js_native_api_v8.cc#L43-L52](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L43-L52)):

```cpp
#define CHECK_NEW_STRING_ARGS(env, str, length, result)                        \
  do {                                                                         \
    CHECK_ENV_NOT_IN_GC((env));                                                \
    if ((length) > 0) CHECK_ARG((env), (str));                                 \
    CHECK_ARG((env), (result));                                                \
    RETURN_STATUS_IF_FALSE(                                                    \
        (env),                                                                 \
        ((length) == NAPI_AUTO_LENGTH) || (length) <= INT_MAX,                 \
        napi_invalid_arg);                                                     \
  } while (0)
```

Used by `NewExternalString` at
[src/js_native_api_v8.cc#L107-L137](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L107-L137).
No pending-exception gate.

## Verification

New `checkSameOutput` test in `test/napi/napi.test.ts`. The released Bun
returns `status=1` for `(NULL,0)` and crashes on `(ptr, INT_MAX+1)`.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 5 · 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 -->
Jarred-Sumner pushed a commit that referenced this pull request Aug 4, 2026
…api_get_buffer_info rejects bare ArrayBuffer (#36850)

Split from #36801 (5/5).

## What

| Function | Before (Bun) | Node.js / after |
|---|---|---|
| `napi_reference_ref` after the weak referent is collected | increments
(returns 1, 2, ...) | returns 0, does not increment |
| `napi_get_buffer_info(env, <ArrayBuffer>, ...)` | `napi_ok` |
`napi_invalid_arg` |

## Node.js source

- `Reference::Ref()` returns 0 without incrementing once the persistent
is empty:
[src/js_native_api_v8.cc#L690-L700](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L690-L700)

  ```cpp
  uint32_t Reference::Ref() {
    if (persistent_.IsEmpty()) {
      return 0;
    }
    if (++refcount_ == 1 && can_be_weak_) {
      persistent_.ClearWeak();
    }
    return refcount_;
  }
  ```

The check in `NapiRef::ref()` is `refCount == 0 &&
!weakValueRef.isClear() && !weakValueRef.get()` so it only fires when a
weak handle was set and has since been cleared by GC; strongly-held or
never-weak references keep their existing behaviour.

- `napi_get_buffer_info` gates on `node::Buffer::HasInstance`:
[src/node_api.cc#L1150-L1169](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1150-L1169),
which is `IsArrayBufferView()`
([src/node_buffer.cc](https://github.com/nodejs/node/blob/v26.x/src/node_buffer.cc)).
Typed arrays and DataView pass; a bare `ArrayBuffer` /
`SharedArrayBuffer` does not.

## Verification

Two new `checkSameOutput` tests. The `reference_ref` driver polls
`napi_get_reference_value` via `gcUntil` so it waits for collection
instead of assuming a single GC pass.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 8 · 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 -->
springmin pushed a commit to springmin/bun that referenced this pull request Aug 4, 2026
…api_get_buffer_info rejects bare ArrayBuffer (oven-sh#36850)

Split from oven-sh#36801 (5/5).

## What

| Function | Before (Bun) | Node.js / after |
|---|---|---|
| `napi_reference_ref` after the weak referent is collected | increments
(returns 1, 2, ...) | returns 0, does not increment |
| `napi_get_buffer_info(env, <ArrayBuffer>, ...)` | `napi_ok` |
`napi_invalid_arg` |

## Node.js source

- `Reference::Ref()` returns 0 without incrementing once the persistent
is empty:
[src/js_native_api_v8.cc#L690-L700](https://github.com/nodejs/node/blob/v26.x/src/js_native_api_v8.cc#L690-L700)

  ```cpp
  uint32_t Reference::Ref() {
    if (persistent_.IsEmpty()) {
      return 0;
    }
    if (++refcount_ == 1 && can_be_weak_) {
      persistent_.ClearWeak();
    }
    return refcount_;
  }
  ```

The check in `NapiRef::ref()` is `refCount == 0 &&
!weakValueRef.isClear() && !weakValueRef.get()` so it only fires when a
weak handle was set and has since been cleared by GC; strongly-held or
never-weak references keep their existing behaviour.

- `napi_get_buffer_info` gates on `node::Buffer::HasInstance`:
[src/node_api.cc#L1150-L1169](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L1150-L1169),
which is `IsArrayBufferView()`
([src/node_buffer.cc](https://github.com/nodejs/node/blob/v26.x/src/node_buffer.cc)).
Typed arrays and DataView pass; a bare `ArrayBuffer` /
`SharedArrayBuffer` does not.

## Verification

Two new `checkSameOutput` tests. The `reference_ref` driver polls
`napi_get_reference_value` via `gcUntil` so it waits for collection
instead of assuming a single GC pass.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 8 · 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 -->
Jarred-Sumner pushed a commit that referenced this pull request Aug 18, 2026
… 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 -->
@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Nov 15, 2026
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.

Panic with vite+lightningcss when using visitors

2 participants