# 《Electron 45.2.3 内核解剖》第 6 章 Node.js 集成:两个事件循环的婚姻

1 阅读1小时+

《Electron 45.2.3 内核解剖》第 6 章 Node.js 集成:两个事件循环的婚姻

主线问题:为什么 Electron 不能直接把 Node 塞进浏览器进程?

这个问题有一个具体的可操作版本:Chromium 主线程跑着自己的消息循环(base::MessagePump),Node 跑着自己的事件循环(libuv)。这两个循环都想独占"阻塞等待 IO"这个动作。一个线程只能阻塞一次。谁来阻塞?答案决定了 Electron 的整个 Node 集成架构。

本章的源码基础是五个文件:

文件行数角色
node_bindings.cc1,261NodeBindings 全部实现
node_bindings.h299类定义、UvHandle<T> RAII
node_bindings_linux.cc42PollEvents() 的 epoll 版
node_bindings_mac.cc35PollEvents() 的 poll 版
node_bindings_win.cc58PollEvents() 的 IOCP 版
microtasks_runner.cc32微任务检查点的仲裁者

外加渲染进程侧的 electron_renderer_client.cc(约 800 行)、web_worker_observer.cc(约 330 行)、utility 进程侧的 node_service.cc(312 行),以及 JS 侧的 lib/renderer/init.ts(180 行)。

第 5 章留下了三条线索:EmbedThreadRunner 的三步握手、node::MultiIsolatePlatform::RegisterIsolate、kExplicit/kScoped 微任务策略。本章把它们全部收拢,并补上第 4 章那个 uv_loop_interrupt 补丁的完整因果链。


6.0 三个观察,一个问题

先做三个实验。全部可以在读完本章前完成,读完本章后你应该能解释每一个。

观察一:主进程里 setTimeout 的回调由谁触发?

// main.js
console.log('tick 0');
setTimeout(() => console.log('tick 1'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('microtask'));

输出是 tick 0、microtask、immediate、tick 1(具体顺序取决于执行时机,后面 6.8 节会精确到"哪个阶段必然先于哪个")。关键问题是:这个进程的主线程跑的是 Chromium 的 MessagePumpDefault,不是 uv_run。但 setTimeout 是 uv 定时器,setImmediate 是 uv 的 check handle。如果主线程在跑 Chromium 的循环,谁在跑 uv 的循环?

观察二:渲染进程开了 nodeIntegration 之后,页面里的 setTimeout 和主进程的 setTimeout 是同一个循环吗?

不是。渲染进程有自己的 uv loop(甚至可能有多个——每个 iframe 一个,6.9 节),主进程也有自己的。它们之间没有任何共享。但两者用同一套代码(NodeBindings + embed 线程)驱动。

观察三:把一个 fs.readFile 挂起,然后主进程什么事都不做,文件读完后回调为什么不丢?

主线程阻塞在 Chromium 的 WaitForWork(MessagePumpDefault::Run 里的 WaitForMessage)上,它不监听 uv 的任何 fd。文件完成事件到达时,必然有"另一个东西"在监听。这个"另一个东西"就是 embed 线程——本章的主角。

三个观察合起来就是本章的地图:同一个线程上的两个循环,靠一个专职信使线程缝合。


6.1 架构总览:一个线程,两个循环,一个信使

先画出全图,再逐块拆。

┌────────────────────── 主线程(UI 线程)──────────────────────┐
│                                                              │
│   Chromium MessagePump          libuv loop (uv_loop_t)       │
│   ┌──────────────────┐           ┌──────────────────┐        │
│   │ base::RunLoop    │           │ timers / polls / │        │
│   │  PostTask 队列   │  UvRunOnce │ checks / idle   │        │
│   │  delayed tasks  │◄──────────►│ (handle 队列)    │        │
│   └──────────────────┘  每tick泵一次 └────────▲─────┘        │
│           ▲                                │               │
│           │ PostTask(UvRunOnce)            │ uv_async_send  │
└───────────┼────────────────────────────────┼───────────────┘
			│                                │
┌───────────┴──────── embed 线程 ────────────┴───────────────┐
│                                                            │
│   while (true) {                                           │
│     uv_sem_wait(embed_sem_);   ← 等主线程处理完             │
│     PollEvents();               ← 阻塞 epoll_wait/IOCP     │
│     WakeupMainThread();         ← PostTask 回主线程        │
│   }                                                        │
│                                                            │
└────────────────────────────────────────────────────────────┘

三个角色,各自的职责边界:

主线程:唯一能碰 V8 isolate 的线程(对 browser 进程而言,isolate 由 v8::Locker 锁定在主线程——见 javascript_environment.cc:207 里 locker_{std::in_place, isolate()})。它跑 Chromium 的消息循环,处理所有 UI、mojo、IPC、定时器。它从不阻塞在 uv 的 fd 上——只在每次被 embed 线程叫醒时,用 uv_run(loop, UV_RUN_NOWAIT) 把"已经就绪的"事件一次性处理掉。

uv loop:一个纯数据结构(uv_loop_t),不是线程。它活在主线程的堆上,handle/请求队列谁都可以往里塞(JS 侧 setTimeout 走 uv_timer_start 改的就是它)。改它的线程和跑它的线程都是主线程;监听它底层 fd 的线程是 embed 线程。

embed 线程:专职信使。它不碰 V8、不碰 JS、不碰 Chromium 对象。它只做一件事:PollEvents() ——阻塞等待 uv 的 backend fd(Linux 上是 epoll fd,Windows 上是 IOCP 句柄,macOS 上是 kqueue fd),有事件就通知主线程。

这个设计的本质是一个生产者-消费者 + 跨线程唤醒的结构:

  • uv loop 的"就绪事件"是可预测的——内核告诉你(epoll/kqueue/IOCP)"这个 fd 有事了"。
  • 但主线程不能阻塞等内核,因为它的阻塞点必须留给 Chromium 的 pump(Chromium 的 delayed task、mojo 的 incoming queue 都靠 pump 分发)。
  • 所以等待被外包给 embed 线程,主线程用 PostTask 被"叫醒"来消费。

为什么不用两个线程各跑一个循环? 因为 V8 isolate 不是线程安全的。JS 代码、GC、微任务都必须在锁 isolate 的那个线程执行。uv 回调要执行 JS(setTimeout(fn) 的 fn 是 JS 函数),所以 uv 的执行必须回到主线程。能外包的只有等待。这就是整章的立论。


6.2 NodeBindings:构造函数里的两行

NodeBindings 是这个架构的载体。四个进程形态共用一个类,差异只在 BrowserEnvironment 枚举和 PollEvents() 的平台实现。

node_bindings.cc:546

NodeBindings::NodeBindings(BrowserEnvironment browser_env, uv_loop_t* loop)
	: browser_env_{browser_env},
	uv_loop_{loop ? loop : &owned_loop_.emplace()} {
	if (owned_loop_)
	CHECK_EQ(0, uv_loop_init(uv_loop_));

	// Interrupt embed polling when a handle is started.
	uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE);
}

构造函数只有三个动作,每个都有讲头。

动作一:loop ? loop : &owned_loop_.emplace()。

两种 loop 来源:

  • 借用:browser 进程传 uv_default_loop()(ElectronBrowserMainParts 里创建 node_bindings_ 时);渲染进程主 frame 也是 uv_default_loop()(electron_renderer_client.cc:69:NodeBindings::Create(kRenderer, uv_default_loop()))。
  • 自有:传 nullptr 时,owned_loop_.emplace() 在 optional 里原地构造一个 uv_loop_t,然后 uv_loop_init 初始化。谁会传 nullptr?iframe 的 FrameEnvironment(6.9 节)、worker 的 WebWorkerObserver(6.11 节)——每个 secondary 环境一个独立 loop。

成员声明顺序(node_bindings.h:241-247)本身就是文档:

	// Engaged when this instance created its loop instead of integrating one.
	std::optional<uv_loop_t> owned_loop_;

	// depends-on: owned_loop_
	const raw_ptr<uv_loop_t> uv_loop_;

depends-on: owned_loop_ 是给 Chromium 静态分析工具看的注解——uv_loop_ 可能指向 owned_loop_,析构必须先于它销毁。析构函数(node_bindings.cc:559-571)确实遵守:

NodeBindings::~NodeBindings() {
	StopPolling();

	if (embed_thread_prepared_) {
	uv_sem_destroy(&embed_sem_);
	dummy_uv_handle_.reset();
	}

	if (owned_loop_)
	stop_and_close_uv_loop(uv_loop_);

	if (initialized_node_per_process_)
	TearDownOncePerProcess();
}

顺序:停信使线程 → 销毁信号量与 dummy handle → 关自有 loop → 兜底 TearDown Node 进程级状态。stop_and_close_uv_loop 不是简单的 uv_loop_close——它先 uv_run(UV_RUN_DEFAULT) 排干残留 handle 再 close(uv 的规矩:有活跃 handle 时 uv_loop_close 返回 UV_EBUSY)。

动作二:uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE)。

这是 Electron 给 libuv 加的自定义选项(第 4 章的 feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch)。一句话版本:当任何线程启动/停止/喂食一个 IO watcher 时,把正在别的线程里阻塞等待的 poller 叫醒。为什么必须有它,6.6 节用补丁原文展开——这里先记住:没有它,"主线程刚算好的 poll 超时"和"新加进来的定时器"会错过彼此,定时器要等到下一个不相干的事件才被处理,setTimeout(fn, 10) 在系统空闲时会变成 setTimeout(fn, ~500)。

动作三:CHECK_EQ(0, uv_loop_init(...))。

只对自有 loop。uv_loop_init 失败基本只可能因为内存耗尽或 fd 用尽(Linux 上 epoll_create 失败),CHECK 让它当场死而不是带病运行。

6.2.1 UvHandle<T>:一个 80 行的 RAII 模板

node_bindings.h:40-120 的 UvHandle<T> 是读 Electron 代码时绕不开的基建。它解决 uv 的一个 API 设计问题,uv 文档原文(被 Electron 抄进了注释):

"uv_close() MUST be called on each handle before memory is released. Moreover, the memory can only be released in close_cb or after it has returned."

也就是说:handle 的 uv_close 是异步的(要等 loop 下一轮跑 close 回调),你不能 close 完立刻 delete。手写这套逻辑极易出 use-after-free。UvHandle<T> 用两个技巧封装:

node_bindings.h:70-77

	UvHandle() : t_{new T{}} {}
	~UvHandle() { reset(); }
	...
	void reset() {
	auto* h = handle();
	if (h != nullptr) {
	if (uv_handle_get_type(h) == UV_UNKNOWN_HANDLE) {
		// Never initialized, so it is on no loop and there is nothing to
		// close, e.g. NodeBindings::dummy_uv_handle_ when a frame goes away
		// before PrepareEmbedThread() runs.
		delete t_;
	} else {
		DCHECK_EQ(0, uv_is_closing(h));
		uv_close(h, OnClosed);
	}
	t_ = nullptr;
	}
	}
	private:
	static void OnClosed(uv_handle_t* handle) {
	delete reinterpret_cast<T*>(handle);
	}

技巧一:值初始化探活。 new T{} 是值初始化——uv_XXX_t 的第一个字段是 UV_UNKNOWN_HANDLE 类型标记(uv 要求 uv_XXX_init 之前 handle 必须是值初始化的)。所以 reset() 能用 uv_handle_get_type(h) == UV_UNKNOWN_HANDLE 区分"从未 init,直接 delete"和"已 init,走 uv_close + 回调里 delete"。

技巧二:delete 发生在 close 回调里。 OnClosed 是 uv_close 的回调,它执行时 handle 已经从 loop 摘除,此时 delete 是安全的。用户(NodeBindings)只需要 dummy_uv_handle_.reset(),剩下交给模板。

注释里那个场景值得记下:NodeBindings::dummy_uv_handle_ when a frame goes away before PrepareEmbedThread() runs——iframe 的 FrameEnvironment 构造时会建 NodeBindings,但 embed 线程要等 DidCreateScriptContext 尾部的 PostTask 才 PrepareEmbedThread()。如果这中间 frame 被销毁,析构函数碰到的是一个"值初始化过但从未 uv_async_init"的 handle。没有这个分支,uv_close 会对一个不在 loop 上的 handle 调用——未定义行为。

一个 80 行的模板,防住三种死法。这是 Electron C++ 代码里"uv 是 C API,但用法可以是 C++"的代表。


6.3 embed 线程:EmbedThreadRunner 的十行

整个婚姻的核心是 node_bindings.cc:1195-1213 这十行:

// static
void NodeBindings::EmbedThreadRunner(void* arg) {
	auto* self = static_cast<NodeBindings*>(arg);

	while (true) {
	// Wait for the main loop to deal with events.
	uv_sem_wait(&self->embed_sem_);
	if (self->embed_closed_)
	break;

	// Wait for something to happen in uv loop.
	// Note that the PollEvents() is implemented by derived classes, so when
	// this class is being destructed the PollEvents() would not be available
	// anymore. Because of it we must make sure we only invoke PollEvents()
	// when this class is alive.
	self->PollEvents();
	if (self->embed_closed_)
	break;

	// Deal with event in main thread.
	self->WakeupMainThread();
	}
}

三步:等许可 → 阻塞等 IO → 叫醒主线程。然后回到第一步。

这十行里有三个精妙处,全部藏在注释和缺失的代码里。

精妙一:uv_sem_wait 是协议的开始,不是等待的开始。

直觉上"embed 线程在等 IO"。但看循环结构:uv_sem_wait 在 PollEvents 之前。所以任意时刻,embed 线程要么在 PollEvents 里阻塞(等 IO),要么在 uv_sem_wait 上阻塞(等主线程)。

主线程什么时候 uv_sem_post?在 UvRunOnce 的最后一行(6.4 节)。所以协议是:

主线程                          embed 线程
	│                                │
	│ ◄── PostTask(UvRunOnce) ────── │ (刚被 PollEvents 唤醒)
	│                                │
	│ uv_run(NOWAIT) 处理就绪事件    │ (阻塞在 uv_sem_wait)
	│                                │
	│ uv_sem_post(embed_sem_) ─────► │ (醒来)
	│                                │ PollEvents(): 重新读
	│                                │ uv_backend_timeout, 阻塞等 IO
	│ ... Chromium pump 继续跑 ...    │
	│                                │
	│            (IO 到了)           │ PollEvents 返回
	│                                │ WakeupMainThread():
	│ ◄── PostTask(UvRunOnce) ────── │
	│                                │ (回到 uv_sem_wait)
	│ uv_run(NOWAIT) ...             │

每一轮 UvRunOnce 恰好对应一次 sem_post 和一次 PollEvents。 这个"one post per UvRunOnce"的协议在 StopPolling 的注释里被点名(6.7 节)。为什么这么设计,而不是让 embed 线程自由地连续 poll?两个原因:

  1. PollEvents 读的 uv_backend_timeout() 是主线程的 loop 数据(下一轮 timer 什么时候到、有没有 pending 的 handle 队列)。它必须在主线程处理完一批事件之后重读才准确。协议保证了读的时机。
  2. PostTask 会被合并吗?不会,但会被丢弃吗?也不会。 每次唤醒恰好一个 PostTask,主线程的 pump 队列里最多积压一个 UvRunOnce,不会堆积。

精妙二:两次检查 embed_closed_。

embed_closed_ 是一个普通 bool(不是 atomic——注释没提,但两线程的读写顺序被 semaphore 的 happens-before 关系约束:StopPolling 先 embed_closed_ = true 再 uv_sem_post,embed 线程 uv_sem_wait 返回后才读它)。

检查了两次,分别在两个阻塞点之后:

  • uv_sem_wait 之后:主线程 StopPolling 时,先 post 让它退出等锁。
  • PollEvents() 之后:主线程 StopPolling 同时还会 WakeupEmbedThread()(uv_async_send),让 PollEvents 从 epoll/IOCP 的阻塞中返回。

两个阻塞点都要能被外部打断,两次检查对应两次打断。 漏掉第二个检查的话,线程在 PollEvents 里被 IO 事件唤醒后还会 WakeupMainThread——PostTask 一个 UvRunOnce 到一个已经在销毁 NodeBindings 的进程里,weak_factory_ 会拦住它,但 PollEvents 本身是虚函数,对象析构后再调就崩了。注释原话:

"when this class is being destructed the PollEvents() would not be available anymore. Because of it we must make sure we only invoke PollEvents() when this class is alive."

注意一个细节:PollEvents() 是唯一的纯虚函数。embed 线程只通过这一个入口碰平台差异。如果析构和 PollEvents 并发,析构走的是 StopPolling → uv_thread_join,join 保证了虚函数调用结束后对象才继续析构——这是"用 join 做虚函数调用与析构的隔离"的标准手法。

精妙三:WakeupMainThread 用的是 PostTask + weak_ptr。

node_bindings.cc:1181

void NodeBindings::WakeupMainThread() {
	DCHECK(task_runner_);
	task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce,
												weak_factory_.GetWeakPtr()));
}

embed 线程唤醒主线程的方式不是 condition variable,不是 pipe,而是 Chromium 的 PostTask。为什么?因为主线程醒来的第一件事必须是"回到 Chromium 的 pump 语境"——它要处理的不只是 uv 事件,还有在它阻塞期间排队的 Chromium task。UvRunOnce 只是 pump 队列里的一个普通 task,跑完它 pump 会继续跑别的。如果用 condvar 唤醒,主线程就得在"处理 uv"和"处理 Chromium 队列"之间做自己的调度——等于重新发明 pump。

weak_factory_.GetWeakPtr() 保证:PostTask 排到队列后、执行前,如果 NodeBindings 被销毁,task 自动失效。这覆盖了 StopPolling 之后 post 竞态漏网的可能性——注意 WakeupMainThread 里只有 DCHECK(task_runner_),embed 线程 post 的时刻 StopPolling 可能正在主线程进行中,weak ptr 让这不再是一个竞态。

但是 weak_ptr 只保护 UvRunOnce 的执行,不保护 PostTask 本身。 如果 embed 线程在 task_runner_ 被 reset 之后调用(析构已开始),task_runner_ 是悬垂的 scoped_refptr。谁来防?答案还是 StopPolling 的 uv_thread_join:join 返回后主线程才继续析构 task_runner_。顺序又一次锁死一切。


6.4 UvRunOnce:主线程泵 uv 的三十七行

node_bindings.cc:1143

void NodeBindings::UvRunOnce() {
	node::Environment* env = uv_env();

	// When doing navigation without restarting renderer process, it may happen
	// that the node environment is destroyed but the message loop is still there.
	// In this case we should not run uv loop.
	if (!env)
	return;

	v8::HandleScope handle_scope(env->isolate());

	// Enter node context while dealing with uv events.
	v8::Context::Scope context_scope(env->context());

	{
	util::ExplicitMicrotasksScope microtasks_scope(
		env->context()->GetMicrotaskQueue());

	if (browser_env_ != BrowserEnvironment::kBrowser)
	TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");

	// The embed thread is parked on |embed_sem_| until we post it below and
	// re-reads uv_backend_timeout() before polling, so skip the interrupts.
	uv_loop_interrupt_suspend(uv_loop_);
	int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
	uv_loop_interrupt_resume(uv_loop_);

	if (browser_env_ != BrowserEnvironment::kBrowser)
	TRACE_EVENT_END0("devtools.timeline", "FunctionCall");

	if (r == 0)
	base::RunLoop().QuitWhenIdle();  // Quit from uv.
	}

	// Tell the worker thread to continue polling.
	uv_sem_post(&embed_sem_);
}

逐段读。

第一段:if (!env) return;。

uv_env() 是 set_uv_env 存的原生指针。什么时候会空?注释给了场景:renderer 进程里做导航但没重启进程时,node environment 已销毁而消息循环还在。此时 UvRunOnce 可能还在 pump 队列里(或被 embed 线程 post 过来),必须直接返回。

注意这个判空的时机:它让 UvRunOnce 连 uv_sem_post 都不做。这会不会破坏 6.3 节的"one post per UvRunOnce"协议?会——embed 线程会永远停在 uv_sem_wait 上。但这正是想要的:环境没了,这个 NodeBindings 事实上已退休(WillReleaseScriptContext 里紧接着就会 StopPolling 把线程 join 掉,6.9 节)。协议的破坏被生命周期管理兜住。

第二段:HandleScope + Context::Scope。

uv 回调要执行 JS。执行 JS 需要:(1)HandleScope 让局部 handle 可管理;(2)正确的 context。第二点在 renderer 里尤其关键——一个 isolate 有几十个 context(每个 frame、每个 world 一个),uv 回调属于哪个 frame 的环境,就必须进哪个 context。Context::Scope 用 RAII 保证回调执行完 context 正确退出。

第三段:ExplicitMicrotasksScope(6.8 节展开)。

一句话预告:它把当前 microtask queue 的策略临时切到 kExplicit再恢复。在 browser 进程里这是个 DCHECK(本来就是 kExplicit);在 renderer 里这是必须的动作——Blink 平时是 kScoped,若不切换,uv 回调执行完后 V8 会立刻自动跑微任务,而 Node 期望微任务由自己的 CallbackScope 管理。

第四段:TRACE_EVENT。

browser_env_ != kBrowser 时打 devtools.timeline 的 FunctionCall 区间。这是给 Chrome DevTools 的 Performance 面板用的——渲染进程里 uv 回调执行 JS,在 DevTools 看来就是一段函数调用,没有标记的话会显示成空白区间。browser 进程不打(DevTools 不 profile 主进程的这种粒度)。

第五段:uv_loop_interrupt_suspend / resume 包住 uv_run。

这是第 4 章补丁在这里的唯一消费者。注释原文:

"The embed thread is parked on |embed_sem_| until we post it below and re-reads uv_backend_timeout() before polling, so skip the interrupts."

意思:这个 uv_run 期间,embed 线程必然停在 uv_sem_wait 上(6.3 的协议保证了这一点——它 post 完 WakeupMainThread 就去等锁了)。而 uv_run 里可能启动/停止 watcher(回调里 setTimeout 一个新定时器),这些改动会触发 UV_LOOP_INTERRUPT_ON_IO_CHANGE 的"叫醒 poller"——但 poller 在睡觉不在 poll,叫醒是白费一次系统调用,还会让醒来的它做一次空的 WakeupMainThread → UvRunOnce 循环。suspend 掉,省一次 write/kevent/PQCS 加一次空转。

注意精细的边界,补丁文档原文(uv_loop_configure 的 doc):

"Calls nest. An embedder that polls uv_backend_fd from another thread suspends while that thread is known to be parked (typically around its own uv_run call) and must re-read uv_backend_timeout before letting it poll again. Loop thread only; uv_async_send() is never suppressed; a uv_run() issued from anywhere else (e.g. a native module pumping the loop from a Chromium task while the embed thread is polling) keeps interrupting."

三条边界:suspend 可嵌套计数;只有 loop 线程能 suspend;uv_async_send 永不被抑制(dummy handle 的叫醒永远有效——它是 StopPolling 用来打断 PollEvents 的生命线,抑制了就关不掉了)。而原生模块从别的 Chromium task 里自己 uv_run 时中断照常——那时 embed 线程可能正在 poll,必须被打断。

第六段:r == 0 时 QuitWhenIdle。

uv_run(UV_RUN_NOWAIT) 返回 0 表示 loop 里没有活跃 handle 了——uv 世界再无事件。base::RunLoop().QuitWhenIdle() 会让当前RunLoop 在队列排空后退出。这是"uv 空了 → 通知 Chromium 循环可以歇了"的桥。什么场景会走到这?主进程里用户代码全部定时器清完、server 全关、没有 pending IO——Node 的 beforeExit 语义(loop 空 → 发 beforeExit)在 Chromium 循环里的镜像。

但注意:它退的是 RunLoop() 当前那个。而 renderer 里这个 quit 是否合理是个经典问题——多个 frame 共享一个消息循环,一个 frame 的 loop 空了不该退整个循环。实践中 quit 有 idle 保护("WhenIdle"),Chromium 循环在有别的 task 时不会真的退出,所以伤害有限。这个 QuitWhenIdle 是从 atom-shell 时代继承下来的行为,属于"带着历史包袱但没人敢动"的代码。

第七段:uv_sem_post(&embed_sem_)。

协议闭环。放行 embed 线程去下一轮 poll。


6.5 PollEvents():三种内核,一种语义

embed 线程的等待在三个平台上有三个实现,各自不超过 30 行,但每一行都对应一个内核语义。

6.5.1 Linux:把 uv 的 epoll fd 再包一层 epoll

node_bindings_linux.cc:18

NodeBindingsLinux::NodeBindingsLinux(BrowserEnvironment browser_env,
									uv_loop_t* loop)
	: NodeBindings(browser_env, loop), epoll_(epoll_create(1)) {
	auto* const event_loop = uv_loop();

	int backend_fd = uv_backend_fd(event_loop);
	struct epoll_event ev = {0};
	ev.events = EPOLLIN;
	ev.data.fd = backend_fd;
	epoll_ctl(epoll_, EPOLL_CTL_ADD, backend_fd, &ev);
}

void NodeBindingsLinux::PollEvents() {
	auto* const event_loop = uv_loop();

	int timeout = uv_backend_timeout(event_loop);

	// Wait for new libuv events.
	int r;
	do {
	struct epoll_event ev;
	r = epoll_wait(epoll_, &ev, 1, timeout);
	} while (r == -1 && errno == EINTR);
}

第一件怪事:为什么造第二个 epoll?uv 内部不就有 epoll 吗?

uv 的 loop 自己有个 epoll 实例(backend_fd),所有 tcp/pipe/socket watcher 都注册在它上面。embed 线程理论上可以直接 epoll_wait(uv_backend_fd(...))。

但不行,两个原因:

  1. uv 自己要跑 uv__io_poll。 主线程的 UvRunOnce 每次 uv_run(NOWAIT) 都会进 uv__io_poll,它也要 epoll_wait(backend_fd)。epoll fd 允许多线程同时 wait 同一个实例(内核支持),但事件只投递给其中一个等待者。如果 embed 线程把事件"抢"走了,主线程的 uv__io_poll 就看不到它,uv 的事件处理逻辑(把就绪 fd 映射到 watcher 并调用回调)就不会执行——embed 线程只负责"发现有事件",不做这个映射。所以 embed 线程必须等在一个镜像上,事件发生后原封不动留给主线程消费。

  2. 要能随时打断。 StopPolling 需要把阻塞中的 PollEvents 叫醒。用第二个 epoll,WakeupEmbedThread 的 uv_async_send 会让 uv 内部唤醒 backend fd(async handle 的 pipe 写会触发 backend fd 可读),于是 epoll_wait 立刻返回。如果嵌在别的结构里(比如 uv_backend_timeout 的计算)就没这么直接。

所以结构是:epoll(embed 线程持有)监听 epoll(uv 持有)。事件到来时 embed 线程只看到"backend fd 可读",然后立刻返回、叫主线程,自己根本不读那个 fd——读了就把事件摘走了。

第二件事:uv_backend_timeout。

node_bindings_linux.cc:26

int timeout = uv_backend_timeout(event_loop);

这个函数(uv 实现)返回"距离下一个 timer 到期还有多少毫秒",如果 loop 里还有 pending 的回调/句柄队列要处理则返回 0,如果 loop 完全空闲且没有 timer 返回 -1(无限等待)。

这个值是在 embed 线程里读的,而 timer 是主线程注册的——数据竞争吗? 是,而且是被接受的竞争:uv_backend_timeout 读的是 loop 的 heap 头部和一个标志位,读到一个稍微过期的值无害(6.6 节会讲 interrupt 机制如何让过期的等待被纠正)。这就是为什么读它的时机被协议钉死在"主线程刚处理完一批事件之后"(uv_sem_post 之后的下一轮 PollEvents 开头)——那是它最新鲜的时刻。

第三件事:EINTR 重试。

epoll_wait 被信号打断(任何未被屏蔽的信号)返回 -1/EINTR。标准处理:重试。但注意它不重读 timeout——信号可能耽误了几十毫秒,重试用的是旧 timeout。uv 自己的 uv__io_poll 也这么干。影响:最多让某次等待比应有多等一点,正确性无损(timer 到期事件会通过 epoll 超时或者下一次 interrupt 到来)。

6.5.2 Windows:把完成事件"拿出来再放回去"

node_bindings_win.cc:19

NodeBindingsWin::NodeBindingsWin(BrowserEnvironment browser_env,
								uv_loop_t* loop)
	: NodeBindings(browser_env, loop) {
	auto* const event_loop = uv_loop();

	// on single-core the io comp port NumberOfConcurrentThreads needs to be 2
	// to avoid cpu pegging likely caused by a busy loop in PollEvents
	if (base::SysInfo::NumberOfProcessors() == 1) {
	// the expectation is the event_loop has just been initialized
	// which makes iocp replacement safe
	CHECK_EQ(0u, event_loop->active_handles);
	CHECK_EQ(0u, event_loop->active_reqs.count);

	if (event_loop->iocp && event_loop->iocp != INVALID_HANDLE_VALUE)
	CloseHandle(event_loop->iocp);
	event_loop->iocp =
		CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 2);
	}
}

void NodeBindingsWin::PollEvents() {
	auto* const event_loop = uv_loop();

	// If there are other kinds of events pending, uv_backend_timeout will
	// instruct us not to wait.
	DWORD bytes, timeout;
	ULONG_PTR key;
	OVERLAPPED* overlapped;

	timeout = uv_backend_timeout(event_loop);

	GetQueuedCompletionStatus(event_loop->iocp, &bytes, &key, &overlapped,
							timeout);

	// Give the event back so libuv can deal with it.
	if (overlapped != nullptr)
	PostQueuedCompletionStatus(event_loop->iocp, bytes, key, overlapped);
}

Linux 版的"镜像监听"技巧在 Windows 上没有对应物——IOCP 的完成事件是投递式的(GetQueuedCompletionStatus 会把事件从队列里取走),不是监听式的。所以这里用了看起来更奇怪的招:取出来,再放回去。

GetQueuedCompletionStatus 阻塞等一个完成事件;等到后,embed 线程不处理它,立刻 PostQueuedCompletionStatus 原样塞回去,然后返回、叫主线程。主线程的 uv__poll(uv 在 Windows 上的 poll)稍后自己 GetQueuedCompletionStatus 把它取走,走 uv 的正常分发。

这就是 IOCP 版的"镜像":事件从内核队列出来又回内核队列,embed 线程只是一个"确认有货"的探测器。

单核的 busy loop 修复是这段代码里最有历史感的部分。注释说:单核机器上,IOCP 的 NumberOfConcurrentThreads(并发线程配额)需要是 2,否则 PollEvents 会"cpu pegging likely caused by a busy loop"。

原理:GetQueuedCompletionStatus 在配额为 1(uv 默认按 CPU 数创建)时,如果主线程正在 uv_run 里持有这个配额,embed 线程的 GetQueuedCompletionStatus 会立刻返回失败(ERROR_INSUFFICIENT_BUFFER? 不——配额不足时 IOCP 让后来者直接绕过等待机制返回),于是 PollEvents 不再阻塞,embed 线程空转——循环回到 uv_sem_wait 又立刻被 post,CPU 直接打满。配额改成 2(两个消费者:主线程 + embed 线程),两个 GetQueuedCompletionStatus 才都能真正挂起。

CHECK_EQ(0u, event_loop->active_handles) 是换 IOCP 的安全前提:IOCP 上挂着未完成请求时销毁它会丢事件。所以这个替换只能发生在"loop 刚 init 完,什么都没注册"的时刻——构造函数恰好是。这条 CHECK 把"安全窗口"变成了断言。

overlapped != nullptr 的判空:GetQueuedCompletionStatus 超时返回 FALSE 且 *overlapped 为 NULL——超时时没有事件可归还。这正是 uv_backend_timeout 说的"timer 到点了,该让主线程跑一圈了"的路径:embed 线程空手叫醒主线程,主线程 uv_run(NOWAIT) 处理到期的 timer。

6.5.3 macOS:poll() 直守 kqueue fd

macOS 有自己的 node_bindings_mac.cc:19-26(35 行),而且它揭示了一个此前没明说的对称性:

node_bindings_mac.cc:22

void NodeBindingsMac::PollEvents() {
	auto* const event_loop = uv_loop();
	// uv_backend_timeout returns milliseconds or -1 for infinite wait.
	const int backend_fd = uv_backend_fd(event_loop);
	const int timeout_ms = uv_backend_timeout(event_loop);  // -1 => infinite

	struct pollfd pfd;
	pfd.fd = backend_fd;
	pfd.events = POLLIN;
	pfd.revents = 0;

	int r;
	do {
	r = poll(&pfd, 1, timeout_ms);
	} while (r == -1 && errno == EINTR);
}

macOS 不需要"镜像"。 它直接 poll() uv 的 backend fd(macOS 上是 kqueue 的 fd)。

为什么 Linux 要造第二个 epoll、macOS 不用?答案在于**"等待是否会消耗事件"**:

  • Linux 的 epoll_wait 不消耗事件——多个等待者等同一个 epoll 实例,就绪事件只投递给其中一个。如果 embed 线程直接等 backend fd,它会"抢走"事件,主线程的 uv__io_poll 就看不见了。所以必须造一个镜像层,让 embed 线程等在"镜像"上,事件原封留在真身上。
  • macOS 的 poll() 只测可读性——它不进入 kqueue 的事件队列,只是检查 fd 当前状态(有数据可读吗)。它不取走任何 kevent。所以 embed 线程可以直接 poll backend fd:可读 → 通知主线程 → 返回;主线程稍后的 uv__io_poll(内部 kevent() 系统调用)照样能取到事件。
  • Windows 的 IOCP 是投递队列——GetQueuedCompletionStatus 必然取走事件。所以走"取出再放回"(6.5.2)。

三个平台,三种内核语义,一个共同的抽象:PollEvents() 必须能(1)带超时等待、(2)被 uv_async_send 打断、(3)不消耗事件。 满足这三条的最低成本方案,各平台不同。

再注意两个细节。一是补丁里那行 int kqueue_evfilt_user_support = 1;(从 static 改为 extern):uv 在 macOS 的 async 实现优先用 kqueue 的 EVFILT_USER 过滤器触发自我唤醒——uv_async_send(WakeupEmbedThread 的底层)靠它打断 PollEvents。没有这个改动,StopPolling 在 macOS 上就掐不死 embed 线程。二是 timeout_ms 的注释 "// -1 => infinite":poll 的超时参数恰好和 uv_backend_timeout 的返回语义(-1 无限等)天然对齐,无需转换——这多半不是巧合,libuv 的 API 就是为这种嵌入设计的。


6.6 uv_loop_interrupt 补丁:为什么必须有它

现在可以完整讲 6.2 节埋下的伏笔了。补丁文件:

feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch

commit message(第 4 章引用过第一段,现在看全文):

The option makes libuv wake up whoever is polling the loop's backend fd from another thread (Electron's embed thread in NodeBindings) whenever a watcher/handle is started, stopped or fed, so that a poll started with a now-stale uv_backend_timeout() gets to see the change.

On top of the upstream PR this adds uv_loop_interrupt_suspend/resume(). An embedder that knows its poller is parked suspends the interrupt around its own uv_run(): NodeBindings::UvRunOnce holds the embed thread on embed_sem_ for the whole of that uv_run(), and the thread re-reads uv_backend_timeout() (0 for a non-empty pending/watcher queue, and aware of newly started timers) before it polls again, so an interrupt there is only a write()/kevent()/PQCS on the loop thread plus a spurious wakeup of the poller and, in Electron, an extra empty UvRunOnce task per tick. The depth is loop-thread only. uv_async_send() is never suppressed, and a uv_run() issued from anywhere else (e.g. a native module pumping the loop from a Chromium task while the embed thread is polling) keeps interrupting. Prepare/check handles started while suspended are not visible to uv_backend_timeout() and wait for the next wakeup; Node only does that in StartProfilerIdleNotifier.

逐句拆。第一段定义问题——过期超时(stale timeout)。

6.6.1 没有 interrupt 的世界

走一遍时序:

T0  主线程 UvRunOnce 完成,uv_sem_post 放行 embed 线程
T1  embed 线程读 uv_backend_timeout() → 返回 -1(loop 空闲,无 timer)
T2  embed 线程 epoll_wait(镜像fd, 超时=-1) → 无限等待
T3  主线程 JS 执行 setTimeout(fn, 10)
	→ uv_timer_start:修改 loop 的 timer 堆 + 更新 loop->timer_counter
	→ 但镜像 epoll 上没有任何变化!
T4  ...10ms 过去...
T5  ...永远没有任何东西叫醒 embed 线程(除非别的 IO 发生)...

T3 的问题:uv_timer_start 的实现里有一个优化——如果新 timer 是"最早到期的",它会更新 loop->time 相关状态并写 wakeup pipe(uv 的 async 机制),让正在 uv__io_poll 里的自己人早点醒。但这个唤醒机制是给"同一个线程里的 uv_run"设计的:uv__io_poll 检查发现 timer 变了,就重算 timeout 继续 wait。

Electron 把 poll 拆到另一个线程后,uv 内部的这套自我唤醒全废了——主线程不在 uv__io_poll 里,embed 线程在镜像 epoll 上,uv 的 async pipe 可读事件确实会被投到 backend fd……等等,async pipe 是注册在 backend fd 上的!那镜像 epoll 不也能看到?

看到,但太迟了。镜像 epoll 看到的是"backend fd 可读"。而 epoll_wait 的超时参数在 T2 时刻就定死为 -1(无限等)——事件到来会打断无限等待,没问题!uv_async_send 会写 pipe,让 backend fd 可读,镜像 epoll 立刻返回,embed 线程叫醒主线程,主线程跑 uv_run(NOWAIT),处理 async + 到期 timer。看起来没问题?

问题出在 uv_async_send 只在 async 机制被触发时发生。uv_timer_start 会不会触发它?看 uv 源码(uv__next_timeout 的使用者 uv__io_poll):uv_timer_start 直接改堆,不发 async。async 只在跨线程 API(uv_async_send)和内部某些请求完成时触发。同线程注册 timer,uv 假设"你注册 timer 的地方就在 loop 线程,等你自己 uv_run 时自然会重算 timeout"。

在 Node 里这个假设成立:注册 timer 的线程就是跑 loop 的线程。 在 Electron 主进程里也成立(都是主线程)!那问题在哪?

问题在时间窗口。回到协议:

T1  embed 线程读 timeout = -1
T2  embed 线程进入 epoll_wait(无限)
T3  主线程 uv_timer_start(fn, 10)   ← 此刻 loop 有 timer 了
T4  主线程回到 pump,阻塞等 Chromium 消息

主线程没有 loop 可跑(uv 的),它阻塞在 Chromium 的 pump 上。uv 的 async pipe 没人写。embed 线程在镜像 epoll 上无限等待——backend fd 不可读(没有任何 IO 事件),async 没触发。10ms 后 timer 逻辑上到期了,但没有人知道。直到下一次 Chromium task 醒来恰好 post 了 UvRunOnce(如果有的话),或者有 IO 发生。

症状:系统空闲时,setTimeout(fn, 10) 实际 500ms+ 才执行(Chromium pump 的默认超时决定了它多久醒一次)。这正是 Electron 早期 issue 列表里"定时器在空闲时漂移"的根因。

6.6.2 补丁的修法

UV_LOOP_INTERRUPT_ON_IO_CHANGE:libuv 在每次 watcher/handle 启动、停止、投喂时,检查这个选项是否开启,若开启则写 loop 的 wakeup 通道(Linux 上是 backend fd 对应的 async pipe / io_uring;macOS 上是 EVFILT_USER 触发 kqueue——补丁把 kqueue_evfilt_user_support 从 static 改成 extern 就是为了让这个跨文件可用;Windows 上是 PostQueuedCompletionStatus)。

效果:T3 的 uv_timer_start 直接把 embed 线程从 epoll_wait 里打醒,它立刻 WakeupMainThread,主线程跑 uv_run(NOWAIT)——但此时 timer 还没到期(才过了 0ms)!uv_run 空转返回。embed 线程重读 timeout = 10ms,这次 epoll_wait 带上正确的超时。10ms 后超时返回,再叫主线程,timer 回调执行。

一次 interrupt 修正了 stale timeout。 这就是 commit message 第一段的全部含义:"so that a poll started with a now-stale uv_backend_timeout() gets to see the change"。

6.6.3 第二段:为什么还要 suspend/resume

suspend/resume 是性能收尾。回顾 6.4 节 UvRunOnce 的结构:主线程自己的 uv_run(NOWAIT) 期间(回调里可能 setTimeout、fs.open),embed 线程必然停在 uv_sem_wait(协议保证)。此时 interrupt 叫醒谁?没人可叫——embed 线程不在 poll。但 interrupt 的系统调用(write/kevent/PQCS)照做,而且更糟:

"an interrupt there is only a write()/kevent()/PQCS on the loop thread plus a spurious wakeup of the poller and, in Electron, an extra empty UvRunOnce task per tick."

三个成本:一次系统调用、poller 被白叫一次、每 tick 多一个空的 UvRunOnce task。第三个最隐蔽:叫醒 embed 线程 → 它 post WakeupMainThread → 主线程多跑一次空 UvRunOnce → uv_run 空转 + 一次 sem_post。每个循环 tick 平白多一整圈。

所以 suspend/resume 的语义是"我知道 poller 在睡觉,这期间 loop 的变化不会丢(它醒来会重读 timeout),所以叫醒是纯浪费"。配合的关键事实是:醒来重读。suspend 不是"屏蔽变化",是"推迟确认"。

补丁文档最后一句话给出已知妥协:

"Prepare/check handles started while suspended are not visible to uv_backend_timeout() and wait for the next wakeup; Node only does that in StartProfilerIdleNotifier."

uv_backend_timeout 不算 prepare/check handle(它们属于"每次 loop 迭代都要跑"的类别,不算"等待理由")。suspend 期间被启动的 prepare/check 会等下一次正常 wakeup。谁会这么干?只有 Node 的 StartProfilerIdleNotifier(--prof 模式的 idle 采样)。普通应用碰不到。

6.6.4 上游 vs 私有

补丁头写着 https://github.com/libuv/libuv/pull/3308——UV_LOOP_INTERRUPT_ON_IO_CHANGE 部分是上游 PR 的副本(Electron 自带 fork 的 libuv,位于 third_party/electron_node/deps/uv,所以还是要打 node 补丁集里),suspend/resume 是 Electron 私有加层。这类"上游有方案但不完全够 → 在 fork 上补一层"的模式,是第 4 章说的"加能力"型补丁的典型形态。


6.7 启动与关闭:PrepareEmbedThread、StartPolling、StopPolling

三个函数构成 embed 线程的生命周期。逐个看。

6.7.1 PrepareEmbedThread:一次性的把手 + 可重复的线程

node_bindings.cc:1073

void NodeBindings::PrepareEmbedThread() {
	// IOCP does not change for the process until the loop is recreated,
	// we ensure that there is only a single polling thread satisfying
	// the concurrency limit set from CreateIoCompletionPort call by
	// uv_loop_init for the lifetime of this process.
	// More background can be found at:
	// https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400
	if (initialized_)
	return;

	// The async handle and semaphore live for the lifetime of this
	// NodeBindings instance (destroyed in ~NodeBindings), but the embed
	// thread itself may be stopped and restarted via StopPolling /
	// PrepareEmbedThread for pooled worklet contexts. Only init the
	// handles once.
	if (!embed_thread_prepared_) {
	// Add dummy handle for libuv, otherwise libuv would quit when there is
	// nothing to do.
	uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr);

	// Start worker that will interrupt main loop when having uv events.
	uv_sem_init(&embed_sem_, 0);
	embed_thread_prepared_ = true;
	}

	uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
}

两个 bool 守卫两个不同的"只做一次":

  • initialized_(在 StartPolling 里置位):整个进程生命周期只准有一个 poll 线程。注释给了原因:Windows 上 IOCP 的并发配额在 uv_loop_init 时定死,第二个 poll 线程会破坏"配额 = 实际消费者数"的假设(正是 6.5.2 单核 bug 的对称问题)。链接指向 vscode#142786——VSCode 遇到过真实的死锁/飙升问题。
  • embed_thread_prepared_(本函数置位):本 NodeBindings 实例的 semaphore 和 dummy handle 只 init 一次,即使线程本身被 Stop/Start 反复折腾(pooled worklet 场景,6.11 节)。

dummy handle 的双重职责。uv_async_init(loop, dummy, nullptr)——注册一个没有回调的 async handle:

  1. 让 loop 永远"活着"。 uv_run 系列判断"loop 是否无事可做"的依据是活跃 handle 计数。dummy 让计数永远 ≥1,所以 UvRunOnce 里 uv_run(NOWAIT) 的返回值永不为 0(除非有人显式关掉它)——loop 不会"自然死亡"。为什么需要?没有它,用户代码暂时清空所有 handle 时,r == 0 → QuitWhenIdle → 主循环退出。dummy 把"进程是否退出"的决定权从 uv 手里拿回到 Chromium/Browser 层。
  2. WakeupEmbedThread 的载体。uv_async_send(dummy) 会写 loop 的 wakeup 通道 → backend fd 可读 → 镜像 epoll / GetQueuedCompletionStatus 返回 → PollEvents 被打断。回调是 nullptr 没关系——唤醒才是目的,uv 处理 async handle 时发现没有回调就跳过。

6.7.2 StartPolling:记住 task runner,立刻跑一轮

node_bindings.cc:1096

void NodeBindings::StartPolling() {
	// Avoid calling UvRunOnce if the loop is already active,
	// otherwise it can lead to situations were the number of active
	// threads processing on IOCP is greater than the concurrency limit.
	if (initialized_)
	return;

	initialized_ = true;

	// The MessageLoop should have been created, remember the one in main thread.
	task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault();

	// Run uv loop for once to give the uv__io_poll a chance to add all events.
	UvRunOnce();
}

两个动作:

task_runner_ 的快照。 GetCurrentDefault() 拿到当前线程的默认 TaskRunner。为什么此刻拿?因为 StartPolling 的调用点保证主线程的 MessageLoop 已存在(browser:PreMainMessageLoopRun,在 message loop 创建之后;renderer:DidCreateScriptContext 尾部 PostTask 出去,跑在 loop 里)。embed 线程之后 post 就用它。注释 "The MessageLoop should have been created, remember the one in main thread"——DCHECK(task_runner_) 在 WakeupMainThread 里验证。

手动先跑一次 UvRunOnce。 注释:"give the uv__io_poll a chance to add all events"。启动时刻 loop 里可能已经有一堆 handle(InitializeOncePerProcess 注册的信号 handle、stdio、LoadEnvironment 里 JS 建立的)——但镜像 epoll 上还没有!embed 线程第一次 PollEvents 前,镜像 epoll 只 add 了 backend_fd。如果主线程不先跑一次 uv_run,uv 内部的 uv__io_poll 不会执行,某些 watcher 的 fd 注册可能还没完成(比如 async pipe 的读端要在第一次 poll 才进 backend epoll)。这一轮 UvRunOnce 把 uv 内部状态推进到"所有 watcher 就位",然后 sem_post 放行 embed 线程开始第一次真正的 poll。 起跑线对齐。

6.7.3 StopPolling:两边打断 + join + 清干净信号量

node_bindings.cc:579

void NodeBindings::StopPolling() {
	if (!initialized_)
	return;

	// Tell the embed thread to quit.
	embed_closed_ = true;

	// The embed thread alternates between uv_sem_wait (waiting for UvRunOnce
	// to finish) and PollEvents (waiting for I/O). Wake it from both.
	uv_sem_post(&embed_sem_);
	WakeupEmbedThread();

	// Wait for it to exit.
	uv_thread_join(&embed_thread_);

	// Drain any leftover semaphore posts so the next embed thread starts
	// in a clean lock-step state. A stale count can occur if UvRunOnce
	// posted sem_post concurrently with our StopPolling sem_post — the
	// embed thread consumed one to see embed_closed_ and exited, leaving
	// the other unconsumed. Without draining, the next EmbedThreadRunner
	// would fall through uv_sem_wait immediately, breaking the intended
	// one-post-per-UvRunOnce protocol.
	while (uv_sem_trywait(&embed_sem_) == 0) {
	}

	// Allow PrepareEmbedThread + StartPolling to restart.
	embed_closed_ = false;
	initialized_ = false;
}

这段注释是全文件最长的之一,因为它描述的竞态最反直觉。

两边打断:6.3 节讲过——embed 线程在两个阻塞点之间轮换,sem_post 打断 uv_sem_wait,uv_async_send(写 wakeup 通道)打断 PollEvents。

竞态场景:主线程执行 StopPolling 的同时,主线程自己……不,竞态的另一方是谁?"if UvRunOnce posted sem_post concurrently with our StopPolling sem_post"——UvRunOnce 是主线程自己跑的,StopPolling 也在主线程,怎么会并发?

细想:UvRunOnce 是 PostTask 的 task。时序可以是:

主线程 pump 队列: [..., task(UvRunOnce), ...]
StopPolling 被调用(比如 WillReleaseScriptContext)之前,
task(UvRunOnce) 可能刚被执行到 sem_post 之前?

不,同线程不并发。真正的场景是顺序错位:

T0  主线程跑 UvRunOnce:uv_run 完成 → 准备 sem_post
T1  (另一个执行流——不对,还是同线程……)

再读注释:"if UvRunOnce posted sem_post concurrently with our StopPolling sem_post"。concurrently 在这里的意思不是真并行,而是"两次 post 在 embed 线程消费之前都已发生":

T0  embed 线程在 uv_sem_wait(第 N 轮开始)
T1  主线程跑 UvRunOnce → sem_post(第 N 轮放行)
T2  embed 线程还没醒(调度延迟)
T3  主线程调 StopPolling → embed_closed_=true → sem_post(第二个!)
T4  embed 线程醒:消费一个 sem(第 N 轮的),读 embed_closed_ —— true!
	→ 退出。第二个 sem 永远没人消费。

如果不清理:下次 PrepareEmbedThread 重启线程(pooled worklet),新线程第一轮 uv_sem_wait 立刻通过(信号量残留计数 1)——它没等主线程的 UvRunOnce 就去 poll 了。协议错位后,后续每一轮都可能"主线程还没处理完上一批,embed 线程已经开始下一轮 poll",读到过期的 timeout……一切的根。

while (uv_sem_trywait(&embed_sem_) == 0) {} 把残留计数清零。然后 embed_closed_ = false; initialized_ = false; 允许重启。这两个 bool 的复位顺序:先清信号量再复位标志,如果反了,新线程可能看到 embed_closed_ = false 但信号量脏。

这个函数的存在本身就是 pooled worklet(6.11 节)需求的证明:没有"线程需要反复停启"的场景,谁会把 stop 写得这么仔细。


6.8 微任务:kExplicit 与 kScoped 的边界谈判

Node 和 Blink 对"微任务什么时候跑"的答案不同。Electron 必须在同一批进程里同时满足两者。

Node 的答案(kExplicit):微任务只在显式检查点跑——node::CallbackScope 析构时、MakeCallback 返回时。保证:一段 JS 里 promise 链不会在半路插入。

Blink 的答案(kScoped):v8::MicrotasksScope 离开时自动跑微任务。浏览器语义:每个脚本"turn"结束(事件处理完、<script> 执行完)就 flush。

V8 的策略是 isolate 级的(每个 MicrotaskQueue 一个),两边共住一个 isolate 时必须仲裁。Electron 的方案分三层。

6.8.1 第一层:SetUpIsolate 按进程定型

node_bindings.cc:780-839(NodeBindings::SetUpIsolate):

	if (browser_env_ == BrowserEnvironment::kBrowser ||
	browser_env_ == BrowserEnvironment::kUtility) {
	// Node.js requires that microtask checkpoints be explicitly invoked.
	is.policy = v8::MicrotasksPolicy::kExplicit;
	} else {
	// Blink expects the microtasks policy to be kScoped, but Node.js expects
	// it to be kExplicit. In the renderer, there can be many contexts within
	// the same isolate, so we don't want to change the existing policy here,
	// which could be either kExplicit or kScoped depending on whether we're
	// executing from within a Node.js or a Blink entrypoint. Instead, the
	// policy is toggled to kExplicit when entering Node.js through UvRunOnce.
	is.policy = isolate->GetMicrotasksPolicy();
	...

三种立场:

  • browser / utility:纯 Node 语义,kExplicit,一锤定音。
  • renderer / worker:不改策略!注释解释了为什么不能改:一个 isolate 几十个 context,"当前策略"取决于当前在哪个入口——Blink 的入口是 kScoped,Node 的入口(uv 回调)想要 kExplicit。策略不再是一个恒定值,而是一个"随入口切换"的状态。

配套的还有三个渲染进程专属的退让(同函数往下):

node_bindings.cc:817-818

	// We do not want to use Node.js' message listener as it interferes with
	// Blink's. Instead we add our own to ensure that the async hook stack is
	// properly cleared when errors are thrown.
	is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL;
	isolate->AddMessageListenerWithErrorLevel(ErrorMessageListener, ...);

报错通道让给 Blink,但 ErrorMessageListener(node_bindings.cc:392)做了 Node 的收尾——把 async_hooks 的栈清干净(EmitAfter 未发出的 after 钩子 + clear_async_id_stack),否则一次异常会让 async hook 栈永久泄漏,之后所有 asyncId 关联错乱。

promise rejection 回调、prepare stack trace 回调也各让一位(SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK、SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK)——都是"Node 的默认实现假设自己是唯一主人,渲染进程里主人是 Blink"的具体让渡。

6.8.2 第二层:UvRunOnce 的进门前切换

renderer 里 uv 回调属于 Node 的入口,进门前切 kExplicit——UvRunOnce 里的 util::ExplicitMicrotasksScope(node_util.cc:201):

ExplicitMicrotasksScope::ExplicitMicrotasksScope(v8::MicrotaskQueue* queue)
	: microtask_queue_(queue), original_policy_(queue->GetMicrotasksPolicy()) {
	// Browser-like processes already run with kExplicit, nested run loops
	// included. Renderers can get here from inside script (a frame's environment
	// freed by element.remove()); explicit checkpoints are then no-ops until the
	// enclosing scope unwinds.
	if (electron::IsBrowserProcess() || electron::IsUtilityProcess())
	DCHECK_EQ(original_policy_, v8::MicrotasksPolicy::kExplicit);

	microtask_queue_->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
}
ExplicitMicrotasksScope::~ExplicitMicrotasksScope() {
	microtask_queue_->SetMicrotasksPolicy(original_policy_);
}

构造时存原策略、切 kExplicit;析构时恢复。browser 进程里这个切换是 DCHECK 验证的恒等操作(本来就是 kExplicit);renderer 里它是每次 uv 回调执行期间的临时状态——回调期间 Blink 的"离开 scope 自动跑微任务"被压制,微任务留给 Node 的显式检查点。

注意注释里的嵌套语义:"explicit checkpoints are then no-ops until the enclosing scope unwinds"——renderer 里 UvRunOnce 可能在 Blink 脚本之内发生(element.remove() 触发 frame 环境销毁 → 内部要泵 uv)。此时外层已经是某层 ExplicitMicrotasksScope,嵌套只是再包一层,内层的"检查点"(kExplicit 模式下的 MicrotasksScope::kRunMicrotasks)仍是 no-op,真正的 flush 等最外层退出。嵌套安全来自"策略是栈式恢复的"这个事实。

6.8.3 第三层:MicrotasksRunner——Chromium task 与 Node checkpoint 的对接

前两层解决了"uv 回调期间"。但 kExplicit 意味着没有任何机制会在 Chromium task 结束时跑微任务——而 Node 的 CallbackScope 只包裹 Node 自己发起的调用。如果 promise 的 resolve 发生在一个纯 Chromium task 里(比如 mojo 回调直接 resolve 了一个 JS promise),谁去 flush?

microtasks_runner.cc:18-21(全文 32 行里最核心的 16 行):

microtasks_runner.cc:18-21

void MicrotasksRunner::DidProcessTask(const base::PendingTask& pending_task) {
	// In the browser process we follow Node.js microtask policy of kExplicit
	// and let the MicrotaskRunner which is a task observer for chromium UI thread
	// scheduler run the microtask checkpoint. This worked fine because Node.js
	// also runs microtasks through its task queue, but after
	// https://github.com/electron/electron/issues/20013 Node.js now performs its
	// own microtask checkpoint and it may happen is some situations that there is
	// contention for performing checkpoint between Node.js and chromium, ending
	// up Node.js delaying its callbacks. To fix this, now we always lets Node.js
	// handle the checkpoint in the browser process.
	{
	v8::HandleScope handle_scope(isolate_);
	node::CallbackScope microtasks_scope(isolate_, v8::Object::New(isolate_),
										{0, 0});
	}
}

MicrotasksRunner 是 Chromium 的 base::TaskObserver——挂在主线程 MessageLoop 上(javascript_environment.cc:318 的 CreateMicrotasksRunner:base::CurrentThread::Get()->AddTaskObserver(...)),每个 Chromium task 执行完毕后被调用。它的 DidProcessTask 里只做一件事:开一个空的 node::CallbackScope,让它的析构跑一次 Node 的 tick + 微任务检查点。

这段注释浓缩了 Electron 的一次架构返工,值得逐句:

第一句(旧世界):"we follow kExplicit and let the MicrotaskRunner ... run the microtask checkpoint"——曾经的方案:Chromium task 结束时由 MicrotasksRunner 负责 flush。

第二句(转折):"This worked fine because Node.js also runs microtasks through its task queue"——旧世界成立的前提:Node 自己的异步(process.nextTick、promise)最终都会经过"宏任务边界",而每个宏任务在 Chromium 眼里是一个 task,task 结束时 observer flush,时序正确。

第三句(崩塌):"but after issue #20013 Node.js now performs its own microtask checkpoint and ... contention ... ending up Node.js delaying its callbacks"——Node 12+ 在自己的代码路径(MakeCallback)里也开始主动做 checkpoint。两边的 checkpoint 争夺"什么时候 flush":Chromium 的 observer 在 task 结束后,Node 的在自己的调用栈内。语义冲突导致 Node 的回调被推迟(具体机制:Node 的 checkpoint 先跑掉了微任务,Chromium observer 后到时队列已空;或反之,双方互相以为对方会跑)。

第四句(新世界):"now we always let Node.js handle the checkpoint in the browser process"——裁判权全部收归 Node。MicrotasksRunner 的 CallbackScope 仍然每次 task 后都开,但它的作用变成了"确保有一个 Node 语境的检查点"而不是"和 Node 抢着跑"——CallbackScope 是 Node 认可的显式检查点,Node 内部机制看到它不会打架(这正是 kExplicit 模式下唯一合法的 flush 方式)。

{0, 0} 是什么? CallbackScope 的第三参数是 async_context(asyncId/triggerAsyncId 对)。{0, 0} 表示"不在任何 async 上下文里"——flush 微任务时不产生 async hook 的 before/after 事件,避免污染用户的 async_hooks 观测。

v8::Object::New(isolate) 又是什么? CallbackScope 的第二参数是"当前 handle scope 的对象"——Node 用它来定位 Environment(从对象的 internal field 反查)。传一个空对象是"我不提供,你自己找当前 context 的"——配合 HandleScope,CallbackScope 从 isolate->GetCurrentContext() 拿到 Environment。

挂载与摘除(javascript_environment.cc:318-342)也有讲究:

void JavascriptEnvironment::CreateMicrotasksRunner() {
	DCHECK(!microtasks_runner_);
	microtasks_runner_ = std::make_unique<MicrotasksRunner>(isolate());
	isolate_holder_->WillCreateMicrotasksRunner();
	base::CurrentThread::Get()->AddTaskObserver(microtasks_runner_.get());
}

void JavascriptEnvironment::DestroyMicrotasksRunner() {
	DCHECK(microtasks_runner_);
	// Should be called before running gin_helper::CleanedUpAtExit::DoCleanup.
	// This helps to signal wrappable finalizer callbacks to not act on freed
	// parameters.
	isolate_holder_->WillDestroyMicrotasksRunner();
	{
	v8::HandleScope scope{isolate()};
	gin_helper::CleanedUpAtExit::DoCleanup();
	}
	// After DoCleanup() so that observers created by JS that ran during it (e.g.
	// a webContents 'destroyed' handler) are notified too.
	gin::PerIsolateData::From(isolate())->NotifyBeforeMicrotasksRunnerDispose();
	base::CurrentThread::Get()->RemoveTaskObserver(microtasks_runner_.get());
	microtasks_runner_.reset();
}

DestroyMicrotasksRunner 里的清理顺序是"先 CleanedUpAtExit::DoCleanup()(让所有注册了退出清理的 C++ 对象有机会在 isolate 活着时释放 JS 侧引用),再通知 PerIsolate 的 observer(OnBeforeMicrotasksRunnerDispose——第 5 章 5.11 节见过的那些 SafeStorage/Session/GlobalShortcut 都实现它,在 observer 摘除前做最后清理),最后才 RemoveTaskObserver"。先给所有人反悔的机会,再拆裁判。

而 utility 进程呢?它也是 kExplicit、也有 js_env_->CreateMicrotasksRunner()(node_service.cc 里与 browser 平行)。渲染进程没有 MicrotasksRunner——Blink 自己有等价物(EndOfTaskRunner),MicrotasksRunner 的头文件注释承认了这一点:"Microtasks runner implementation is based on the EndOfTaskRunner in blink"。


6.9 渲染进程:一个 isolate,多个 context,多个 loop

渲染进程是这套架构最复杂的宿主。三个前提叠在一起:

  1. 一个渲染进程只有一个主 isolate(Blink 的规矩),所有 frame 共用。
  2. 每个 frame 有自己的 V8 context(每个 world 再乘一层)。
  3. Node 的 Environment 绑定在 context 上,而 Environment 又绑着一个 uv loop。

于是:一个 isolate 里并存多个 node::Environment,每个各自带一个 uv loop 和一个 embed 线程。

6.9.1 FrameEnvironment:主 frame 借 loop,其余 frame 各造一个

electron_renderer_client.cc:34-65:

struct ElectronRendererClient::FrameEnvironment {
	// A main frame borrows |primary|, which integrates uv_default_loop(), while
	// no other environment occupies it; every other frame gets its own loop.
	FrameEnvironment(bool is_main_frame,
				NodeBindings* primary,
				ElectronBindings* primary_electron_bindings) {
	if (is_main_frame && primary->uv_env() == nullptr) {
	node_bindings = primary;
	electron_bindings = primary_electron_bindings;
	return;
	}
	own_node_bindings = NodeBindings::Create(
		NodeBindings::BrowserEnvironment::kRenderer, nullptr);
	own_electron_bindings =
		std::make_unique<ElectronBindings>(own_node_bindings->uv_loop());
	node_bindings = own_node_bindings.get();
	electron_bindings = own_electron_bindings.get();
	}
	...
};

注意条件是复合的:is_main_frame && primary->uv_env() == nullptr。第一个好懂——只有主 frame 可以借默认 loop。第二个呢?

"主 frame 但 uv_env 已被占用" 什么时候发生?跨世界(world)。同一 frame 的 preload 可能跑在 isolated world 里;主 world 的 Node 环境和 isolated world 的 Node 环境都要建,先到者占 uv_default_loop(),后到者即使是同一个 frame 也只能另造 loop。条件写法防止了两个 Environment 抢一个 loop 的时序漏洞。

每个 FrameEnvironment 持有:

electron_renderer_client.cc:56-58

	std::shared_ptr<node::Environment> environment;
	// The world of |environment|'s context, recorded while Blink can still map
	// the context to its frame.
	int world_id = 0;
	base::WeakPtrFactory<FrameEnvironment> weak_factory{this};

world_id 的注释值得划线:"recorded while Blink can still map the context to its frame"——world 到 context 的映射只在世界存活时有效,环境销毁时 Blink 侧先行拆除,所以要提前抄下来。这类"趁还认得出就记下"的防御在 Electron 里反复出现。

6.9.2 DidCreateScriptContext:八个关键步骤,每步都不能换序

electron_renderer_client.cc:134-223。按出场顺序讲:

(1)只给主 frame / devtools / 明确许可的 subframe 建 Node。

electron_renderer_client.cc:132-133

	if (!ShouldLoadPreload(isolate, renderer_context, render_frame))
	return;

iframe 默认没有 Node——安全边界(第 15 章展开)。

(2)进程级 Node 初始化只做一次。

electron_renderer_client.cc:135-139

	if (!node_integration_initialized_) {
	node_integration_initialized_ = true;
	node_bindings_->Initialize(isolate, renderer_context);
	node_bindings_->SetUpIsolate(isolate);
	// SetUpIsolate registers Node's WebAssembly streaming callback, whose JS
	// side kNoBrowserGlobals never installs; put Blink's back.
	blink::WasmResponseExtensions::Initialize(isolate);
	}

Initialize 调 node::InitializeOncePerProcess——进程级,做两次会崩。所以第一个 frame 进来时做完,后续 frame 跳过。

那三行 WASM 注释是 Electron/Node/Blink 三方的一个精确三角债:SetUpIsolate → node::SetIsolateUpForNode 会注册 Node 的 WASM 流式编译回调;但渲染进程里 kNoBrowserGlobals 让 Node 的 JS 侧 wasm glue(v8::WasmWebAssembly 的 JS 支撑函数)不装——回调会调一个不存在的 JS 对象。所以立刻 blink::WasmResponseExtensions::Initialize 把 Blink 的装回去。C++ 回调是 Node 的,JS 运行时是 Blink 的——第 5 章 5.5.5 的 --experimental-eventsource 是同一个模式的又一实例。

(3)node::InitializeContext——per-context 的 Node 基建。

electron_renderer_client.cc:153-154

	v8::Maybe<bool> initialized = node::InitializeContext(renderer_context);
	CHECK(!initialized.IsNothing() && initialized.FromJust());

在 context 的 embedder slot 里装 IsolateData 语境、给 global 装内部函数等——这是 node::Environment 的前置。browser 进程里这步在 CreateEnvironment 内部完成,渲染进程拆开了:因为 context 是 Blink 造的,必须显式改造。

(4)冻结文档加载,直到 preload 跑完。

electron_renderer_client.cc:160-161

	// Before we load the node environment, let's tell blink to hold off on
	// loading the body of this frame.  We will undefer the load once the preload
	// script has finished.  This allows our preload script to run async (E.g.
	// with ESM) without the preload being in a race
	render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
	blink::LoaderFreezeMode::kStrict);

kStrict 冻结:HTML 继续解析(preload 需要的 DOM 得有),但子资源加载停住、脚本不跑。为什么?ESM preload 是异步的——await import() 的过程中,如果没有冻结,页面自己的 <script> 会和 preload 竞争 globals(process、Buffer 刚装上就被页面脚本看到一半的状态)。冻结把"preload 先于页面脚本"从巧合变成保证。

解冻回调链:CreateEnvironment(..., base::BindRepeating(&ElectronRendererClient::UndeferLoad, ...))——这个 on_app_code_ready 回调被塞进 process.appCodeLoaded,lib/renderer/init.ts:128 的 onPreloadsLoaded(6.10 节)最后调用它。preload 跑完 → JS 调 appCodeLoaded() → C++ UndeferLoad → SetDefersLoading(kNone) → 页面开始加载。 一条从 JS 顶回 Blink 的完整控制链。

(第 5 章讲过 browser 进程的 appCodeLoaded:同一机制,两端消费不同——browser 端是 JoinAppCode 的退出条件,renderer 端是文档解冻。)

(5)CreateEnvironment(isolate, renderer_context, nullptr, 0, ...)——platform 传 nullptr!

browser 进程传的是 js_env_->platform()(node::MultiIsolatePlatform)。渲染进程传 nullptr。为什么?

因为渲染进程的 V8 平台是 Blink 的(blink::V8Platform,在渲染进程启动早期就 InitializePlatform 了)。MultiIsolatePlatform 的作用是把 V8 后台任务和 isolate 绑定的 uv loop 对接——渲染进程根本不用这套(Blink 的平台对接 Chromium 的线程池)。node::CreateIsolateData 的 platform 参数允许为空:Node 在 Environment 里做异步任务调度(ToAsyncRequest/RequestInterrupt)时会判空走降级路径。传 nullptr 是"告诉 Node:这个进程里你只是房客,平台的事别管"。

(6)force_context_aware = true 和 unhandled_rejections = "warn-with-error-code"。

electron_renderer_client.cc:172-173

	// If we have disabled the site instance overrides we should prevent loading
	// any non-context-aware native module.
	env->options()->force_context_aware = true;

	// We do not want to crash the renderer process on unhandled rejections.
	env->options()->unhandled_rejections = "warn-with-error-code";

force_context_aware:原生模块(.node)必须声明支持多 context(NODE_MODULE_INIT 的 context-aware 版),否则拒绝加载。渲染进程里 context 生命周期混乱(每个 frame 一个),不支持多 context 的原生模块会在 frame 销毁后带着悬垂指针活着——所以一刀切禁掉。

unhandled_rejections 设为"警告 + 非零 exit code"而不是默认的崩溃:渲染进程崩溃的代价是整页白屏,一个未处理的 rejection(可能来自第三方库)不值得。

(7)preload 路径经 mojo 推送,不走同步 IPC。

electron_renderer_client.cc:193-195

	// The preload scripts to run, pushed by the browser ahead of the navigation
	// (see WebContents::MaybeSendRendererStartupData) so renderer init does not
	// have to ask for them with a synchronous IPC.
	...
	process_dict.SetHidden(
		"preloadPaths",
		v8::Array::New(isolate, preload_paths.data(), preload_paths.size()));

浏览器进程在导航前就把 preload 列表推过来(ElectronApiServiceImpl 的 startup_data),渲染进程初始化时直接从内存拿。注释点明动机:避免同步 IPC(渲染进程初始化路径上的一次 GetPreloadPaths 往返会阻塞整个启动关键路径)。SetHidden = 私有符号,JS 侧用 v8Util.getHiddenValue(process, 'preloadPaths') 取(6.10 节)。

(8)LoadEnvironment + 异步启动 embed 线程。

electron_renderer_client.cc:202-209

	node_bindings->LoadEnvironment(env.get());

	// This context may have been created from inside a script (e.g. the opener's
	// window.open() call), so give the loop its first run from a fresh task.
	base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
	FROM_HERE, base::BindOnce(
					[](base::WeakPtr<FrameEnvironment> frame_env) {
					if (!frame_env)
						return;
					frame_env->node_bindings->PrepareEmbedThread();
					frame_env->node_bindings->StartPolling();
					},
					weak_frame_env));

LoadEnvironment 同步执行 renderer_init bundle(6.10 节)——CJS preload 在这里就跑完了。但 embed 线程的启动被推迟到下一个 task。注释给了场景:window.open() 的 opener 脚本还在栈上——此刻 DidCreateScriptContext 是从 Blink 脚本执行中调进来的,直接 StartPolling(它先手动跑一轮 UvRunOnce)会在 JS 执行中途插入 uv 回调,重入当前脚本。推迟到 fresh task,保证 UvRunOnce 永远不在别的 JS 栈顶执行。

6.9.3 WillReleaseScriptContext:先停 poll 再销毁

electron_renderer_client.cc:225

void ElectronRendererClient::WillReleaseScriptContext(...) {
	node::Environment* env = GetEnvironment(render_frame);
	if (!env || env->context() != context)
	return;
	gin_helper::EmitEvent(isolate, env->process_object(), "exit");

	auto iter = environments_.find(render_frame);
	std::unique_ptr<FrameEnvironment> frame_env = std::move(iter->second);
	environments_.erase(iter);

	// Park the embed thread so FreeEnvironment's uv_run is the loop's only user.
	frame_env->node_bindings->set_uv_env(nullptr);
	frame_env->node_bindings->StopPolling();
	frame_env->electron_bindings->EnvironmentDestroyed(env);
	// Freeing the environment runs its loop, i.e. enters Node.js.
	util::ExplicitMicrotasksScope microtasks_scope(context->GetMicrotaskQueue());
	frame_env->environment.reset();
}

第一句 EmitEvent(..., "exit")——process 对象的 exit 事件,与 Node 的 process.on('exit') 语义对齐(frame 销毁 = 该环境的进程终结)。

set_uv_env(nullptr) 在 StopPolling 之前:让已经 Post 出去的 UvRunOnce 判空直退(6.4 节第一段),不碰正在销毁的 env。

然后 environment.reset()——shared_ptr 归零,触发 env_deleter(第 5 章 5.5.6 精读过的六步 lambda)。其中 node::FreeEnvironment 内部会跑一轮 uv loop 来清 handle/请求——注释 "Freeing the environment runs its loop, i.e. enters Node.js" 说的就是这个:销毁本身会执行 JS(close 回调)。所以外面包了 ExplicitMicrotasksScope:销毁中 JS 排下的微任务要有一个合法的检查点跑掉,否则泄漏到下一个不相干的 context 里。

而 StopPolling 必须在 reset 之前的理由,web_worker_observer.cc:286 里有完整版(6.11.3),此处注释是短版:"so FreeEnvironment's uv_run is the loop's only user"——Windows 上两个消费者抢一个 IOCP 会死锁。


6.10 渲染进程 JS 侧:lib/renderer/init.ts 的五件事

180 行的 renderer_init bundle(第 3 章讲过它怎么从 lib/renderer/init.ts:11-16 编出来)。它是每个 Node-enabled frame 的 JS 起点。五件事:封 vm、改 Module.wrapper、读 preload 列表、跑 preload(CJS/ESM 两路)、删 globals。

6.10.1 封 vm(其实是警告)

lib/renderer/init.ts:11-15

const originalModuleLoad = Module._load;
Module._load = function (request: string) {
	if (request === 'vm') {
	console.warn(
	"The vm module of Node.js is unsupported in Electron's renderer process due to incompatibilities with the Blink rendering engine. Crashes are likely and avoiding the module is highly recommended. This module may be removed in a future release."
	);
	}
	return originalModuleLoad.apply(this, arguments as any);
};

没有封死,只 console.warn。vm 的实现在渲染进程里能加载,但它创建新 context 的行为与 Blink 的 context 管理冲突(Blink 认为自己拥有 isolate 里所有 context 的生死簿),崩溃概率随使用方式浮动。所以 Electron 的选择是警告但不拦——拦掉会破坏既有应用,警告至少让开发者能搜到这句话。

6.10.2 Module.wrapper:防止 preload 的 globals 被页面脚本删掉

这是 init.ts:35-38 最著名的 hack,注释有三段(Note 1/2/3):

// Make sure globals like "process" and "global" are always available in preload
// scripts even after they are deleted in "loaded" script.
//
// Note 1: We rely on a Node patch to actually pass "process" and "global" and
// other arguments to the wrapper.
//
// Note 2: Node introduced a new code path to use native code to wrap module
// code, which does not work with this hack. However by modifying the
// "Module.wrapper" we can force Node to use the old code path to wrap module
// code with JavaScript.
//
// Note 3: We provide the equivalent extra variables internally by injecting
// lib/common/node-globals.ts (see `inject` in build/bundle/bundle.mjs). If you
// add any extra variables to this wrapper please ensure to update that as well.
Module.wrapper = [
	'(function (exports, require, module, __filename, __dirname, process, global, Buffer) { ' +
	// By running the code in a new closure, it would be possible for the module
	// code to override "process" and "Buffer" with local variables.
	'return function (exports, require, module, __filename, __dirname) { ',
	'\n}.call(this, exports, require, module, __filename, __dirname); });'
];

要防的问题:preload 跑完后,页面脚本(或框架)把 global.process、global.Buffer 删了。而 preload 脚本可能在之后还要被再次执行(比如 require 懒加载一个模块,模块代码里用 process)——那时 process 已经不在了。

解法:把每个模块包进双闭包。外层闭包的参数表里有 process, global, Buffer(模块代码执行时作为形参可见,哪怕全局已被删);外层闭包体里立刻 return 内层函数(参数表是标准五个)——Module._load 调用的是内层,外层在编译时就先执行了、把当时的 globals 捕获进闭包。

三段 Note 各对应一个补丁/机制:

  • Note 1:"a Node patch to actually pass process and global to the wrapper"——Node 原版的 wrapper 只有五个参数。patches/node/ 里有对应补丁让 Module.prototype._compile 传 Node 的实参进去。(练习 6.6:在 patches/node/.patches 里找到这个补丁。)
  • Note 2:"native code to wrap module code"——Node 新版本用 C++ 实现(vm.compileFunction 的内部路径)做模块包装,改 Module.wrapper 这个 JS 字符串不影响它。但 Electron 检测到 wrapper 被改就退回旧的 JS 包装路径——"modifying the Module.wrapper forces Node to use the old code path" 是反向利用了这个回退机制。
  • Note 3:打包配套。node-globals.ts:4 会被 bundle.mjs 的 inject 机制注入每个 bundle(第 3 章 3.11 讲过 bundle 的 inject),让"编译期可静态分析"的等价变量存在。wrapper 加新变量必须同步改它——这是给 Electron 贡献者的维护提示。

6.10.3 nodeIntegration 决定 globals 的命运

lib/renderer/init.ts:58-65

const nodeIntegration = mainFrame.getWebPreference('nodeIntegration');

if (nodeIntegration) {
	const { makeRequireFunction } = require('internal/modules/helpers');
	global.module = new Module('internal/electron/js2c/renderer_init');
	global.require = makeRequireFunction(global.module) as NodeRequire;
	...
	// file: 协议时 __filename = html 路径;否则指向 electron.asar 的假路径
	if (window.location.protocol === 'file:') { ... }
	else {
	// For backwards compatibility we fake these two paths here
	global.__filename = path.join(process.resourcesPath, 'electron.asar', 'renderer', 'init.js');
	...
	}
	// Redirect window.onerror to uncaughtException.
	window.onerror = function (...) { ... };
}

开了 nodeIntegration,页面主 world 拿到完整的 require/module/__filename/__dirname。__filename 的语义按 file: 协议分叉:本地文件就指向 html,远程页面则给一个指向 electron.asar 的假路径(向后兼容:老代码假定 __dirname 一定存在)。

注意 window.onerror 的改写:global.process.listenerCount('uncaughtException') > 0 时把 window 的错误转投给 process——让 preload/页面在 Node 里注册的处理器接得住 window 的错误。返回 true 表示"已处理",Blink 不再走默认的 console 输出。

6.10.4 删 globals 的时机:一个真实的 bug(#46142)

lib/renderer/init.ts:125

// In a non context-isolated renderer without Node integration, the Node
// globals (process, Buffer, ...) must be removed from the renderer's main
// world before the page's own scripts run, but only after the preload
// scripts have had a chance to use them. The 'loaded' event fires on the
// next tick after init returns, which is before any async ESM preload
// finishes executing, leaving its code with no `process` (#46142). So we
// instead schedule the deletion explicitly once preloads are loaded.
const shouldDeleteRendererNodeGlobals = !nodeIntegration && !process.contextIsolated;

需求有两个互相拉扯的约束:页面脚本开跑前必须删(安全:没开 nodeIntegration 的页面不能看到 process);preload 跑完后才能删(preload 要用)。

曾经的方案是监听 Node 的 loaded 事件(init 返回后的下一个 tick)删——但 ESM preload 是异步的,loaded 的时候 ESM preload 还在 await import() 半路,process 先被删了,preload 的剩余代码直接崩。#46142。

现在的方案:onPreloadsLoaded 显式触发——CJS preload 同步跑完就触发;ESM preload 在 runEntryPointWithESMLoader 的 .finally 里触发(无论成败)。删法是物理 delete:

lib/renderer/init.ts:130-137

const onPreloadsLoaded = () => {
	if (shouldDeleteRendererNodeGlobals) {
	delete (global as any).process;
	delete (global as any).Buffer;
	delete (global as any).setImmediate;
	delete (global as any).clearImmediate;
	delete (global as any).global;
	delete (global as any).root;
	delete (global as any).GLOBAL;
	}
	appCodeLoaded!();
};

七个名字:process、Buffer、setImmediate/clearImmediate(Node 特有,页面不该有)、global/root/GLOBAL(Node 的 globalThis 别名,浏览器的漏洞利用经典入口——root 和 GLOBAL 是老 Node 的遗留别名,攻击者常用它们探测"这是不是个带 Node 的页面")。删完调 appCodeLoaded()——解冻文档加载(6.9.2 第 4 步的闭环)。

6.10.5 preload 的两条加载路径

lib/renderer/init.ts:145-152

const preloadPaths: string[] = v8Util.getHiddenValue(process, 'preloadPaths') ?? [];
const cjsPreloads = preloadPaths.filter((p) => path.extname(p) !== '.mjs');
const esmPreloads = preloadPaths.filter((p) => path.extname(p) === '.mjs');
if (cjsPreloads.length) {
	for (const preloadScript of cjsPreloads) {
	try {
	Module._load(preloadScript);
	} catch (error) {
	console.error(`Unable to load preload script: ${preloadScript}`);
	ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, error);
	}
	}
}
if (esmPreloads.length) {
	runEntryPointWithESMLoader(async (cascadedLoader: any) => {
	for (const preloadScript of esmPreloads) {
	await cascadedLoader.import(pathToFileURL(preloadScript).toString(), undefined, Object.create(null))
		.catch((err: Error) => { ... ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, ...); });
	}
	}).finally(onPreloadsLoaded);
} else {
	onPreloadsLoaded();
}

.mjs 后缀决定一切(和 app_package.cc 判 ESM 的规则一致——第 5 章 5.6)。两个细节:

  • preload 报错不上抛:CJS 用 try/catch,ESM 用 .catch——preload 挂了进程继续跑(页面还是要加载的),错误经 ipcRendererInternal.send(BROWSER_PRELOAD_ERROR) 送到主进程报给开发者。preload 是"增强"不是"入口",这个容错哲学和主进程的 init.ts(throw new Error('Unable to find a valid app') 直接崩)刻意相反。
  • CJS 路径不包 try 的对立面:每个 CJS preload 单独 try——一个 preload 崩不能挡住后面的。ESM 循环里 await ... .catch 逐个吞错同理。

6.11 Worker 与 Worklet:WebWorkerObserver

Blink 的 Web Worker 跑在独立线程上,每个线程一个 isolate(不是进程!)。Node 在 worker 线程里怎么活?

6.11.1 谁在 worker 线程里出现

WorkerHasNodeIntegration(electron_renderer_client.cc:241 起)划了边界:

	// We do not create a Node.js environment in service or shared workers
	// owing to an inability to customize sandbox policies in these workers
	// given that they're run out-of-process.
	// Also avoid creating a Node.js environment for worklet global scope
	// created on the main thread — those share the page's V8 context where
	// Node is already wired up.
	if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope() ||
	ec->IsMainThreadWorkletGlobalScope())
	return false;

Service worker / shared worker 跑在专用的服务进程里(out-of-process),Electron 无法定制那里的沙箱策略(fuses、contextIsolation 的执行点都不适用)——干脆不给 Node。主线程 worklet 共享页面 context,不用另建。

剩下的三种拿 Node:dedicated worker(每线程一个)、off-main-thread worklet(Audio/Paint/Animation/SharedStorage——Blink 的 WorkletThreadHolder 会池化线程)。池化引入了一个新的生命周期问题,IsPooledWorkletContext 的注释直说:

// Returns true if `context` belongs to a worklet that runs on a thread
// pooled by Blink's WorkletThreadHolder, where the worker thread can be
// reused for multiple worklet contexts. For these scopes the
// WebWorkerObserver and its NodeBindings must outlive the v8::Context so
// the next pooled context can reuse them — Node.js cannot be re-initialized
// on the same thread (the allocator shim only loads once). See callers of
// blink::WorkletThreadHolder in third_party/blink for the authoritative
// list.

"Node.js cannot be re-initialized on the same thread (the allocator shim only loads once)"——Node 的进程级初始化里有 allocator shim(把 malloc 换成 Node 的分区分配器一类的操作),只能做一次。线程池复用线程时,Node 的 per-process 状态已在,不能重新 InitializeOncePerProcess。所以 WebWorkerObserver + 它的 NodeBindings 必须比 context 活得久,下一个 context 来了复用它们。

6.11.2 首个 context:InitializeNewEnvironment

web_worker_observer.cc:73-79

void WebWorkerObserver::WorkerScriptReadyForEvaluation(
	v8::Local<v8::Context> worker_context) {
	active_context_count_++;

	if (environments_.empty()) {
	// First context on this thread - do full Node.js initialization.
	InitializeNewEnvironment(worker_context);
	} else {
	// Thread is being reused (AudioWorklet thread pooling). Share the
	// existing Node.js environment with the new context instead of
	// reinitializing, which would break existing contexts on this thread.
	ShareEnvironmentWithContext(worker_context);
	}
}

注意计数器 active_context_count_——池化线程同时有多个 context 活着(一个 AudioWorklet 线程可能并行服务多个 worklet context),只有归零才销毁。这是引用计数管理"一个 loop 服务多个 context"的载体。

InitializeNewEnvironment 的步骤(web_worker_observer.cc:95-124)和 renderer 主 frame 几乎一致:v8::MicrotasksScope(kDoNotRunMicrotasks)(Bootstrap 期间不跑微任务——worker 的 kScoped 策略下,进出的 scope 会触发自动 flush,显式关掉)、PrepareEmbedThread、node::InitializeContext、CreateEnvironment(isolate, worker_context, nullptr)(platform 同样是 nullptr——Blink 的平台)、unhandled_rejections = "warn-with-error-code"(worker 崩了渲染进程也跟着遭殃,所以同样不崩)、LoadEnvironment、StartPolling。

6.11.3 销毁:ContextWillDestroy 的四道防线

归零路径的代码(web_worker_observer.cc:198-285)信息密度极高,四个防御依次出现:

防线一:不用 gin_helper::EmitEvent 发 exit。

	// Emit the "exit" event on the process object. We avoid using
	// gin_helper::EmitEvent here because it goes through
	// CallMethodWithArgs, which creates a node::CallbackScope. During
	// worker shutdown (PrepareForShutdownOnWorkerThread), the
	// CallbackScope destructor's InternalCallbackScope::Close() tries to
	// process ticks and microtask checkpoints, which can SEGV because the
	// worker context is being torn down by Blink.

EmitEvent 的正常路径会创建 node::CallbackScope,其析构要跑 tick + 微任务检查点——但此刻 Blink 正在拆 context,那些检查点一跑就 SEGV。所以手工调 process.emit('exit'):拿到 emit 函数、手动 Call、手包 MicrotasksScope(kDoNotRunMicrotasks)(kScoped 策略下 V8 的 DCHECK 要求 scope 存在,但用 kDoNotRun 而不是 kRunMicrotasks——不跑)、手包 TryCatch。

防线二:异常不能漏回 Blink。

	// We are mid-teardown and about to destroy the worker's
	// node::Environment, so we cannot let an exception thrown by an
	// 'exit' listener propagate back into Blink (it would assert in
	// V8::FromJustIsNothing on the next call into V8). Log it and
	// explicitly reset the TryCatch so the destructor doesn't rethrow.

exit 监听器(用户 JS)可能 throw。此刻往上抛会把异常带回 Blink 的 C++ 栈,而那条栈上后续的 FromJust() 调用会 assert。所以 LOG(ERROR) + try_catch.Reset()(显式吞掉,防止 TryCatch 析构 rethrow)。

防线三:先 join embed 线程,再销毁 Environment(Windows IOCP 死锁)。

web_worker_observer.cc:277-278

	// Prevent UvRunOnce from using the environment after it's destroyed.
	node_bindings_->set_uv_env(nullptr);

	// Stop the embed thread before destroying environments. The embed
	// thread's PollEvents and FreeEnvironment's uv_run both compete for
	// completions on the same libuv event loop; on Windows (IOCP) this
	// race can deadlock. Joining the embed thread first eliminates the
	// contention so FreeEnvironment's uv_run can drain handles cleanly.
	// For pooled worklets the thread is restarted in
	// InitializeNewEnvironment via PrepareEmbedThread + StartPolling.
	node_bindings_->StopPolling();

6.9.3 的短版注释在这里有完整因果:PollEvents(GetQueuedCompletionStatus)和 FreeEnvironment 内部的 uv_run(也是 GetQueuedCompletionStatus)是同一 IOCP 的两个消费者,销毁期并发消费会死锁。IOCP 的死锁场景:一个在等完成包,另一个把包取走了又以不同状态归还……总之 join 掉 embed 线程,让 FreeEnvironment 独占。

防线四:最后一个 context 的归属判断。

	} else {
	// Other contexts still use the shared environment. Just unassign
	// this context from the environment if it's not the primary context
	// (the primary context must stay assigned because env->context()
	// references it, and UvRunOnce enters that context scope).
	if (context != env->context()) {
	env->UnassignFromContext(context);
	}
	// If the destroyed context IS the primary context, we leave the env
	// assigned to it. The env's PrincipalRealm holds a Global<Context>
	// reference that keeps the V8 context alive even though Blink has
	// torn down its side. This is safe because UvRunOnce only needs
	// the V8 context scope, not Blink-side objects.

非归零路径:环境还要给其他 context 用。被销毁的 context 从 env 的 context 注册表里摘掉——除非它是 primary。primary context 被 env 的 Global<Context> 引用着,强行为零才安全;Blink 拆的是它自己那侧的对象(DOM/WorkerGlobalScope),V8 context 本体还活着,UvRunOnce 的 Context::Scope 只需要 V8 侧——所以"半死不活"是安全的。这种分层死亡(Blink 侧死、V8 侧由 Node 养着)是 embedder 责任划分的教科书案例。

6.11.4 复用:ShareEnvironmentWithContext

新 context 来到已初始化的线程(web_worker_observer.cc:126-196):

	// Assign the existing Node.js environment to this new context so that
	// node::Environment::GetCurrent(context) returns the shared environment.
	env->AssignToContext(worker_context, env->principal_realm(),
					node::ContextInfo("electron_worker"));

核心一行:AssignToContext——Node 的 Environment 支持关联多个 context(正是为这种共享场景设计的 API)。然后是 globals 的手工搬运:

	// Script in the original context can redefine these globals with accessors
	// that throw, so read them defensively and fall back to the environment's
	// own process object / undefined rather than crashing the worker.
	v8::TryCatch try_catch(isolate);
	...读 process/require/Buffer,失败则 fallback...

防御读取:原始 context 的 JS 可能把这些 global 改成了会 throw 的 accessor(恶意或巧合),直接 Get 会把异常留在 isolate 里毒化后续操作,所以包 TryCatch、读不到就 fallback。

然后是 Blink fallback 的六个名字:

web_worker_observer.cc:200-202

	// Ensure the Blink implementations of fetch and friends are available in
	// the new pooled context. Node.js no longer touches these globals when
	// kNoBrowserGlobals is set, but some worklet global scopes do not expose
	// them at all; fall back to the original context's bindings in that case.
	for (const std::string_view key :
	{"fetch", "Response", "FormData", "Request", "Headers", "EventSource"}) {
	// First, check if the new context has a working Blink version.
	...没有就从原 context 复制...
	}

新 worklet context 可能是 Blink 的极简 scope(比如 AudioWorkletGlobalScope 没有 fetch)。preload/worker 代码要用——从第一个 context 复制过来。EventSource 又出现了(第 5 章 5.5.5 的主角),这不是巧合:Node 不装(kNoBrowserGlobals),Blink 的某些 scope 不给,Electron 手工补位——三不管地带由 Electron 填。


6.12 utility 进程:NodeService 的平行世界

utility 进程里的 Node 服务(node_service.cc)是 browser 进程启动链路的缩减复刻。第 2 章讲过 utility process 的进程形态,这里补 Node 侧。

node_service.cc:105

NodeService::NodeService(mojo::PendingReceiver<node::mojom::NodeService> receiver)
	: node_bindings_{
		NodeBindings::Create(NodeBindings::BrowserEnvironment::kUtility,
							uv_default_loop())},
	electron_bindings_{
		std::make_unique<ElectronBindings>(node_bindings_->uv_loop())} {

kUtility + uv_default_loop()——和 browser 进程同款起手式。

NodeService::Initialize(收到主进程 mojo 调用后)的顺序(node_service.cc:130-220):

WASM trap handler(fuse + 架构)
→ js_env_.emplace(node_bindings_->uv_loop())        ← JavascriptEnvironment,含 MultiIsolatePlatform
→ NodeSnapshotForThisProcess 判定(utility 也走快照!)
→ node_bindings_->Initialize(isolate, context)      ← InitializeOncePerProcess(utility 不关 stdio 继承)
→ ParentPort::Initialize(params->port)              ← MessagePort 绑定(暂不 resume)
→ NetworkChangeNotifier::CreateIfNeeded()
→ CreateEnvironment(isolate, context, js_env_->platform(), ...)   ← platform 非 nullptr!
→ if (context.IsEmpty()) context Enter               ← 快照路径
→ electron_bindings_->BindTo(...)
→ node_env_ 设置、unhandled_rejections 保持默认(utility 崩溃是合法语义!)
→ LoadEnvironment → utility_init bundle → JoinAppCode 无(utility 没有)
→ js_env_->CreateMicrotasksRunner()                  ← utility 也有 MicrotasksRunner
→ node_bindings_->PrepareEmbedThread() + StartPolling()

与 browser 的三个关键差异:

差异一:unhandled_rejections 不改。 SetUpIsolate 里 utility 进程不装 should_abort_on_uncaught_exception_callback = return false(browser/renderer 都装了)。注释(node_bindings.cc:774):"For utility process we expect the process to behave as standard Node.js runtime and abort the process with appropriate exit code depending on a handler being set for uncaughtException event."——utility 进程的未捕获异常会真的崩进程,和标准 Node 一致。设计动机:utility process 是 Node 的官方继任者(第 2 章),行为向 Node 看齐是它的产品承诺。

差异二:stdio 继承被关。 NodeBindings::Initialize 里 if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= kEnableStdioInheritance——第 5 章 5.5.4 讲过:utility 进程的 stdio 是和主进程的管道,spawn 子进程时不能继承。

差异三:ParentPort 的 resume 权交给 JS。 注释:

	// ParentPort is a cppgc-managed wrappable, so it must be created after the
	// V8 isolate (and its cppgc heap) exists. The connector is created paused and
	// is not resumed until the entry script calls parentPort.start() during
	// LoadEnvironment below, so binding the port here changes no observable
	// behavior.

process.parentPort.start() 是用户 API——消息泵的启动权归用户脚本。这保证 onmessage 注册完成前不会丢消息(paused 队列缓存)。这是 worker 语义(worker.postMessage 的 MessagePort)在 utility 进程的移植。


6.13 ESM:两个 loader 的仲裁

最后一块拼图。渲染进程里,import() 由谁解析?Blink 和 Node 各有一套完整的 ESM loader(URL 解析、CSP 检查 vs 文件系统解析、node_modules 查找),一个 isolate 只能注册一个 HostImportModuleDynamicallyCallback。

Electron 的答案(node_bindings.cc:245-332):一个分诊台。

enum class ESMHandlerPlatform { kBlink, kNodeJS, kNone };

SelectESMHandlerPlatform(context, host_defined_options) 的判定规则(按顺序):

  1. 没有 Node Environment 的 context(沙箱渲染进程 / isolated world 之外)→ kBlink,或者纯沙箱 → kNone(import() 返回空 promise,Chromium 沙箱里不支持)。
  2. browser / utility 进程 → kNodeJS(Node 全权)。
  3. 渲染进程、没有 frame 的 context → kBlink。
  4. 开了 contextIsolation 的 frame:world 是 ISOLATED_WORLD_ID → kNodeJS(preload 用 Node 的 loader 解析本地文件);否则 kBlink(页面用浏览器的)。
  5. 没开 contextIsolation、有 nodeIntegration:按 host_defined_options 的长度区分——

node_bindings.cc:282-288

	// Since the routing is based on the `host_defined_options` length -
	// make sure that Node's host defined options are different from Blink's.
	static_assert(
	static_cast<size_t>(node::loader::HostDefinedOptions::kLength) !=
	blink::ReferrerScriptInfo::HostDefinedOptionsIndex::kLength);

	// Use Node.js resolver only if host options were created by it.
	auto options = v8::Local<v8::FixedArray>::Cast(raw_host_defined_options);
	if (options->Length() == node::loader::HostDefinedOptions::kLength) {
	return ESMHandlerPlatform::kNodeJS;
	}
	return ESMHandlerPlatform::kBlink;

妙处:同一 world 里 Node 的模块(preload import 进来的)和页面的模块共存,每个 v8::Module 对象身上带着编译者留下的 host_defined_options(一个 FixedArray)。static_assert 强制两个 loader 的 options 数组长度永远不相等——于是"这个模块是谁编的"在 import() 传播链上可判:从 Node 的模块出发的动态 import 走 Node 的 loader(文件路径语义),从页面模块出发的走 Blink(URL + CSP 语义)。同 world 双 loader,按调用来源分诊。

这个 static_assert 是 Electron 的补丁强制的(第 4 章提到 Blink 的 blink_local_frame patch 系列里有一条 revert 上游"统一 HostDefinedOptions"的 CL——上游一旦改变 options 长度约定,这个分诊就失效,所以必须 revert)。三条线(第 4 章补丁、本章机制、第 15 章 contextIsolation)在这里交汇。

HostImportModuleWithPhaseDynamically(source phase imports,第 5 章讲过的 --no-js-source-phase-imports)额外检查 import_phase == kEvaluation——Node 只支持 evaluation phase,非 evaluation 的回 Blink。


6.14 三种宿主形态对照 + 十问速查

维度browser 进程renderer(主 frame)worker / workletutility 进程
loop 来源uv_default_loop()uv_default_loop()(主 frame 借用)自建(owned_loop_)uv_default_loop()
V8 平台Node MultiIsolatePlatformBlink 的平台(CreateEnvironment platform=nullptr)Blink 的(nullptr)Node MultiIsolatePlatform
context 来源node::NewContext / 快照Blink 创建,Node 改造(InitializeContext)Blink 创建快照 / NewContext
微任务策略kExplicit(恒定)kScoped↔kExplicit(按入口切换)按入口切换kExplicit(恒定)
MicrotasksRunner有(TaskObserver)无(Blink 的 EndOfTaskRunner)无有
embed 线程1 个主 frame 1 个 + 每 iframe 一个每线程 1 个1 个
appCodeLoadedJoinAppCode 的退出条件文档解冻(UndeferLoad)无无(entry 自己控制)
未捕获异常弹框(GUI)console.error 级崩(worker 隔离)崩进程(Node 语义)
ESM loaderNode按 world/options 分诊按 options 分诊Node

十问:

Q1:主进程里 setTimeout(fn, 0) 的完整路径? JS → uv_timer_start(主线程)→ interrupt 叫醒 embed 线程 → PollEvents 立刻返回(重读 timeout=0)→ PostTask(UvRunOnce) → 主线程 uv_run(NOWAIT) → timer 回调执行。一共两次线程切换。

Q2:为什么 setImmediate 和 setTimeout(fn,0) 的顺序在 Electron 主进程里可能和纯 Node 不同? 纯 Node 按"check phase 先于 timer phase"的固定顺序;Electron 里两者都靠 embed 线程唤醒后的一次 uv_run(NOWAIT) 执行,谁在 handle 队列里排前面谁先——uv_run 的内部 phase 顺序(uv__run_check 在 uv__run_timers 之后……实际 uv 顺序是 timers→pending→idle→prepare→poll→check→close)依然成立,但"哪一次 UvRunOnce 处理谁"受 PostTask 时序影响。

Q3:process.exit() 时 embed 线程怎么样了? PostMainMessageLoopRun → node_env_.reset() → ~NodeBindings → StopPolling → join。嵌入线程先死,Node 后死——顺序由 ~NodeBindings 保证。

Q4:原生模块里自己调 uv_run(UV_RUN_DEFAULT) 会怎样? 会阻塞主线程直到 loop 空(dummy handle 挡着,永远不空——死循环!)。UV_RUN_NOWAIT 才是安全的。这是原生模块作者的常见翻车点。

Q5:iframe 里 require('electron') 为什么拿不到? ShouldLoadPreload(renderer_client_base.cc:241)的判定是 (is_main_frame || is_devtools || node_integration_in_sub_frames) && !IsWebViewFrame(...)——默认 iframe 连 Node 环境都不建(DidCreateScriptContext 直接 return),require 这个函数本身就不存在。只有显式开启 nodeIntegrationInSubFrames 才有(第 15 章展开)。

Q6:为什么 --js-flags 在渲染进程要重设 --no-freeze-flags-after-init? PostIOThreadCreated(electron_renderer_client.cc:73):Blink 初始化时会冻结 flag,Node 在渲染进程里初始化得晚,再设一次防止"写冻结 flag"。和 browser 进程在 JavascriptEnvironment::Initialize 里 prepend 是同一个 flag、两个注入点。

Q7:renderer 崩溃时 process.on('exit') 能跑吗? 正常销毁(导航)走 WillReleaseScriptContext → EmitEvent('exit');进程崩溃(OOM/沙箱 kill)什么都不跑——和 Node 的硬崩语义一致。

Q8:ELECTRON_RUN_AS_NODE 进程有 embed 线程吗? 没有。node_main.cc:148 走纯 Node 路径,主线程直接 uv_run(UV_RUN_DEFAULT) 阻塞——不需要信使。

Q9:utility 进程 spawn 子进程,子进程的 stdout 去哪了? 按 stdio 选项配置(第 2 章);关键在 kEnableStdioInheritance 被关——utility 自己的管道不会被孙进程继承。

Q10:为什么 PollEvents 不直接调用 uv_run(UV_RUN_ONCE)? UV_RUN_ONCE 会处理事件(执行回调)——那需要在 embed 线程跑 JS,而 isolate 锁在主线程。PollEvents 只能"等",不能"跑"。


6.15 本章小结

七条结论。

结论一:Electron 的 Node 集成是一份"等待的外包"协议。 执行必须留在主线程(isolate 单线程),等待外包给 embed 线程,两者以 semaphore + PostTask 严格交替——"one post per UvRunOnce"。这个协议的每一次例外(if (!env) return 的早退、StopPolling 的双重打断)都有专门的生命周期管理兜底。

结论二:跨线程 poll 的三平台方案由"内核是否消耗事件"决定。 Linux epoll 会把事件投递给某个等待者 → 造镜像层;macOS poll 只测状态 → 直守;Windows IOCP 必然取走 → 取出放回。同一抽象(PollEvents),三种实现,30 行以内。

结论三:stale timeout 是拆分 loop 的固有病,interrupt 是它的药。 uv_backend_timeout 在读和用之间永远有窗口。上游的 UV_LOOP_INTERRUPT_ON_IO_CHANGE 保证任何 IO 变化都纠正等待;Electron 的 suspend/resume 把"poller 明在睡觉"的窗口里的药也省了。整个补丁只服务于这一件事。

结论四:微任务策略不是配置,是谈判。 Node 要 kExplicit,Blink 要 kScoped,同 isolate 共存的方式是"按入口切换":browser/utility 定型为 kExplicit + MicrotasksRunner 每次 task 后补 Node 检查点;renderer 在 uv 回调入口用 ExplicitMicrotasksScope 临时切换、栈式恢复。issue #20013 的注释记录了裁判权从"双方抢"到"全归 Node"的一次真实返工。

结论五:渲染进程的 Node 是"每个 Environment 一套班子"。 一个 isolate、几十个 context、每个 Node 环境自带 loop + embed 线程 + bindings。主 frame 借默认 loop 是唯一共享,其余全部隔离。销毁按计数器归零触发,Windows IOCP 的双消费者死锁逼出了"先 join 再 Free"的铁律。

结论六:worklet 线程池暴露了 Node 的不可重入性。 allocator shim 只装载一次 → 同线程不能二次 InitializeOncePerProcess → 观察者与 NodeBindings 必须比 context 长寿 → ShareEnvironmentWithContext 半启动 + globals 手工搬运 + Blink fallback 六件套。复用一套 Node 环境的成本清单,全部写在 web_worker_observer.cc 的注释里。

结论七:utility 进程是 Node 语义的回归。 同一套 NodeBindings/JavascriptEnvironment 基建,但 kUtility 的每个分叉(stdio 不继承、异常真崩、无 JoinAppCode)都把行为推回标准 Node。它是 Electron 偿还"嵌入税"的账户——在能不嵌入的地方就不嵌入。


6.16 练习题

练习 6.1(入门) 在主进程写一个每 50ms 打点一次的 setInterval,运行你的应用但不碰它。用 process.hrtime.bigint() 记录实际间隔。观察系统繁忙(拖动窗口)vs 空闲时打点间隔的差异,用本章的协议解释。

练习 6.2(入门) ELECTRON_RUN_AS_NODE=1 ./your-app -e "setTimeout(()=>console.log('done'),10); while(1){}" 会怎样?(提示:纯 Node 路径没有 Chromium pump,while(1) 会饿死一切。)对比 Electron 模式下同样代码的行为。

练习 6.3(进阶) 画出 StopPolling 与"主线程最后一次 UvRunOnce 的 sem_post"交错时,信号量计数的完整时间线,标出"残留计数 1"发生的帧。然后解释 while (uv_sem_trywait(...) == 0) {} 为什么用 trywait 而不是 wait。

练习 6.4(进阶) 阅读 6.5.2 的单核 IOCP 修复。在单核 Windows 机器(或 1 vCPU 虚机)上验证:不打这个补丁时,把 NumberOfConcurrentThreads 设为 1,观察 embed 线程的 CPU 占用(用 Process Explorer 看线程级占用)。

练习 6.5(进阶) 6.4 节说 r == 0 时 QuitWhenIdle 退出"当前" RunLoop。构造一个主进程场景证明 dummy handle 的存在使这行永远走不到(提示:数一数 uv_run(NOWAIT) 的活跃 handle 计数),然后讨论:如果真的走到了,行为对不对?

练习 6.6(进阶) 在 patches/node/.patches 里找到实现 Module.wrapper 六参数版(Note 1)的补丁,读它的 diff。列出 Node 原版 wrapper 与 Electron 版的差异,以及 Node 新的"native wrapping"路径如何检测 wrapper 被改而回退。

练习 6.7(深入) 6.8.3 的 MicrotasksRunner::DidProcessTask 用 node::CallbackScope 做 flush。写一个实验:主进程里在一个非 Node 语境的 Chromium 回调(比如 app.on('browser-window-focus') 的触发路径)里 resolve 一个 promise,验证微任务确实在该 task 结束时跑(用 process._tickCallback 相关诊断或 async_hooks 观察顺序)。

练习 6.8(深入) 6.11.3 的"防线一"说 EmitEvent 在 worker 销毁期会 SEGV。读 gin_helper::event_emitter_caller.cc 的 CallMethodWithArgs,找出它创建 CallbackScope 的具体行,解释为什么其析构的 InternalCallbackScope::Close() 会碰到已拆的 context。

练习 6.9(挑战) 实现一个"最小 Electron":写一个 C++ 程序,创建 uv loop、起 embed 线程、把 UvRunOnce 挂到 base::MessageLoop 的 task 上,跑通一个 uv timer。不能用 NodeBindings(自己抄结构),验证你对协议的理解。做完后回答:哪里最容易写错?

练习 6.10(挑战) 6.13 的 static_assert 保证两个 loader 的 options 长度不同。找到这个 static_assert 引用的两个常量的定义(一个在 electron_node/src,一个在 Blink),计算它们的值。然后阅读第 4 章提到的 revert 补丁,解释上游 CL 想做什么、为什么对 Electron 是灾难。


6.17 下一章预告

第 7 章《gin 绑定层:C++ 对象如何在 JS 里活着一辈子》接住本章的三条尾巴:

尾巴一:6.10.2 的 Module.wrapper 依赖"a Node patch to actually pass process and global"。那个补丁属于第 4 章的 node 补丁集,但它修改的 wrapper 代码最终服务于 gin 世界——第 7 章讲 _linkedBinding(process._linkedBinding('electron_common_v8_util'))这套"原生模块注册表"怎么把 C++ 的 v8_util.cc:91 变成 JS 可 require 的东西。

尾巴二:6.9.2 的 process_dict.SetHidden("preloadPaths", ...) 和 JS 侧的 v8Util.getHiddenValue。Hidden value(v8::Private)是 gin_helper 在"不想被用户 JS 看见"的通道上的核心工具,第 7 章展开它的实现与坑。

尾巴三:6.11.3 的"半死不活"——env 的 Global<Context> 养着 V8 context。v8::Global 的引用语义、gin::ContextHolder、以及 CleanedUpAtExit 的"最后清理"协议,都是第 7 章"对象生命周期"的主角。

一句话预告第 7 章的立论:Electron 的 API 表面是 JS,本体是 C++;gin 是两者之间的海关。海关的规则决定了每个 Electron 对象从生到死的每一站。

6.18 本章源码落点索引

下列位置全部来自本仓库源码树,按实现层归集;每个 路径:行号 指向该文件中与本章论述对应的声明或实现行,可逐条复核。

  • 渲染进程 C++ 层:electron_renderer_client.h:15 electron_sandboxed_renderer_client.cc:38 electron_sandboxed_renderer_client.h:14 renderer_client_base.h:19 preload_environment.cc:33 preload_environment.h:14 electron_extensions_renderer_client.cc:14 electron_extensions_renderer_client.h:11
  •  browser_exposed_renderer_interfaces.cc:22 browser_exposed_renderer_interfaces.h:9 preload_realm_context.cc:43 preload_realm_context.h:11 preload_utils.cc:48 preload_utils.h:15 service_worker_data.cc:16 service_worker_data.h:24
  • 浏览器进程 C++ 层:javascript_environment.h:16 electron_api_ipc_handler_impl.cc:24 electron_api_ipc_handler_impl.h:18 electron_api_sw_ipc_handler_impl.cc:28 electron_api_sw_ipc_handler_impl.h:18 electron_web_contents_utility_handler_impl.cc:23 electron_web_contents_utility_handler_impl.h:15 login_handler.cc:30
  •  login_handler.h:13 network_hints_handler_impl.cc:18 network_hints_handler_impl.h:13 preload_code_cache.cc:38 preload_code_cache.h:18 preload_script.cc:27 preload_script.h:17 renderer_startup_data.cc:38
  •  renderer_startup_data.h:11
  • shell 其余实现:node_bindings_linux.h:12 node_bindings_mac.h:12 node_bindings_win.h:12 handle.h:24 thread_restrictions.h:12
  • JS 门面与运行时:asar-fs-wrapper.ts:9 ipc-renderer-internal-utils.ts:3 ipc-renderer-internal.ts:1
  • 接口契约层:electron_api_environment.cc:11