Skip to content

Native EventEmitter: hold the emitter during a method call (heap-use-after-free) - #48089

Open
robobun wants to merge 1 commit into
mainfrom
robobun/770a7873/emitter-keep-alive
Open

robobun wants to merge 1 commit into
mainfrom
robobun/770a7873/emitter-keep-alive

Conversation

@robobun

@robobun robobun commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • The EventEmitter methods of process accept any object as this. For a this that is not a native emitter, they use the native emitter in this._events. Nothing holds that emitter during the call (JSEventEmitterCustom.h:23).
  • The conversion of the event name runs user code, which can drop the last reference and collect. listenerCount, listeners, rawListeners, emit and removeAllListeners(name) then use a freed emitter.
  • Release ASAN build: AddressSanitizer: heap-use-after-free in WebCore::EventEmitter::listenerCount. A release build gives wrong answers, and removeAllListeners(name) ends in panic(main thread): abort() called.

Fix

Background

  • The native EventEmitter is the C++ class behind the prototype of process. The first on() call on another receiver builds an emitter and stores it as receiver._events.
  • EnsureStillAliveScope keeps a cell where the collector looks for roots, until the scope ends.
  • Considered a keep-alive in each method body: 12 sites, and a new method can miss it.

Downsides

  • Instructions per call of these methods: +3 to +5, also on process itself. process.listenerCount("x") 123 to 126, process.emit("x", 1) 224 to 228, process.on("x", f) 1,791 to 1,796.
  • Binary text: no change (140,315,585 bytes).
Notes

Repro. Run on main 7ca0042 and on bun 1.4.4, which has the same emitter sources. The emitter is reachable only through an accessor, and the calls run in a later task, so that no frame of the script holds it.

const proto = Object.getPrototypeOf(process);
const holder = {};
const state = { fired: 0 };
proto.on.call(holder, "x", () => state.fired++);
state.emitter = holder._events;
delete holder._events;
setImmediate(() => {
  const receiver = { get _events() { return state.emitter; } };
  const count = proto.listenerCount.call(receiver, {
    toString() {
      state.emitter = undefined;
      Bun.gc(true);
      return "x";
    },
  });
  console.log(count); // 1
});
build of main listenerCount emit removeAllListeners(name)
release 0 false, the listener does not run panic(main thread): abort() called, exit code 134
release ASAN with Malloc=1 heap-use-after-free, READ of size 8 heap-use-after-free heap-use-after-free, WRITE of size 1
with this change 1 true, the listener runs returns this

The ASAN report for an emitter that a plain property holds (process.on.call(o, "x", f), then process.listenerCount.call(o, { toString() { delete o._events; Bun.gc(true); return "x" } })):

ERROR: AddressSanitizer: heap-use-after-free
READ of size 8
    #3 WebCore::IdentifierEventListenerMap::find(JSC::Identifier const&) IdentifierEventListenerMap.cpp:119
    #4 WebCore::EventEmitter::listenerCount(JSC::Identifier const&) EventEmitter.cpp:163
    #5 WebCore::jsEventEmitterPrototypeFunction_listenerCountBody JSEventEmitter.cpp:479
    #6 WebCore::IDLOperation<WebCore::JSEventEmitter>::call<...>

Why the debug build does not show it. A method body keeps only castedThis->wrapped() across the conversion. An optimized build drops the pointer to the wrapper cell, the collector frees the cell, and its destructor releases the emitter. A debug build keeps every local in a stack slot for the whole call, so the collector still finds the cell. The 5 new tests pass on a debug build of main (5 of 5) and fail on a release build of main (0 of 5) and on a release ASAN build of main (0 of 5). With this change they pass on the three builds.

Cost per call. Instructions inside the host function, from its first instruction to its return, on release builds of main and of this branch. The count comes from ptrace(PTRACE_SINGLESTEP), because perf and valgrind are not available on the machine. Each row is calls 40 to 49 of a loop, and the count is the same for the 10 calls.

call main this PR
process.listenerCount("x") 123 126
process.emit("x", 1), no listener 224 228
process.emit("x", 1), one listener 612 615
process.on("x", f) 1,791 1,796
listenerCount.call(o, "x"), o has an emitter in _events 319 322
emit("x", 1) on Object.create(process), one listener 780 783

size bun-profile gives 140,315,585 bytes of text before and after.

Relation to other changes.

Suites run. test/js/node/events/event-emitter.test.ts on the debug build (102 pass, also with BUN_JSC_validateExceptionChecks=1), the release build (102 pass) and the release ASAN build (102 pass). On the debug build also 28 files of test/js/node/test/parallel/ (test-event-emitter-*.js, test-process-emit*.js).

The emitter of a receiver that is not a native emitter can have
this._events as its only reference. The conversion of the event name
runs user code, which can drop that reference and collect. The method
then used a freed emitter.
@robobun

robobun commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:23 AM PT - Nov 7th, 2026

❌ @robobun, your commit 1a747af has 38 failures in Build #138221 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 48089

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

bun-48089 --bun

@robobun

robobun commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduced on main 7ca0042 and on bun 1.4.4 (linux x64) with the script in the description: an emitter that is reachable only through an accessor _events, and an event name whose toString() drops that reference and collects.

  • Release build: listenerCount returns 0 for one listener, emit returns false, and removeAllListeners(name) ends in panic(main thread): abort() called.
  • Release ASAN build with Malloc=1: AddressSanitizer: heap-use-after-free in WebCore::EventEmitter::listenerCount.

With this change the answers are 1, true and this. The 5 new tests fail on release and release ASAN builds of main. They pass on the debug, release and release ASAN builds of this branch.

The tests also pass on a debug build of main. A debug build keeps the pointer to the emitter in a stack slot for the whole call, so the defect shows only in an optimized build.

CI. Build 138221 finished red from 28 test files: 27 in test/aot/ and test/bundler/compile-aot-size.test.ts. The same files fail in the final builds of recently merged pull requests, and this change touches none of them. No lane reports a failure in test/js/node/events/event-emitter.test.ts. The x64 ASAN lane ran it with 102 pass and 0 fail.

@coderabbitai

coderabbitai Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

IDLOperation<JSEventEmitter>::call now keeps the emitter alive while it invokes an operation. A regression test covers five native methods during event-name conversion that clears stored references and forces garbage collection.

Changes

Native EventEmitter lifetime

Layer / File(s) Summary
Keep the emitter alive during calls
src/jsc/bindings/webcore/JSEventEmitterCustom.h, test/js/node/events/event-emitter.test.ts
The operation keeps thisObject alive during the call. A subprocess test checks listenerCount, listeners, rawListeners, emit, and removeAllListeners while event-name conversion clears a stored reference and forces garbage collection.

Suggested reviewers: dylan-conway

Merge Risk: Minimal · up to 1a747

The change protects native emitters from collection during method calls, with regression coverage for the shared safeguard. No actionable merge-blocking issue remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title clearly describes the EventEmitter lifetime fix.
Description check Passed The description explains the change and its verification. It uses different headings from the template but includes the required information.
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.
  • 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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7ca0042 and 1a747af.

Files selected for processing: 2

  • src/jsc/bindings/webcore/JSEventEmitterCustom.h
  • test/js/node/events/event-emitter.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this 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.

LGTM — a two-line keep-alive in the one shared trampoline, with a subprocess regression test that pins the exact output.

What was reviewed:

  • Confirmed jsEventEmitterCastFast is the only native site that resolves this._events, and all 15 prototype host functions in JSEventEmitter.cpp go through IDLOperation<JSEventEmitter>::call, so rooting thisObject there covers removeListener/off and the other methods not in the test matrix.
  • Checked the method bodies: each keeps only castedThis->wrapped() across toPropertyKey/listener conversion, so rooting the wrapper cell (whose destructor releases the impl) is sufficient; EnsureStillAliveScope is the same idiom these bindings already use for arguments.
  • Test: bunExe/bunEnv, await using, stdout/stderr/exit drained concurrently, exact toEqual on the combined result; the known limitation that debug lanes pass with or without the fix is acceptable since release lanes fail on the unfixed build.
Extended reasoning...

The diff adds JSC::EnsureStillAliveScope keepEmitterAlive(thisObject) in src/jsc/bindings/webcore/JSEventEmitterCustom.h before the operation call, plus a five-case test.concurrent.each in test/js/node/events/event-emitter.test.ts that spawns bun -e and asserts the emitter survives Bun.gc(true) triggered from the event-name toString. It touches no security-sensitive surface (no auth, crypto, or input parsing); it is a GC-rooting fix for a native EventEmitter wrapper that was reachable only via a user getter. Approve was decided by the change being tiny, placed at the single owning layer that every method shares, using an established JSC idiom, with no CODEOWNER on either file, no third-party objections, and the bug hunt exiting on dry_streak.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants