Skip to content

Run the process.env and require.extensions setters on every assignment - #45282

Open
dylan-conway wants to merge 2 commits into
mainfrom
claude/uncacheable-put-hooks
Open

dylan-conway wants to merge 2 commits into
mainfrom
claude/uncacheable-put-hooks

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Assigning to process.env.X or require.extensions[".js"] from the same line of code more than a couple of times stopped doing anything beyond storing the value.

Both objects override put to do work on assignment: process.env converts the value to a string, and require.extensions tells the module loader about the new handler. Both then passed the caller's PutPropertySlot on to JSObject::put, which marks the store as cacheable. The interpreter and baseline inline caches then wrote later values straight into the object without calling put.

const t = [];
for (let i = 0; i < 4; i++) { process.env.ZZZ = i; t.push(typeof process.env.ZZZ); }
console.log(t.join(" "));
// 1.4.3:   string string number number
// this PR: string string string string
  • require.extensions[".js"] = fn in a loop kept using the first fn.
  • A value whose toString() adds, deletes or first reads another variable changed the structure of process.env during the store. The caching code assumes the structure it saw before the store, and the process aborted:
process.env.A = process.env.B = "x";
process.env.A = { toString() { delete process.env.B; return "y"; } };

Both hooks now call slot.disableCaching(), as JSFunction::put does for prototype. Reads stay cacheable.

Integer keys had the same symptom by another route: process.env[0] = i stored the raw number from the second store on. JavaScriptCore overwrites an element that is in an object's element vector without calling putByIndex. process.env now keeps such values in sparse storage, where every indexed store calls it.

Not covered: the values are still plain data properties, so once a function is hot enough for the DFG and the compiler knows the object's structure, it can turn the store into a direct write. That case behaves as it does on main.

How did you verify your code works?

Three new tests: two in test/js/node/process/process.test.js, one in test/js/node/module/require-extensions.test.ts. The first also covers integer keys, one new and one that comes from the environment. All three fail with USE_SYSTEM_BUN=1 bun test (1.4.3). With bun bd test, require-extensions.test.ts passes and so do the process.env tests in process.test.js. The scripts above print the same as Node on the debug build.

@robobun

robobun commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 5:26 PM PT - Oct 14th, 2026

✅ @dylan-conway, your commit c1324425aca3b3774d2a328ad9a415507b871477 passed in Build #125625! 🎉


🧪   To try this PR locally:

bunx bun-pr 45282

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

bun-45282 --bun

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: oven-sh/bun/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: ccdbf0d2-3041-4432-b80e-22931a112a54
📥 Commits

Reviewing files that changed from the base of the PR and between b0cc488 and c132442.

📒 Files selected for processing: 2
  • src/jsc/bindings/JSEnvironmentVariableMap.cpp
  • test/js/node/process/process.test.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Walkthrough

Property writes in JavaScript extension and environment-variable maps now disable inline caching. Numeric environment properties use dictionary indexing. Tests cover successive require.extensions assignments and process.env coercion and reentrant value conversion.

Changes

Property Write Cache Handling

Layer / File(s) Summary
Update property write handling
src/jsc/bindings/JSCommonJSExtensions.cpp, src/jsc/bindings/JSEnvironmentVariableMap.cpp
Both write paths disable property caching. Indexed environment writes use dictionary indexing after storing the coerced value. Initial numeric environment properties also use dictionary indexing.
Verify repeated property writes
test/js/node/module/require-extensions.test.ts, test/js/node/process/process.test.js
Tests check successive loader assignments and process.env value coercion, indexed writes, and reentrant conversion behavior.

Suggested reviewers: jarred-sumner

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to c1324

The known optimized-store limitation remains unchanged; this change adds safeguards for other assignment paths. No new merge-blocking impact is established.

Pre-merge checks: Passed 4
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description includes both required sections. It clearly explains the caching issue, implementation changes, limitations, and verification results.
Title check Passed The title clearly and concisely describes the main change: ensuring the process.env and require.extensions setters run on every assignment.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the placement of slot.disableCaching() after the inherited-receiver early return in JSEnvironmentVariableMap::put — a store whose receiver is a child of process.env intentionally lands the raw value on the child with no process side effects, so letting that path stay cacheable does not skip anything.

Extended reasoning...

The change adds slot.disableCaching() to the custom put() overrides of process.env and require.extensions plus three regression tests; it touches no auth, crypto, or data-exposure surface. Inline findings were posted, so this note only records the one adjacent concern that was examined and ruled out.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 src/jsc/bindings/JSEnvironmentVariableMap.cpp — pre-existing: a script that writes a numeric key such as process.env[0] = i more than once still gets the raw value stored (typeof "number") from the second write on, so the string coercion the PR restores for named keys is not restored for index keys. JSEnvironmentVariableMap::putByIndex at JSEnvironmentVariableMap.cpp:225 is only reached while the object has no indexed storage; the first write creates contiguous storage via Base::putByIndex, and later indexed stores take JSC's setIndexQuickly path and never call putByIndex. Fix: make every indexed write re-enter putByIndex (e.g. add InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero to StructureFlags at JSEnvironmentVariableMap.h:21, as JSSharedEnvMap already does at JSEnvironmentVariableMap.cpp:609). [also at: src/jsc/bindings/JSEnvironmentVariableMap.cpp:234 - pre-existing: a repeated integer-keyed store such as process.env[0] = 1 after an earlier process.env[0] = "a" keeps the raw number, so typeof process.env[0] is "number" and DEP0104 never fires.]

    Why this was flagged

    The trigger is any script that assigns to an integer key of process.env twice, e.g. process.env[0] = 1; process.env[0] = 2; typeof process.env[0], entering through op_put_by_val with an int32 subscript. The first store reaches JSEnvironmentVariableMap::putByIndex (JSEnvironmentVariableMap.cpp:225-235), coerces to a string, and Base::putByIndex creates contiguous indexed storage on the object because StructureFlags at JSEnvironmentVariableMap.h:21 carries only OverridesPut and no indexed-intercept flag. The second store is handled by JSC's putByVal slow path, which calls trySetIndexQuickly/canSetIndexQuickly on the now-contiguous butterfly and writes the raw JSValue, so putByIndex and its coerceEnvValue are skipped and the stored value is the number 2. The base branch behaves the same way; this PR adds slot.disableCaching() only in put() at JSEnvironmentVariableMap.cpp:185, which does not affect indexed stores because putByIndex takes no PutPropertySlot. The sibling JSSharedEnvMap at JSEnvironmentVariableMap.cpp:607-613 sets InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero and does not have this gap.

    Verification: pre-existing. JSEnvironmentVariableMap::StructureFlags (JSEnvironmentVariableMap.h:21) has no InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero, so Base::putByIndex at line 234 gives the object contiguous storage after the first store. Later int32 put_by_val stores take trySetIndexQuickly, never putByIndex (lines 225-235), so typeof process.env[0] is "number". slot.disableCaching() at line 185 only affects named-key put.

Comment thread test/js/node/process/process.test.js Resolved
Comment on lines 189 to 193
if (!isAllowedToMutateExtensions(globalObject)) return true;
// An inline cache would store the next value without calling put().
slot.disableCaching();
onAssign(defaultGlobalObject(globalObject), propertyName, value);
return Base::put(cell, globalObject, propertyName, value, slot);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: Assigning an extension on an object that merely inherits from require.extensions re-registers the module loader for the whole VM, even though the property lands on the child. src/jsc/bindings/JSCommonJSExtensions.cpp:192 calls onAssign before checking slot.thisValue() against cell, so a store with an inherited receiver still reaches NodeModuleModule__onRequireExtensionModify. The sibling override JSEnvironmentVariableMap::put at JSEnvironmentVariableMap.cpp:174 guards exactly this case and the PR touched this line without adding the same guard. Fix: when slot.thisValue() != cell, skip onAssign and only forward to Base::put so the write stays on the receiver, matching the process.env override.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A tool does const ext = Object.create(require.extensions); ext['.js'] = fn (or sets through a Proxy or Reflect.set with a different receiver). JSC walks the prototype chain and calls JSCommonJSExtensions::put with cell = require.extensions and slot.thisValue() = the child. JSCommonJSExtensions.cpp:192 runs onAssign unconditionally, which calls NodeModuleModule__onRequireExtensionModify at :172 and swaps the VM-wide loader for '.js'; Base::put at :193 then defines the property on the child, so require.extensions['.js'] still shows the original function while the loader actually used is fn. Node only mutates Module._extensions when the own property changes. The base branch behaves the same, but this PR edits the same four-line function and the repository instructions require fixing the class across sibling overrides; the process.env twin already has the receiver guard at JSEnvironmentVariableMap.cpp:174-182. Seven finders raised it. Remedy: return Base::put without onAssign when the receiver is not the extensions object itself.

Verification: pre-existing (the base already has the same route). Trigger: any [[Set]] whose receiver is not require.extensions itself but whose lookup reaches it as a prototype. In src/jsc/bindings/JSCommonJSExtensions.cpp:187-194, put has no receiver check: line 192 onAssign(...) runs unconditionally. isAllowedToMutateExtensions (line 54) only inspects the calling stack frame, so it is not a guard for this path.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed: Object.create(require.extensions)[".js"] = fn changes the loader on 1.4.3 and does not in Node. It is a different bug from the one here (which stores reach put(), not what put() does with a foreign receiver), so I am leaving it out of this PR.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the rewritten putByIndex in src/jsc/bindings/JSEnvironmentVariableMap.cpp (lines 232-238): both coerceEnvValue and Base::putByIndex are exception-checked before enterDictionaryIndexingMode, which cannot throw, so the scope is handled on every path. The slot.disableCaching() placement in put is also after the inherited-receiver branch, whose structure read happens only on a path that returns before any user toString() runs, so the mutating-toString test cannot reach a stale structure read there.

Extended reasoning...

The change touches two custom-put exotic objects (process.env and require.extensions) in src/jsc/bindings plus their tests; no security-sensitive surface. The new commit since the prior review adds the putByIndex/enterDictionaryIndexingMode handling, whose exception-scope rewrite and coercion ordering were examined and found correct; the two inline findings (a pre-existing string-then-integer key path and a test that does not prove the inherited-key line is exercised) are what remain.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 src/jsc/bindings/JSEnvironmentVariableMap.cpp — pre-existing: a script that first writes an integer-like key through a string, e.g. process.env["0"] = "a", and later writes it with a number, e.g. process.env[0] = 5, still ends up with the raw number stored, as on the base branch. JSEnvironmentVariableMap::put at JSEnvironmentVariableMap.cpp:222 hands index-shaped names to Base::put, whose parseIndex branch calls JSObject::putByIndex directly, so the override at :225 and its enterDictionaryIndexingMode at :237 never run and the value lands in the element vector. Fix: keep every integer-keyed store out of the vector on every route (put, defineOwnProperty, putByIndex), e.g. have put dispatch parseIndex names to JSEnvironmentVariableMap::putByIndex.

    Why this was flagged

    Condition: the first store to an integer-like key arrives as a string key (process.env["0"] = "a", or Object.defineProperty(process.env, "0", ...) via defineOwnProperty at JSEnvironmentVariableMap.cpp:264), which JSC passes to put() with an Identifier rather than to putByIndex(). JSEnvironmentVariableMap::put coerces at :198 and then calls Base::put at :222; JSObject::put's parseIndex branch calls the static JSObject::putByIndex, not the method-table override, so JSEnvironmentVariableMap::putByIndex at :225 and the enterDictionaryIndexingMode call at :237 are skipped and the string is written into the object's indexed vector. A later integer-keyed store, process.env[0] = 5, hits trySetIndexQuickly on that vector and stores the raw number: typeof process.env[0] is "number", and the native env / coercion never run. The base branch behaves the same, so this is pre-existing; the PR's fix does not reach this route, and the new test only exercises integer keys so it cannot catch it.

    Verification: pre-existing — the base branch fails identically by the same route; the PR fixes the putByIndex() route to integer keys but not the put()-with-index-like-name route. JSEnvironmentVariableMap::put ends at src/jsc/bindings/JSEnvironmentVariableMap.cpp:222 with Base::put, whose parseIndex branch calls the static JSObject::putByIndex, not methodTable()->putByIndex. So the override at :225 and its enterDictionaryIndexingMode(vm) at :237 never run.

Comment thread test/js/node/process/process.test.js Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants