Skip to content

Fix null deref in forEachProperty when Proxy prototype throws - #28882

Closed
robobun wants to merge 9 commits into
mainfrom
farm/6c267311/fix-null-deref-foreachproperty
Closed

robobun wants to merge 9 commits into
mainfrom
farm/6c267311/fix-null-deref-foreachproperty

Conversation

@robobun

@robobun robobun commented Apr 5, 2026

Copy link
Copy Markdown
Collaborator

When iterating prototypes in `JSC__JSValue__forEachPropertyImpl`, calling `getPrototype()` on an object with a Proxy in the chain can throw, returning an empty `JSValue`. Calling `.getObject()` on that empty value hits UBSan as a member call on a null `JSCell*` (the tag bits of an empty JSValue match `isCell()` but the pointer is null).

The fast path above (~line 5121) already guards against this with the same pattern. Mirror it in the slow path: clear the exception, and treat an empty prototype as "no more prototypes to visit".

Repro:
```js
const v1 = Bun.jest();
const v2 = v1.expect(v1);
Object.setPrototypeOf(v2, new Proxy(Object.getPrototypeOf(v2), {}));
Bun.inspect(v2);
```

Fixes a Fuzzilli-found crash (fingerprint `147521e6b763081c`).

@github-actions github-actions Bot added the claude label Apr 5, 2026
@robobun

robobun commented Apr 5, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:06 AM PT - Apr 5th, 2026

❌ @robobun, your commit 4a32946 has 3 failures in Build #43819 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 28882

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

bun-28882 --bun

@github-actions

github-actions Bot commented Apr 5, 2026

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. bun eslint.config.mjs | more panixs #17381 - Crash stack trace goes through JSC__JSValue__forEachPropertyImpl during console output, matching the exact code path this PR fixes

If this is helpful, consider adding Fixes #17381 to the PR description to auto-close the issue on merge.

🤖 Generated with Claude Code

@robobun
robobun requested a review from alii as a code owner April 5, 2026 05:45
@robobun
robobun force-pushed the farm/6c267311/fix-null-deref-foreachproperty branch from f6ab668 to 2eb666e Compare April 5, 2026 05:46
@coderabbitai

coderabbitai Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Prototype traversal now captures prototype lookups into temporaries, clears pending exceptions from Proxy getPrototype traps, and guards against null prototypes to avoid aborting enumeration; a test was added to exercise Bun.inspect on an object whose prototype is a Proxy.

Changes

Cohort / File(s) Summary
Prototype handling — JSC bindings
src/bun.js/bindings/bindings.cpp
Store getPrototype result in a temporary JSValue, clear pending exceptions from Proxy getPrototype traps, and check for null before advancing the prototype walk in JSC__JSValue__forEachPropertyImpl.
Prototype handling — N-API bindings
src/bun.js/bindings/napi.cpp
Capture getPrototype as JSValue protoVal, clear exceptions (CLEAR_IF_EXCEPTION(...)), and derive JSObject* proto only if non-empty to avoid propagating Proxy getPrototype exceptions during prototype traversal in napi_get_all_property_names.
Tests — inspect crash cases
test/js/bun/util/inspect.test.js
Add a crash-test input factory that sets an object's prototype to a Proxy (via Object.setPrototypeOf) so Bun.inspect(await input()) is exercised with a proxied prototype.
🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main fix: handling null dereference in forEachProperty when a Proxy prototype throws.
Description check ✅ Passed The description covers the 'What does this PR do?' section well with detailed technical explanation, repro case, and bug reference, but lacks explicit 'How did you verify your code works?' section.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — minimal, targeted crash fix that mirrors the existing fast-path guard.

Extended reasoning...

Overview

Two files changed: a 4-line fix in src/bun.js/bindings/bindings.cpp to the slow path of JSC__JSValue__forEachPropertyImpl, and two new regression test cases in test/js/bun/util/inspect.test.js.

Security risks

None. The change only affects how prototype-chain traversal handles exceptions from Proxy traps during Bun.inspect. There is no new attack surface.

Level of scrutiny

Low — this is a one-line logic fix that exactly mirrors a guard already present in the fast path a hundred lines above. The pattern (CLEAR_IF_EXCEPTION + null-check before .getObject()) is established convention in this file. The root cause (UBSan null deref when Proxy getPrototype trap throws) is well-understood and the fix is the minimal correct response.

Other factors

No bugs found by the bug-hunting system. Regression tests cover both a simple case and the exact Fuzzilli-found reproducer. The PR is already merging as commit 2eb666e on main.

Comment thread test/js/bun/util/inspect.test.js Resolved
Comment thread src/bun.js/bindings/bindings.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.

Both prior concerns addressed — LGTM.

Extended reasoning...

Overview

This PR fixes a UBSan null member-call crash in two prototype-chain traversal paths: the JSC forEachPropertyImpl slow path in bindings.cpp and the NAPI napi_get_all_property_names prototype walk in napi.cpp. A third-file change adds two crash-testing fixtures to inspect.test.js.

Changes since last review

My previous review raised two issues: (1) napi.cpp:1837 still had the unsafe .getPrototype().getObject() pattern, and (2) the second test fixture called Bun.jest() with no arguments, causing it to throw before Bun.inspect was ever reached. Both are addressed in the current diff: napi.cpp now uses the same safe JSValue protoVal / CLEAR_IF_EXCEPTION / conditional getObject() pattern, and the fixture now passes Bun.fileURLToPath(import.meta.url).

Security risks

None. The changes are purely defensive: they prevent a crash by clearing Proxy-trap exceptions and guarding null pointers. No auth, crypto, or permission-sensitive code is touched.

Level of scrutiny

Medium-low. The fix is a mechanical, well-understood pattern already used elsewhere in the same file (the fast path above ~line 5121 uses the identical guard). The remaining inline nit about CLEAR_IF_EXCEPTION potentially swallowing getOwnPropertyDescriptor exceptions in napi_get_all_property_names is a real but narrow correctness concern; it is already noted in the inline comment and represents a separate, incremental improvement rather than a blocker.

Other factors

The fix addresses a Fuzzilli-found crash with a known fingerprint, and coderabbitai found no actionable issues. CI failure on an earlier commit was in a build step unrelated to these source changes.

Comment thread src/bun.js/bindings/napi.cpp Resolved
Comment thread test/js/bun/util/inspect.test.js 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.

LGTM — all three prior bug reports have been addressed in the follow-up commits.

Extended reasoning...

Overview

This PR fixes a Fuzzilli-found UBSan null member-call crash in JSC__JSValue__forEachPropertyImpl (bindings.cpp) where calling .getObject() on an empty JSValue returned by getPrototype() after a Proxy [[GetPrototypeOf]] trap throws causes UB. The fix captures the result in a JSValue temporary, clears the pending exception via CLEAR_IF_EXCEPTION, and derives the JSObject* only when non-empty. Three files are modified: the core slow-path fix in bindings.cpp, a mirrored fix in napi.cpp, and a crash-test fixture in inspect.test.js.

Prior concerns and resolution

My three previous bug reports have been addressed in subsequent commits:

  1. napi.cpp same UBSan crash (original comment): Fixed in d975a2b — the identical getPrototype().getObject() pattern in napi_get_all_property_names is now guarded with a protoVal temporary and null check.
  2. Bun.jest() no-args fixture: Fixed in c6a3946 — the problematic fixture that would throw "Bun.jest() expects a string filename" was removed entirely.
  3. CLEAR_IF_EXCEPTION silently discarding getOwnPropertyDescriptor exceptions: Fixed in c64df4b — NAPI_RETURN_IF_EXCEPTION(env) is now placed before calling getPrototype() so that exceptions from the loop condition are propagated rather than cleared.

Security risks

The empty-Proxy-handler test fixture still does not exercise the specific throwing-trap code path (my 4th inline comment), so the added test provides partial regression coverage. This is a test quality issue only; the underlying fix is correct. The pre-existing infinite-loop risk from a self-referential Proxy in napi_get_all_property_names (flagged by the bug hunter) is not introduced by this PR and is out of scope.

Level of scrutiny

Medium — this is a targeted crash fix in C++ JSC bindings with a clear root cause and well-understood fix pattern. The code changes are small and closely mirror the fast-path guard that already existed. The napi.cpp changes touch native addon code but follow the same exception-handling conventions used throughout that file.

Other factors

The overall fix is correct, conservative, and well-commented. The bug-hunt flagged one pre-existing DoS (depth-unbounded prototype walk in napi.cpp) that is orthogonal to the crash being fixed here.

Comment on lines 1834 to 1844
// Climb up the prototype chain to find inherited properties
JSObject* current_object = object;
while (!current_object->getOwnPropertyDescriptor(globalObject, key.toPropertyKey(globalObject), desc)) {
JSObject* proto = current_object->getPrototype(globalObject).getObject();
NAPI_RETURN_IF_EXCEPTION(env);
JSValue protoVal = current_object->getPrototype(globalObject);
// Ignore exceptions from Proxy "getPrototype" trap.
CLEAR_IF_EXCEPTION(napi_preamble_throw_scope__);
JSObject* proto = protoVal ? protoVal.getObject() : nullptr;
if (!proto) {
break;
}

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.

🟣 The while loop in napi_get_all_property_names (napi.cpp:1836) that climbs the prototype chain has no iteration depth limit, unlike the analogous slow path in bindings.cpp which caps at 5 prototype hops (prototypeCount++ < 5). A Proxy whose [[GetPrototypeOf]] trap returns itself (valid per spec when extensible) and whose [[GetOwnProperty]] trap always returns false will cause the process to hang forever. This is a pre-existing issue, but the PR directly modifies this loop body without addressing the missing depth guard.

Extended reasoning...

What the bug is and how it manifests

The while loop in napi_get_all_property_names (napi.cpp:1836) walks the prototype chain to find an inherited property descriptor. The loop has no bound on the number of prototype hops it will take. The PR correctly adds exception-handling plumbing (NAPI_RETURN_IF_EXCEPTION + CLEAR_IF_EXCEPTION) to this loop body, but does not add the depth guard that the analogous slow path in JSC__JSValue__forEachPropertyImpl (bindings.cpp:5143) uses: while (iterating && ... && prototypeCount++ < 5).

The specific code path that triggers it

A native addon calls napi_get_all_property_names(env, obj, napi_key_own_and_inherited, napi_key_all_properties, napi_key_include_prototypes, result) where obj's prototype chain contains a Proxy P that: (a) has a [[GetPrototypeOf]] trap returning P itself (allowed by the ECMAScript spec when the Proxy target is extensible), and (b) has a [[GetOwnProperty]] trap that always returns undefined/false. The outer loop over exportKeys reaches a key that is not an own property of the initial object, so the inner while loop begins climbing prototypes.

Why existing code doesn't prevent it

Each iteration of the while loop: (1) calls getOwnPropertyDescriptor → returns false (trap); (2) NAPI_RETURN_IF_EXCEPTION passes (no exception); (3) getPrototype returns P itself; (4) CLEAR_IF_EXCEPTION is a no-op; (5) proto = P (non-null, no break); (6) current_object = P. The loop condition is immediately re-evaluated with the same Proxy and the cycle repeats forever. The bindings.cpp slow path prevents exactly this scenario with its prototypeCount++ < 5 guard.

What the impact would be

Any native Node.js addon that triggers napi_get_all_property_names with napi_key_include_prototypes on a self-referential Proxy (e.g., a malicious npm package or crafted input) will hang the Bun process in an uninterruptible infinite loop, constituting a denial-of-service.

How to fix it

Mirror the bindings.cpp guard by adding a prototypeCount variable and bounding the loop:

int prototypeCount = 0;
JSObject* current_object = object;
while (!current_object->getOwnPropertyDescriptor(globalObject, key.toPropertyKey(globalObject), desc)) {
    NAPI_RETURN_IF_EXCEPTION(env);
    if (prototypeCount++ >= 5) break;  // <-- depth guard, same as bindings.cpp
    JSValue protoVal = current_object->getPrototype(globalObject);
    CLEAR_IF_EXCEPTION(napi_preamble_throw_scope__);
    JSObject* proto = protoVal ? protoVal.getObject() : nullptr;
    if (!proto) break;
    current_object = proto;
}

Step-by-step proof

  1. Addon calls napi_get_all_property_names with napi_key_include_prototypes on an object whose [[Prototype]] is a Proxy P where P.[[GetPrototypeOf]]() === P and P.[[GetOwnProperty]]() always returns undefined.
  2. The outer loop iterates over exportKeys; for some key, getOwnPropertyDescriptor on the initial object returns false.
  3. The while loop enters: current_object = P.
  4. P.getOwnPropertyDescriptor(...) → false → enter body.
  5. NAPI_RETURN_IF_EXCEPTION → passes (trap did not throw).
  6. P.getPrototype() → returns P (self-referential); CLEAR_IF_EXCEPTION → no-op.
  7. proto = P (non-null) → no break; current_object = P.
  8. Return to step 4 — loop runs forever; process hangs.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — all previously raised concerns have been addressed in follow-up commits.

Extended reasoning...

Overview

This PR fixes a UBSan null member-call crash in JSC__JSValue__forEachPropertyImpl (bindings.cpp) and the identical pattern in napi_get_all_property_names (napi.cpp). The fix mirrors the existing fast-path guard: capture the getPrototype result in a temporary JSValue, clear any pending exception from a Proxy [[GetPrototypeOf]] trap, and treat an empty result as end-of-chain.

Security risks

None introduced. The changes make exception handling more robust without changing any auth, crypto, or permission logic.

Level of scrutiny

The changes are small and surgical — each hunk is 4–5 lines following an established pattern already present in the fast path. The test fixture was updated to use a throwing getPrototypeOf trap, so the fix is actually exercised rather than passing trivially. Scrutiny is appropriate for a focused crash fix at this level.

Other factors

Previous review iterations flagged five distinct issues (Bun.jest() no-arg crash, missing napi.cpp fix, CLEAR_IF_EXCEPTION swallowing getOwnPropertyDescriptor exceptions, missing depth limit, empty Proxy handler not exercising the fix). Commits d975a2b, c6a3946, c64df4b, and 9e3baf5 address all of them except the depth limit, which was explicitly noted as a pre-existing issue predating this PR and not introduced by it. The CI failure is in an unrelated Azure service-bus test.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — all previously raised concerns have been addressed: the test now uses a throwing getPrototypeOf trap, napi.cpp properly propagates getOwnPropertyDescriptor exceptions via NAPI_RETURN_IF_EXCEPTION, and the unsafe Bun.jest() fixture was removed.

Extended reasoning...

Overview

This PR fixes a UBSan null-member-call crash in JSC__JSValue__forEachPropertyImpl (bindings.cpp) and mirrors the same guard in napi_get_all_property_names (napi.cpp). When a Proxy's getPrototypeOf trap throws, getPrototype() returns an empty JSValue whose tag bits match isCell() but whose cell pointer is null; calling .getObject() on it is UB. The fix captures the return value into a temp, clears the pending exception, and null-checks before advancing.

Previous revision concerns — now resolved

My prior reviews flagged three issues. All three are fixed in the current revision:

  1. Test quality (empty Proxy handler): The new fixture now uses getPrototypeOf() { throw new Error("boom"); }, which actually triggers the code path being guarded.
  2. napi.cpp exception propagation: NAPI_RETURN_IF_EXCEPTION(env) is now placed at the top of the loop body, so exceptions from getOwnPropertyDescriptor in the while condition are returned to the caller rather than silently cleared by the subsequent CLEAR_IF_EXCEPTION.
  3. Dead Bun.jest() fixture: The Bun.jest() crash fixture (which threw before Bun.inspect was reached) was removed.

Security risks

No security-sensitive code paths involved. The change prevents a crash by clearing exceptions from Proxy traps during prototype traversal — consistent with how the fast path already behaves.

Level of scrutiny

Low-to-medium. The change is a targeted crash fix with a clear root cause, a matching repro, and a test that exercises the specific code path. The pattern mirrors the already-existing fast-path guard in the same file.

Other factors

No outstanding unresolved reviewer comments remain. The core C++ changes are small, mechanical, and follow established conventions in the codebase.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — the primary crash fix is correct, the test now properly exercises the throwing-trap path, and the getOwnPropertyDescriptor exception propagation concern has been addressed. The remaining depth-limit note is pre-existing and can be tracked separately.

Extended reasoning...

Overview

The PR adds a null-deref guard in JSC__JSValue__forEachPropertyImpl (bindings.cpp) and mirrors the same fix in napi_get_all_property_names (napi.cpp). The test adds a crash-test fixture that uses a Proxy with a throwing getPrototypeOf trap.

Security risks

None introduced. The change is strictly defensive: it prevents a UBSan null-member-call crash when a Proxy's [[GetPrototypeOf]] trap throws. The CLEAR_IF_EXCEPTION pattern here intentionally swallows the Proxy exception rather than propagating it, which is correct — the JS spec says that inspection/iteration is not required to surface prototype-traversal errors.

Level of scrutiny

Moderate. The fix is a two-line mechanical change that mirrors the existing fast-path guard already present in the same function. The napi.cpp fix adds NAPI_RETURN_IF_EXCEPTION(env) before getPrototype, which correctly propagates getOwnPropertyDescriptor exceptions and was added in response to my prior review. The test change now exercises the exact crash path with a throwing trap.

Other factors

My earlier feedback about the empty Proxy handler, the Bun.jest() argument issue, and the getOwnPropertyDescriptor exception-swallowing have all been addressed in follow-up commits (c64df4b, 9e3baf5). The outstanding inline comment about the missing depth-limit guard in the napi.cpp while loop is a pre-existing issue that predates this PR and does not make the situation worse. It is appropriate to track that separately.

@robobun

robobun commented Apr 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI failure is in test/js/third_party/@azure/service-bus/azure-service-bus.test.ts which crashes with ERROR: Unchecked JS exception at getIfPropertyExists in JSC. This test:

  • Requires TEST_INFO_AZURE_SERVICE_BUS secret and crashes on module load (skips locally without the secret)
  • Fails in the exact same way on multiple retries across 3 builds
  • The crash is in pre-existing JSC exception-check machinery triggered by azure-service-bus package imports, not in code this PR touches

The fix itself — guarding getPrototype().getObject() against empty JSValue from throwing Proxy traps — is minimal, correct, mirrors an existing fast-path guard, and is LGTM'd by two reviewers.

robobun added a commit that referenced this pull request Apr 23, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
@robobun

robobun commented Apr 23, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #29642, which combines the getPropertySlot exception-clear reorder, the getPrototype() null guard, the EnsureStillAliveScope for the prototype-walk object, and the equivalent guard in napi_get_all_property_names.

@robobun robobun closed this Apr 23, 2026
@robobun
robobun deleted the farm/6c267311/fix-null-deref-foreachproperty branch April 23, 2026 21:41
robobun added a commit that referenced this pull request Apr 26, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
Jarred-Sumner pushed a commit that referenced this pull request May 4, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
robobun added a commit that referenced this pull request Aug 13, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
robobun added a commit that referenced this pull request Aug 17, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
robobun added a commit that referenced this pull request Aug 17, 2026
…get_all_property_names

Hold the current link in the prototype chain as a JSValue under an
EnsureStillAliveScope so a Proxy trap that runs JS (and may GC) during
property enumeration can't free it out from under us.

Also guard the equivalent getPrototype().getObject() pattern in
napi_get_all_property_names, propagating Proxy trap exceptions as
napi_pending_exception.

Supersedes #29071 #28991 #28919 #28918 #28882 #28854 #28530 #28325.
dylan-conway pushed a commit that referenced this pull request Aug 18, 2026
…p or getPrototypeOf throws during the property walk (#29642)

### Problem

- `Bun.inspect()`, `console.log()` and `expect()` failure output crash
with `Segmentation fault at address 0x5` (debug builds: UBSan "member
call on null pointer of type 'JSC::JSCell'" in `JSCJSValueCell.h`) when
a property lookup throws while an object is being formatted. Release
repro:
  ```js
const proto = new Proxy({ a: 1 }, { getPrototypeOf() { throw new
Error("boom"); } });
  console.log(Object.create(proto));
  ```
and likewise with a Proxy whose `get` trap (or a getter reached through
a Proxy) throws for one property.
- The same happens with a lazily initialized property of the `Bun`
object whose initializer throws (fuzzer sample: `globalThis.Symbol`
replaced, then `Bun.inspect(Bun)`; the builtin behind `Bun.$` calls
`Symbol("cwd")`). Release builds print `Bun` with most of its properties
missing (72 of 115 on the shipped build); debug builds abort with
`ASSERTION FAILED: Unexpected exception observed` / `Symbol is not a
function. (In 'Symbol("cwd")' ...)` when the next lazy property is
built.
- Plain-JavaScript variant of the same leak: `console.log` of a module
namespace during an import cycle, when one export is still in its
temporal dead zone, throws `ReferenceError: Cannot access 'x' before
initialization` out of `console.log` (the stale exception is picked up
while the next export is formatted). `util.inspect` prints such an
export as `<uninitialized>`.
- Cause, in the slow path of `JSC__JSValue__forEachPropertyImpl`
(`src/jsc/bindings/bindings.cpp`):
- `object->getPropertySlot()` reports a throwing Proxy trap, a throwing
lazy initializer or a TDZ namespace export as "not found" with the
exception still pending, and the loop `continue`d before the
`CLEAR_IF_EXCEPTION` below it. The following lookups and formatting
callbacks then run with that exception pending (the dropped properties,
the rethrown `ReferenceError`, the debug assertion).
- When the walk moves to the next prototype,
`iterating->getPrototype(globalObject).getObject()` runs `getObject()`
on the empty `JSValue` that `getPrototype` returns when it threw (either
because of the stale exception above or because the `getPrototypeOf`
trap itself throws). The empty value passes `isCell()`, so this reads
the type byte of a null cell: the fault at address 5.
- `napi_get_all_property_names` (`src/jsc/bindings/napi.cpp`, descriptor
filter loop) has the same `getPrototype().getObject()` chain after an
unchecked `getOwnPropertyDescriptor`, so a Proxy trap throwing there
returned `napi_ok` with an exception pending in own-only mode and
segfaulted in include-prototypes mode.
- `defaultBunSQLObject` / `constructBunSQLObject`
(`src/jsc/bindings/BunObject.cpp`) had a debug-only block that handed a
sql module load failure to `reportUncaughtExceptionAtEventLoop` while
the exception was still pending on the VM, so `globalThis.Symbol = NaN;
Bun.sql` (and the fuzzer sample above, once the walk gets past `Bun.$`)
aborted debug builds with `ASSERTION FAILED: ... object->structure() ==
this` in `Structure::storedPrototype` instead of throwing.

### Fix

- `bindings.cpp`: clear the exception after `getPropertySlot` regardless
of its result, which is what the ordered variant
`JSC__JSValue__forEachPropertyOrdered` already does; read the next
prototype into a `JSValue`, clear the exception and stop the walk when
it is empty. (An earlier revision also held the prototype being walked
under an `EnsureStillAliveScope`; dropped, since the raw pointer is used
after every call into JS in the loop body and so is live across them
anyway.)
- Behaviour change to note: a property whose lookup throws is now left
out of the output instead of the whole `console.log` / `Bun.inspect`
call throwing or crashing. For TDZ namespace exports this differs from
`util.inspect`'s `<uninitialized>`; printing that marker would be a
formatter feature on top of this fix and is not attempted here.
- `napi.cpp`: check for an exception after `getOwnPropertyDescriptor`
and after `getPrototype` and return `napi_pending_exception`, which is
what Node returns for these cases.
- `BunObject.cpp`: drop the debug-only report. The exception is
propagated to the reader by the `RETURN_IF_EXCEPTION` right below it, so
debug builds now behave like release builds (`Bun.sql` throws).
- Why this is the right place: the formatter deliberately swallows
errors thrown by individual properties (getters, traps) and prints the
rest of the object; these two sites were the only ones in the walk that
acted on a "not found" result or a prototype value before clearing the
exception that produced it. Skipping just the property (or stopping at
just the prototype) whose lookup threw is the existing behaviour for
every other throw site in this function.
- Verification:
- `test/js/bun/util/inspect.test.js`, "Bun.inspect when a property
lookup throws" (5 spawned cases): a Proxy `get` trap, a getter behind a
Proxy, a `getPrototypeOf` trap, a throwing lazy `Bun` property, and a
two-file import cycle with a TDZ export. Without the fix (shipped
release build and an unfixed debug build) all five fail: the Proxy
children segfault / fail UBSan, the `Bun` child prints
`[false,false,...]` on release and aborts on debug, the cycle child
exits 1 with the `ReferenceError`; with it each prints everything except
the one property whose lookup threw.
- `test/js/bun/util/BunObject.test.ts`, "a lazy property whose builtin
fails to load throws from the read": `Bun.$` / `sql` / `SQL` /
`postgres` with `Symbol` broken throw a `TypeError` on two consecutive
reads. Aborts on an unfixed debug build (the `BunObject.cpp` hunk);
passes on release either way, as the removed block is debug-only. The
fixture builds `process.env` before breaking `Symbol` because the `$`
builder reads it, and building it on Windows reifies another `Bun`
property mid-lookup, which on a Windows debug build would hit the
separate `storedPrototype` assertion that #37001 fixes (verified on
Linux only).
- `test/napi/napi.test.ts`: `getOwnPropertyDescriptor` trap throwing in
own-only and include-prototypes mode (compared against Node), and a
`getPrototypeOf` trap that throws on the second call so the check after
`getPrototype` is the one that fires.
- Repros above and the tests also run clean under
`BUN_JSC_validateExceptionChecks=1`.

### Background

- `forEachPropertyImpl` is the property walk behind Bun's native
formatter. It collects the property names of the object and of up to
five prototypes, looks each one up through the original object with
`getPropertySlot`, and hands the value to a callback that formats it.
Errors thrown by individual properties are swallowed on purpose so that
one bad getter does not make `console.log` throw.
- A JSC exception is "pending" state on the VM, not C++ unwinding. A
function that throws returns a failure value (`false`, or the empty
`JSValue`) and leaves the exception on the VM; until something clears or
rethrows it, most JSC entry points return early as soon as they are
called, and debug builds assert when a function that did not throw is
observed returning with an exception pending. `CLEAR_IF_EXCEPTION` drops
the pending exception.
- The empty `JSValue` (`JSValue()`) is encoded as 0. `isCell()` is true
for it, so `getObject()` on it dereferences a null cell pointer rather
than returning null; callers have to test the value itself first.
- Lazy properties of the `Bun` object are entries in a static property
table whose value is produced by a builder the first time the property
is read (`PropertyCallback`). Some builders evaluate built-in JavaScript
modules (the shell for `Bun.$`, the sql module for `Bun.sql`), so they
can throw when that module fails to evaluate, and JSC reports that to
the reader as "property not found" plus a pending exception.

### Consolidated duplicates

Found repeatedly by the fuzzer (fingerprint `d678cafe50a2ad6e`). Earlier
round, folded in here in April: #29071 #28991 #28919 #28918 #28882
#28854 #28530 #28325. This round, closed in favour of this PR: #30099
#30245 #37160 #37175 #37213 #37256 #37428 #38700 #38921 #39363 #39365
#39380 #39412 #39413 (and #39411, closed earlier). The `BunObject.cpp`
hunk and the `BunObject.test.ts` test come from #30245 / #37428; the
same hunk is also part of #37001, which fixes the underlying
`storedPrototype` assertion in JSC.

Related fixes that are not part of this bug and stay open on their own:
#39382 (a custom inspect function when `node:util` fails to load),
#37202 (`util.isError` with a throwing `getPrototypeOf` trap), #37331
(`forEachPropertyOrdered` when the callback throws), #37001 (stale
structure in `JSObject::getPropertySlot`), #32263 (additional checks in
the same napi loop).

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

---

**no test proof** · iteration 11 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/bun/util/inspect.test.js test/napi/napi.test.ts

<!-- robobun:evidence:end -->

---------

Co-authored-by: robobun <robobun@users.noreply.github.com>
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.

1 participant