Skip to content

Renderer crash (use-after-free) when calling a removed subframe's process.activateUvLoop / process.getCPUUsage — regression from #52964 #56072

Backlog

Description

@sherlockfang04

Preflight Checklist

Electron Version

45.5.0

What operating system(s) are you using?

macOS

Operating System Version

macOS Tahoe 26.5.1

What arch are you using?

arm64 (including Apple Silicon)

Last Known Working Electron version

Not bisected. The code path was introduced by #52964, which (per the release notes) first shipped in v42.10.0 (#53042), v43.5.0 (#53041), v44.0.0 (#53040, from 44.0.0-beta.6) and v45.0.0-alpha.1. Releases before those (e.g. 42.9.x, 43.4.x) should not be affected, but I have not tested them.

Does the issue also appear in Chromium / Google Chrome?

No

Expected Behavior

Calling a reference to process.activateUvLoop (or process.getCPUUsage) that belongs to a subframe which has since been removed should do nothing (or throw / return undefined). The renderer should not crash.

Actual Behavior

The renderer crashes on every run:

FATAL:base/allocator/partition_alloc_support.cc:827] Detected dangling raw_ptr in unretained with id=0x…
render-process-gone { reason: 'crashed', exitCode: 5 }

This is PartitionAlloc's dangling-base::Unretained check firing: the C++ object the function is bound to has already been freed.

With that check disabled (--disable-features=PartitionAllocUnretainedDanglingPtr), the renderer goes on to use the freed memory and segfaults at 0xefefefefefefefff / 0xefefefefefefefef (PartitionAlloc's quarantine fill byte) inside electron::ElectronBindings::ActivateUVLoop / base::ProcessMetrics::GetCumulativeCPUUsage. Symbolized stacks are below.

Only nodeIntegrationInSubFrames: true and sandbox: false are required. It reproduces with the recommended contextIsolation: true and nodeIntegration: false, from a preload script.

Testcase Gist URL

https://gist.github.com/sherlockfang04/bb1fdc9f949d7eb7a16d242603a65432

Additional Information

Testcase

package.json

{
  "name": "electron-bindings-uaf",
  "main": "main.js"
}

main.js

const { app, BrowserWindow, protocol, net } = require('electron')
const path = require('node:path')
const { pathToFileURL } = require('node:url')

// Serve index.html and child.html from one origin so the top frame's preload
// can reach the child frame's window.
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { standard: true, secure: true } }
])

app.whenReady().then(() => {
  protocol.handle('app', (req) =>
    net.fetch(pathToFileURL(path.join(__dirname, new URL(req.url).pathname)).toString()))

  const win = new BrowserWindow({
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      nodeIntegrationInSubFrames: true,
      sandbox: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })
  win.webContents.on('render-process-gone', (_event, details) => {
    console.log('render-process-gone', details)
  })
  win.loadURL('app://poc/index.html')
})

preload.js

// Runs in every frame (nodeIntegrationInSubFrames). The top frame drives the repro.
if (process.isMainFrame) {
  window.addEventListener('DOMContentLoaded', () => {
    const iframe = document.createElement('iframe')
    iframe.src = 'child.html'
    iframe.onload = () => {
      // The subframe has its own Node.js environment and its own ElectronBindings.
      const activateUvLoop = iframe.contentWindow.process.activateUvLoop
      activateUvLoop() // fine: the child's ElectronBindings is alive
      iframe.remove() // frees the child's ElectronBindings
      activateUvLoop() // use-after-free -> renderer crash
    }
    document.body.appendChild(iframe)
  })
}

index.html

<!DOCTYPE html>
<html><body><h1>parent</h1></body></html>

child.html

<!DOCTYPE html>
<html><body>child</body></html>

Steps: npm install [email protected] && npx electron . → the renderer crashes as soon as the iframe loads. Deleting the last activateUvLoop() call (the control) makes the crash go away.

Notes on the testcase:

  • The child must be a real same-origin document. about:blank subframes never get a Node.js environment (ElectronRenderFrameObserver::ShouldNotifyClient), so they don't reproduce this. The custom app: scheme just makes both pages same-origin.
  • The same crash happens from page script with nodeIntegration: true, contextIsolation: false, nodeIntegrationInSubFrames: true, sandbox: false, using iframe.contentWindow.process.activateUvLoop.
  • process.getCPUUsage from the removed frame crashes the same way (it is bound to the freed metrics_).

Root cause

Links point at b5e057b on main.

  1. Every subframe (and every extra main frame in the process) now gets its own ElectronBindings. FrameEnvironment borrows the process-lifetime ElectronBindings only for the first main frame; every other frame creates own_electron_bindings, which is destroyed with the FrameEnvironment:
    electron_renderer_client.cc#L34-L65

  2. That per-frame object is bound into JS functions with base::Unretained. DidCreateScriptContext calls frame_env->electron_bindings->BindTo(...) (L199), which installs:

    // electron_bindings.cc#L81-L83
    dict.SetMethod("activateUvLoop",
                   base::BindRepeating(&ElectronBindings::ActivateUVLoop,
                                       base::Unretained(this)));
    // electron_bindings.cc#L58-L60 (via BindProcess(..., metrics_.get()))
    process->SetMethod("getCPUUsage",
                       base::BindRepeating(&ElectronBindings::GetCPUUsage,
                                           base::Unretained(metrics)));

    electron_bindings.cc#L58-L60, #L81-L83

  3. The JS functions outlive the frame. The callback lives in a cppgc-managed gin_helper::CallbackHolder (function_template.h#L65, #L439), so it stays alive for as long as any JS reference to the function exists, including one held by another frame.

  4. Removing the frame frees the object without invalidating the functions. WillReleaseScriptContext → FreeFrameEnvironment (L255, L294) drops the FrameEnvironment, whose destructor deletes own_electron_bindings (and with it metrics_, pending_next_ticks_ and call_next_tick_async_). env->set_can_call_into_js(false) doesn't help here, because the call goes from JS into C++.

  5. A later call runs on the freed object. ActivateUVLoop (L90-L97) reads and writes pending_next_ticks_ and calls uv_async_send() on the freed handle (whose loop has also been freed by ~NodeBindings). In the detector-off crash, std::ranges::contains loads the std::list sentinel's next pointer from the quarantined object (0xefefefefefefefef) and faults reading that node's value at +0x10 (0xefefefefefefefff).

The child's setImmediate and process.nextTick are wrapped to call process.activateUvLoop() (lib/common/init.ts#L14-L20), so holding on to a removed frame's setImmediate should reach the same freed object. I haven't tested that path.

Regression

Before #52964 every renderer environment used the process-lifetime ElectronBindings owned by ElectronRendererClient, so Unretained(this) was safe. #52964 did not touch electron_bindings.cc; the binding site changed by one line:

-  electron_bindings_->BindTo(env->isolate(), env->process_object());
+  frame_env->electron_bindings->BindTo(env->isolate(), env->process_object());

That made the receiver of the existing Unretained(this) per-frame, and so shorter-lived than the JS functions bound to it.

Stack traces

Electron 45.5.0, darwin-arm64, symbolized with the official electron-v45.5.0-darwin-arm64-symbols.zip (module 4C4C449555553144A1E4E0ADB297AB1C0). These come from the page-script variant, triggered from the iframe's onload; the preload testcase produces the same FATAL.

Default build (dangling-Unretained check):

EXC_BREAKPOINT
#0  logging::LogMessage::HandleFatal(...)
#1  logging::LogMessage::Flush()
#2  logging::LogMessageFatal::~LogMessageFatal()
#5  base::internal::Invoker<...>::Run                       raw_ptr.h:994
#6  gin_helper::Dispatcher<void (v8::Isolate*)>::DispatchToCallback(...)
#7-#10 <V8 builtins>
#11 v8::internal::Execution::Call(...)                      execution.cc:492
#12 v8::Function::Call(...)
#13 blink::V8ScriptRunner::CallFunction(...)
...
#21 blink::HTMLFrameOwnerElement::DispatchLoad()

(Frame #5's symbol name shows electron::Browser::* because the linker folded identical Invoker instantiations; the dispatcher signature void (v8::Isolate*) is activateUvLoop's.)

--disable-features=PartitionAllocUnretainedDanglingPtr, activateUvLoop:

EXC_BAD_ACCESS (SIGSEGV) KERN_INVALID_ADDRESS at 0xefefefefefefefff
#0  electron::ElectronBindings::ActivateUVLoop(v8::Isolate*)
#2  gin_helper::Dispatcher<void (v8::Isolate*)>::DispatchToCallback(...)
#7  v8::internal::Execution::Call(...)
#8  v8::Function::Call(...)
#9  blink::V8ScriptRunner::CallFunction(...)
...
#17 blink::HTMLFrameOwnerElement::DispatchLoad()

--disable-features=PartitionAllocUnretainedDanglingPtr, getCPUUsage:

EXC_BAD_ACCESS (SIGSEGV) KERN_INVALID_ADDRESS at 0xefefefefefefefef
#0  base::ProcessMetrics::GetCumulativeCPUUsage()           process_metrics_apple.mm:128
#1  electron::ElectronBindings::GetCPUUsage(base::ProcessMetrics*, v8::Isolate*)
#2  base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>::Run(...)
#5  gin_helper::Dispatcher<v8::Local<v8::Value> (v8::Isolate*)>::DispatchToCallback(...)
#10 v8::internal::Execution::Call(...)
...
#20 blink::HTMLFrameOwnerElement::DispatchLoad()

Suggested fix

Bind the per-frame methods through a WeakPtr, so that a stale function becomes a no-op (not compiled; a sketch):

// electron_bindings.h — last member
base::WeakPtrFactory<ElectronBindings> weak_factory_{this};

// electron_bindings.cc, in BindTo()
dict.SetMethod("activateUvLoop",
               base::BindRepeating(&ElectronBindings::ActivateUVLoop,
                                   weak_factory_.GetWeakPtr()));

// getCPUUsage returns a value, so it needs an explicit check rather than
// WeakPtr cancellation:
dict.SetMethod("getCPUUsage",
               base::BindRepeating(
                   [](base::WeakPtr<ElectronBindings> self,
                      v8::Isolate* isolate) -> v8::Local<v8::Value> {
                     if (!self)
                       return v8::Undefined(isolate);
                     return GetCPUUsage(self->metrics_.get(), isolate);
                   },
                   weak_factory_.GetWeakPtr()));

The static BindProcess(..., metrics) used by the sandboxed renderer client can keep Unretained, because that client's metrics_ lives for the whole process. A regression spec could follow the testcase above: keep a removed subframe's process.activateUvLoop and call it.

Related

Scope

  • Reproduced on Electron 45.5.0, macOS 26.5.1, arm64 only. Not yet tested on Windows or Linux, or on the 42/43/44 lines.
  • Only code that already has Node.js access (a preload script, or a page with nodeIntegration on) can get hold of the child frame's process object. With contextIsolation: true, web content in the main world can't reach it. I'm therefore filing this as a crash bug rather than a security report.

Activity

  1. added
    has-repro-gist
    on Nov 26, 2026
  2. moved this to 👀 Unsorted Items in 45-x-yon Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    45-x-ybug 🪲has-repro-gistplatform/macOS

    Type

    Projects

    • Status
      👀 Unsorted Items

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions