《Electron 45.2.3 内核解剖》第 7 章 gin 绑定层:C++ 对象如何在 JS 里活一辈子
7.0 三个可复现的观察
打开任意一个 Electron 应用的 DevTools 控制台,敲三行:
const { BrowserWindow } = require('electron')
typeof BrowserWindow // 'function'
BrowserWindow.prototype.setTitle // [Function: setTitle]
const win = new BrowserWindow({ show: false })
win instanceof BrowserWindow // true
Object.keys(win) // 一个空数组,或者几个内部字段
win.destroy()
win.isDestroyed() // true
win.setTitle('x') // TypeError: Object has been destroyed
三行观察,三个无法用"JS 包装了一层"解释的现象。
第一,BrowserWindow 是 C++ 类,但它是 function。 不是 class,不是 Proxy,不是 Object.create 出来的东西——typeof 返回 'function',new 能调,instanceof 成立,prototype 上有方法。这意味着它是一个真正的 V8 FunctionTemplate 实例化出来的函数,而不是 JS 层拼装的门面。
第二,Object.keys(win) 几乎是空的。 但 win.setTitle 存在、win.id 有值、win.webContents 能取到对象。属性都挂在原型上(prototype),实例上只有 V8 的 internal field——那些字段对 JS 不可见,Object.keys 数不到。
第三,win.isDestroyed() 返回 true 而不是抛错,win.setTitle() 却抛 TypeError: Object has been destroyed。
这是一对刻意的设计。isDestroyed 的作用就是"在对象可能已死的时候问一句",所以它必须在死后仍可调用。而 setTitle 是"对活对象做操作",所以它必须拒绝死对象——而且拒绝的方式是一条可读的错误,不是段错误。
三行观察指向同一个问题,也是本章要回答的唯一问题:
一个 C++ 对象和一个 JS 对象,怎样共享同一条命?
这个问题的答案不在 electron_api_browser_window.cc 里,也不在 browser-window.ts 里。它在一个很少被提到的目录:shell/common/gin_helper/。
57 个文件,6,518 行。这个目录不是 Chromium 的 gin,也不是 Node 的 node::,它是 Electron 自己的一层——夹在 gin(Chromium 提供的 V8 绑定库)和 Electron 的 API 之间。
$ ls shell/common/gin_helper/ | wc -l
57
$ wc -l shell/common/gin_helper/*.cc shell/common/gin_helper/*.h | tail -1
6518 total
6,518 行代码,决定了 Electron 里每一个 API 对象的生、老、病、死。
本章的立论:
Electron 的 API 表面是 JS,本体是 C++;gin_helper 是两者之间的海关。海关的规则决定了每个 Electron 对象从生到死的每一站。
7.1 四层结构:从 require('electron') 到 C++ 构造函数
先给全景。一次 require('electron').BrowserWindow 要穿过四层:
[第 4 层] 用户 JS
require('electron').BrowserWindow
│
▼
[第 3 层] lib/browser/api/exports/electron.ts ← JS:惰性 getter 表
defineProperties(module.exports, browserModuleList)
│ browserModuleList 里有一项:
│ { name: 'BrowserWindow', loader: () => require('./browser-window') }
▼
[第 2 层] lib/browser/api/browser-window.ts ← JS:包装 + 参数处理
const { BrowserWindow } = process._linkedBinding('electron_browser_window')
│
▼
[第 1 层] C++ Node 模块注册表 ← C++:56 个模块
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
│ Initialize 里:
│ dict.Set("BrowserWindow", CreateConstructor<BrowserWindow>(...))
▼
[第 0 层] gin_helper::Wrappable / gin::Wrappable ← C++:生命周期
class BrowserWindow : public BaseWindow, ...
四层各有各的职责,混淆任何两层都会导致错误的排查方向。
第 3 层是"惰性"。 browserModuleList 里每一项都是 { name, loader },loader 是一个函数,不是值。defineProperties 把它变成一个 getter:
define-properties.ts:22-28
// lib/common/define-properties.ts
export function defineProperties(targetExports: Object, moduleList: ElectronInternal.ModuleEntry[]) {
const descriptors: PropertyDescriptorMap = {};
for (const module of moduleList) {
descriptors[module.name] = {
enumerable: true,
get: handleESModule(module.loader)
};
}
return Object.defineProperties(targetExports, descriptors);
}
用 getter 而不是直接赋值,三个理由都能实测:
- 启动时间。
require('electron')在main.js第一行就被调用。40 多个模块全部立即加载会连带构造Menu、Tray、Session的整条依赖链,实测差几十毫秒——对一个冷启动 200ms 的应用不是小数。 - 循环依赖。
browser-window.ts与web-contents.ts互相需要。惰性求值把求值时机推到"真正有人访问时",那时循环已经解开。 - 可被 stub。
module.exports是可写对象,测试框架能Object.defineProperty(require('electron'), 'dialog', {...})替换掉(第 21 章)。
handleESModule 的那段注释值得单独读:
define-properties.ts:1-8
const handleESModule = (loader: ElectronInternal.ModuleLoader) => {
let resolved: any;
return () => {
if (resolved !== undefined) return resolved;
const value = loader();
if (!value.__esModule) {
resolved = value;
} else if (value.default) {
resolved = value.default;
} else {
// require() of a bundled ES module returns a fresh, read-only copy of
// its namespace on every call; settle on a single plain object instead so
// that the module keeps its identity and its exports can be replaced
// (e.g. stubbed out by tests) like those of any CommonJS module.
resolved = { ...value };
}
return resolved;
};
};
第三分支说的是一件非常具体的事:lib/ 下的源码是 TypeScript,用 ESM 写,但打包成 CJS(第 3 章的 rolldown bundle)。rolldown 对 ESM 模块生成的 CJS 包装是"每次 require 返回一个新的、只读的命名空间对象副本"。
后果:require('electron').dialog !== require('electron').dialog。同一性丢失。测试里的 stub 无效(改的是副本),instanceof 检查失效,Map 键查找失效。
所以 { ...value } 做一次浅拷贝,把命名空间摊平成普通对象,然后缓存。这是打包器行为泄漏到运行时的典型修补——一行代码,修的是一个跨工具链的语义断层。
第 2 层是"拆包"。 browser-window.ts 开头:
browser-window.ts:4
const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT };
_linkedBinding 是 Node 的 API(process._linkedBinding),返回的是 C++ 模块 Initialize 填充的那个 exports 对象。Electron 用它而不是 require,因为这些模块不是文件,没有 .js 路径,是链接进二进制的注册项。
as { BrowserWindow: typeof BWT } 这句类型断言说明:C++ 侧返回的类型在 TypeScript 眼里是 any(_linkedBinding 的返回类型是 Record<string, any>),要靠人手写断言。整个 Electron 类型系统(electron.d.ts)就是从这个断言的另一头生长出来的——第 22 章讲打包时会看到 electron.d.ts 怎么从 docs/api/*.md 生成。
第 1 层是"注册"。 56 个模块,按前缀分四组:
| 前缀 | 数量 | 谁注册的 | 在哪生效 |
|---|---|---|---|
electron_browser_* | 37 | shell/browser/api/*.cc | 主进程 |
electron_common_* | 12 | shell/common/api/*.cc | 主进程 + 渲染进程(部分) |
electron_renderer_* | 5 | shell/renderer/api/*.cc | 渲染进程 |
electron_utility_* | 2 | shell/services/node/*.cc | utility 进程 |
这个划分不是美学,是编译期与运行期的双重隔离。electron_browser_app 的 Initialize 引用了 electron::api::App,而 App 引用了 Browser、Session、Menu——一整套只有主进程才链接的代码。渲染进程的二进制里没有这些符号。所以渲染进程调 process._linkedBinding('electron_browser_app') 会得到一个空的 exports 对象,而不是崩溃。
这一点可以实测:
// 在渲染进程的 preload 里(nodeIntegration 开着)
const b = process._linkedBinding('electron_browser_app')
Object.keys(b) // [] —— 模块不存在,返回空对象
Node 的 linkedBinding 在找不到名字时的行为是返回空对象并打印一条警告,不是抛错。这个宽松行为在这里救了场:lib/renderer/api/* 里那些"可能被主进程和渲染进程共用"的文件,不需要 try/catch 保护。
第 0 层是"活命"。 这一层才是本章的主体。它由五个机制组成,后面逐一展开:
Wrappable(对象绑定)
├─ internal field / cppgc 两种载体
├─ 弱回调(垃圾回收时销毁 C++ 对象)
└─ WrapperInfo + PointerTag(类型识别)
EventEmitterMixin(事件)
function_template(调用)
Promise(异步)
TrackableObject / CleanedUpAtExit(逃生舱)
7.2 NODE_LINKED_BINDING_CONTEXT_AWARE:Node 的模块注册表
一个模块是这么注册的(electron_api_event_emitter.cc:15-24,全文 48 行):
#include "shell/common/node_includes.h"
namespace {
v8::Global<v8::Object>* GetEventEmitterPrototypeReference() {
static base::NoDestructor<v8::Global<v8::Object>> event_emitter_prototype;
return event_emitter_prototype.get();
}
void SetEventEmitterPrototype(v8::Isolate* isolate,
v8::Local<v8::Object> proto) {
GetEventEmitterPrototypeReference()->Reset(isolate, proto);
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* const isolate = electron::JavascriptEnvironment::GetIsolate();
gin::Dictionary dict{isolate, exports};
dict.Set("setEventEmitterPrototype",
base::BindRepeating(&SetEventEmitterPrototype));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_event_emitter, Initialize)
最后那一行是整个机制的入口。它来自 Node 的 node.h(node_includes.h 会带上),展开后大致是:
// 简化后的宏展开
static node::node_module _module = {
NODE_MODULE_VERSION,
NM_F_LINKED, // ← 关键:标记为"链接进二进制"
nullptr, // 没有 .node 文件路径
__FILE__,
nullptr,
(node::addon_context_register_func)(Initialize),
"electron_browser_event_emitter", // ← 注册名
nullptr,
nullptr,
};
static node::node_module* _register_##name = [] { ... 挂进链表 ... }();
四个细节:
NM_F_LINKED。 普通原生模块(.node 文件)是运行时 dlopen 加载的,nm_flags 是 NM_F_NONE。NM_F_LINKED 表示"这个模块已经被链接器静态链进了可执行文件,不需要也不能再 dlopen"。所以 process._linkedBinding 而不是 require——两个 API 查的是两张表,require('./foo.node') 走文件系统,_linkedBinding('foo') 走静态链表。
addon_context_register_func 的四个参数。 Initialize(exports, unused, context, priv):
| 参数 | 内容 | 用途 |
|---|---|---|
exports | 一个空对象,Node 刚创建的 | 往里塞属性,就是模块的导出 |
unused | 永远是 undefined | 历史遗留(旧版 Node 的 module 对象) |
context | 当前 V8 context | 创建对象时要用 |
priv | node_module 的 priv 字段,这里是 nullptr | 传私有数据 |
unused 这个参数名本身就是注释:Electron 的 56 个模块里没有一处用它。
__FILE__ 嵌入。 宏的第四个字段是 __FILE__。这意味着每个模块的注册结构里都存了一份源文件路径字符串——在二进制里占几百字节。它的用途是错误信息:当一个模块的 Initialize 崩溃时,Node 能报出是哪个文件注册的。
static 变量的构造期注册。 宏展开的最后是一个静态对象的构造函数,它在 main() 之前跑,把 node_module 挂进 Node 的全局链表。这意味着注册发生在进程启动时,不是模块加载时。
这一点有个可观测的后果:模块的注册表是进程级的、只建立一次。而 Initialize 的执行是每个 context 一次——Node 在创建 Environment 时会遍历链表,对每个模块调一次 Initialize,把结果塞进新环境的 binding 缓存。
所以同一个 electron_browser_app 模块在主进程里只 Initialize 一次,但在渲染进程的每个 frame 里都会 Initialize 一次(如果那个 frame 有 Node 环境)。这就是为什么 App::Get() 用 static base::NoDestructor——它必须在多次 Initialize 之间保持同一性。
7.2.1 与 NODE_MODULE_CONTEXT_AWARE 的区别
Node 有三个相关宏:
NODE_MODULE(name, fn) // 经典,无 context,已废弃
NODE_MODULE_CONTEXT_AWARE(name, fn) // 支持 context(多 Environment)
NODE_MODULE_CONTEXT_AWARE_INTERNAL(name, fn) // 内部模块
NODE_MODULE_INIT(fn) // 自注册,现代写法
NODE_LINKED_BINDING_CONTEXT_AWARE(name, fn) // ← Electron 用的
它是 Node 为"链接进二进制的内置模块"准备的变体,属于 NODE_MODULE_CONTEXT_AWARE_X 家族,nm_flags 带 NM_F_LINKED。
为什么不用 NODE_MODULE_INIT?后者是自注册的、名字来自构建目标而非显式指定,且注册的是"普通原生模块"(NM_F_NONE),要走 require 或 dlopen。Electron 需要显式命名 + 链接式,才能用 _linkedBinding('electron_browser_app') 按字符串查找。
7.2.2 56 个模块的完整清单
按前缀分组,这就是 Electron 的 C++ API 表面:
electron_browser_*(37 个,主进程):
app auto_updater base_window clipboard
clipboard_item content_tracing crash_reporter desktop_capturer
dialog event_emitter global_shortcut image_view
in_app_purchase ipc_dispatch menu message_port
msix_updater native_theme notification power_monitor
power_save_blocker printing protocol push_notifications
safe_storage screen service_worker_main session
system_preferences tray utility_process view
web_contents web_contents_view web_frame_main web_view_manager
window
electron_common_*(12 个,主进程 + 渲染进程):
asar command_line crashpad_support environment
events features native_image net
shared_texture shell testing v8_util
electron_renderer_*(5 个,渲染进程):
context_bridge crash_reporter ipc web_frame web_utils
electron_utility_*(2 个,utility 进程):
local_ai_handler parent_port
这份清单本身在讲一个故事。看 electron_common_* 这 12 个:
asar—— 读 asar 归档(第 5 章的app_package.cc用的就是它)command_line——app.commandLinenative_image——nativeImage.createFromPath,主进程和渲染进程都要net—— 底层网络v8_util——v8Util.getHiddenValue,第 5 章和第 6 章的 hidden value 通道events——EventEmitter构造器(第 7.9 节展开)features—— 特性开关shell——shell.openExternalenvironment—— 环境变量shared_texture—— 跨进程共享纹理(第 13 章)crashpad_support—— 崩溃上报辅助testing—— 测试专用(gc()、triggerFatalErrorForTesting)
这 12 个的共同点是不依赖 Browser 单例。asar 只读文件系统,native_image 只碰 Skia,v8_util 只碰 V8。它们可以在任何进程里工作。
而 37 个 electron_browser_* 全都要碰 Browser::Get()、Session、WebContents——只能活在主进程。
这个划分的正确性可以直接验证:在渲染进程里 process._linkedBinding('electron_common_native_image') 能拿到完整的 NativeImage,而 electron_browser_dialog 返回空对象。
7.3 Initialize 的两种写法:单例与构造器
读完 56 个 Initialize,会发现只有两种形状。
7.3.1 单例:app、screen、powerMonitor
electron_api_app.cc:2247
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* const isolate = electron::JavascriptEnvironment::GetIsolate();
gin_helper::Dictionary dict{isolate, exports};
electron::api::App* app = electron::api::App::Get();
v8::Local<v8::Object> wrapper;
if (app->GetWrapper(isolate).ToLocal(&wrapper)) {
// app is an EventEmitter.
std::ignore = wrapper->SetPrototype(
context, electron::GetEventEmitterPrototype(isolate));
}
dict.Set("app", app);
#if BUILDFLAG(IS_LINUX)
// For desktop-name.spec.
dict.SetMethod(
"defaultDesktopName",
base::BindRepeating([](std::optional<std::u16string> name) {
return electron::DefaultDesktopName(name.value_or(std::u16string()));
}));
#endif
}
四个动作,每个都有理由。
App::Get() 是 cppgc::Persistent 包着的单例:
electron_api_app.cc:1950
App* App::Get() {
static base::NoDestructor<cppgc::Persistent<App>> instance([] {
v8::Isolate* const isolate = JavascriptEnvironment::GetIsolate();
return cppgc::Persistent<App>(cppgc::MakeGarbageCollected<App>(
isolate->GetCppHeap()->GetAllocationHandle()));
}());
return instance->Get();
}
三层包装,每一层防一件事:cppgc::Persistent<App> 让 App 分配在 unified heap 上并由持久句柄钉住(单例不该被 GC);base::NoDestructor 禁止析构(析构里有 Emit("quit"),进程退出时会崩,泄漏比崩溃好);static 局部变量提供 C++11 的线程安全懒初始化。
JavascriptEnvironment::GetIsolate() 而不是 v8::Isolate::GetCurrent():前者是 Electron 的单例,后者依赖 TLS。在 Initialize 的回调里两者应当一致,但 GetIsolate() 更明确——它断言"这个进程有一个 Electron 的 JS 环境",在 ELECTRON_RUN_AS_NODE 路径下调会 CHECK 失败,这是一个有用的错误。
GetWrapper(isolate) 可能失败。 if (...ToLocal(&wrapper)) 这个判断不是防御性编程的仪式,它对应真实场景:App 的 wrapper(JS 对象)可能还没创建。
GetWrapper 的实现(wrappable.cc:186)是"没有就造一个":
v8::MaybeLocal<v8::Object> DeprecatedWrappableBase::GetWrapperImpl(
v8::Isolate* isolate,
gin::DeprecatedWrapperInfo* info) {
if (!wrapper_.IsEmpty()) {
return v8::MaybeLocal<v8::Object>(
v8::Local<v8::Object>::New(isolate, wrapper_));
}
if (dead_) {
return v8::MaybeLocal<v8::Object>();
}
...
if (!templ->NewInstance(isolate->GetCurrentContext()).ToLocal(&wrapper)) {
// The current wrappable object will be no longer managed by V8. Delete this
// now.
delete this;
return v8::MaybeLocal<v8::Object>(wrapper);
}
NewInstance 返回空 MaybeLocal 的唯一现实场景,注释说了:Object.prototype.constructor 被覆盖。这时 V8 造不出实例,GetWrapper 返回空,Initialize 里的 if 就不进——app 对象照常导出,只是没有 EventEmitter 原型。降级而不是崩溃,这是 Electron 对"用户把全局搞坏了"的一贯态度。
SetPrototype(GetEventEmitterPrototype(isolate)): 这是 app 能 on('ready') 的关键。
GetEventEmitterPrototype 返回的是 lib/browser/init.ts 里塞进来的那个对象:
// lib/browser/init.ts 第 1 段
process._linkedBinding('electron_browser_event_emitter').setEventEmitterPrototype(EventEmitter.prototype);
链路是:
Node 的 EventEmitter.prototype
│ setEventEmitterPrototype(第 1 段,init.ts 第一行)
▼
C++ 的 static v8::Global<v8::Object>
│ GetEventEmitterPrototype(isolate)
▼
app 的 wrapper 的 [[Prototype]]
所以 app 的 on / emit / once / removeListener 全部来自 Node 的 EventEmitter.prototype——不是重新实现的,是同一个对象。这就是为什么 app instanceof EventEmitter 在 Node 上下文里成立。
但注意:App 这个 C++ 类自己还继承着 gin_helper::EventEmitterMixin<App>(electron_api_app.h:62)。Mixin 提供的是 Emit()(C++ 侧发事件),prototype 链接提供的是 on()(JS 侧听事件)。两半合起来才是完整的 EventEmitter。
dict.Set("app", app): 把裸指针交给 gin::Converter<T*>,它会调 val->GetWrapper()。这就是 7.4 节要拆的转换器。
7.3.2 构造器:BrowserWindow、Menu、View
electron_api_browser_window.cc:382
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* const isolate = electron::JavascriptEnvironment::GetIsolate();
gin_helper::Dictionary dict{isolate, exports};
dict.Set("BrowserWindow",
gin_helper::CreateConstructor<BrowserWindow>(
isolate, base::BindRepeating(&BrowserWindow::New),
electron::api::BaseWindow::GetConstructorTemplate(isolate)));
}
CreateConstructor<T>(isolate, factory, parent) 在 constructor.h:106-113 里,展开成四步:
constructor.h:106-113
template <typename T, typename Sig>
v8::Local<v8::Function> CreateConstructor(
v8::Isolate* isolate,
const base::RepeatingCallback<Sig>& func,
v8::Local<v8::FunctionTemplate> parent = ...) {
return CreateConstructorTemplate<T>(isolate, func, parent)
->GetFunction(isolate->GetCurrentContext())
.ToLocalChecked();
}
而 CreateConstructorTemplate 是:
constructor.h:86-93
template <typename T, typename Sig>
v8::Local<v8::FunctionTemplate> CreateConstructorTemplate(
v8::Isolate* isolate,
const base::RepeatingCallback<Sig>& func,
v8::Local<v8::FunctionTemplate> parent = v8::Local<v8::FunctionTemplate>()) {
#ifndef NDEBUG
static bool called = false;
CHECK(!called) << "CreateConstructor can only be called for one type once";
called = true;
#endif
v8::Local<v8::FunctionTemplate> templ = gin_helper::CreateFunctionTemplate(
isolate, base::BindRepeating(&internal::InvokeNew<Sig>, func));
templ->InstanceTemplate()->SetInternalFieldCount(1);
if (!parent.IsEmpty())
templ->Inherit(parent);
T::BuildPrototype(isolate, templ);
return templ;
}
五个动作:
-
#ifndef NDEBUG的static bool called—— debug 构建下,同一个类型只能建一次构造器。理由注释写了:"otherwise we would have memory leak"。static局部变量在模板实例化里是每个T一份,所以这个检查是 per-type 的。Release 构建下这个检查被剥掉(
#ifndef NDEBUG),代价是如果真建了两次,两个FunctionTemplate会各自持有BuildPrototype里创建的CallbackHolder,其中一个永远不释放。这是一个只在 debug 里报的泄漏——合理,因为泄漏只在开发期需要发现。 -
CreateFunctionTemplate(isolate, BindRepeating(&InvokeNew<Sig>, func))—— 把"new的时候调什么"包装成一个 V8 函数模板。InvokeNew在同一个文件里:
constructor.h:53-60
template <typename Sig>
void InvokeNew(const base::RepeatingCallback<Sig>& factory,
v8::Isolate* const isolate,
gin::Arguments* const args) {
if (!args->IsConstructCall()) {
args->ThrowTypeError("Requires constructor call");
return;
}
WrappableBase* object;
{
// Don't continue if the constructor throws an exception.
v8::TryCatch try_catch{isolate};
object = internal::InvokeFactory(args, factory);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
return;
}
}
if (!object)
args->ThrowError();
}
if (!args->IsConstructCall()) 挡住 BrowserWindow() 这种不带 new 的调用。这是 class 语义(ES6 class 也要求 new),但注意 Node 的 assert.throws(() => BrowserWindow(), /Requires constructor call/) 能过——错误消息是可测的。
TryCatch 那段:InvokeFactory 会调 BrowserWindow::New,后者可能抛异常(比如 new BrowserWindow({width: -1}))。如果不捕获,异常会留在 isolate 里,args->ThrowError() 又抛一个,变成"异常套异常",V8 会报 Fatal error: unsent exception。所以先 try_catch.ReThrow() 把原异常放出去,直接 return。
-
SetInternalFieldCount(1)—— 给每个实例分配 1 个 internal field。这是WrappableBase存this指针的地方(7.4 节)。 -
Inherit(parent)——BrowserWindow继承BaseWindow的FunctionTemplate。这就是为什么Object.getPrototypeOf(BrowserWindow.prototype) === BaseWindow.prototype。实测:
const { BrowserWindow, BaseWindow } = require('electron') Object.getPrototypeOf(BrowserWindow) === BaseWindow // true(构造器继承) Object.getPrototypeOf(BrowserWindow.prototype) === BaseWindow.prototype // true(原型链)Inherit一次做两件事,这就是 ES6class B extends A的 C++ 等价物。 -
T::BuildPrototype(isolate, templ)—— 调T的静态方法,往templ->PrototypeTemplate()上挂方法和属性。这是每个 API 类必须实现的:
electron_api_power_save_blocker.cc:63
gin::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<PowerSaveBlocker>::GetObjectTemplateBuilder(isolate)
.SetMethod("start", &PowerSaveBlocker::Start)
.SetMethod("stop", &PowerSaveBlocker::Stop)
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
}
注意这里是 GetObjectTemplateBuilder(返回 builder),而 CreateConstructorTemplate 调的是 BuildPrototype。中间有一层适配——BuildPrototype 是 gin::Wrappable 提供的,它内部调 GetObjectTemplateBuilder 然后 .Build()。
7.3.3 为什么 app 是单例而 BrowserWindow 是构造器
因为 JS 侧的 API 形状不同:
app.md:11-15
// app:一个对象,全局唯一
const { app } = require('electron')
app.quit()
// BrowserWindow:一个类,可以有多个实例
const { BrowserWindow } = require('electron')
const a = new BrowserWindow()
const b = new BrowserWindow()
C++ 侧必须匹配这个形状:App 的 Initialize 导出一个实例,BrowserWindow 的 Initialize 导出一个构造函数。
这个匹配有个例外:Screen。C++ 侧 Screen::Get() 是单例,但 JS 侧的 screen 也是单例对象。PowerMonitor 同理。而 Menu 是既有构造器又有静态方法(Menu.setApplicationMenu)——Menu::Initialize 导出构造函数,静态方法挂在构造函数上:
dict.Set("Menu", gin_helper::CreateConstructor<Menu>(...));
// 静态方法在 Menu 的 FunctionTemplate 上,不在 prototype 上
这个区别在 JS 侧的表现:Menu.setApplicationMenu 能调,menuInstance.setApplicationMenu 是 undefined。
7.4 Wrappable:internal field 里的那根指针
现在进入第 0 层。先看最古老、也是理解一切的起点:WrappableBase。
wrappable_base.h:34
class WrappableBase {
public:
WrappableBase();
virtual ~WrappableBase();
// Retrieve the v8 wrapper object corresponding to this object.
v8::Local<v8::Object> GetWrapper() const;
// Returns the Isolate this object is created in.
v8::Isolate* isolate() const { return isolate_; }
protected:
// Bind the C++ class to the JS wrapper.
virtual void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
v8::Global<v8::Object> wrapper_; // Weak
private:
static void FirstWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data);
static void SecondWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data);
raw_ptr<v8::Isolate> isolate_ = nullptr;
};
三个成员,构成双向绑定:
C++ 对象 ──── wrapper_(v8::Global,弱引用)────> JS 对象
JS 对象 ──── internal field 0(void*)─────────> C++ 对象
两个方向,两个不同的强弱语义。
C++ → JS 的 wrapper_ 是弱的(SetWeak)。C++ 对象不持有 JS 对象——否则 JS 对象永远不会被回收(C++ 对象的生命周期由谁管?如果 App 强引用它的 wrapper,wrapper 永远活着,App 也永远活着,单例可以接受,但 BrowserWindow 不行)。
JS → C++ 的指针是裸的(internal field 里存 void*)。JS 对象不"拥有"C++ 对象——V8 不知道这个指针是什么,不会去 delete 它。
那 C++ 对象什么时候死?当 JS 对象被 GC 回收时。回收触发弱回调,弱回调里 delete C++ 对象。
这就是"共享一条命"的机制:命由 JS 的 GC 决定,死由 C++ 的析构函数执行。
7.4.1 InitWith:绑定的那一刻
wrappable.cc:44
void WrappableBase::InitWith(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper) {
CHECK(wrapper_.IsEmpty());
isolate_ = isolate;
wrapper->SetAlignedPointerInInternalField(0, this,
v8::kEmbedderDataTypeTagDefault);
wrapper_.Reset(isolate, wrapper);
wrapper_.SetWeak(this, FirstWeakCallback,
v8::WeakCallbackType::kInternalFields);
OnWrapped(isolate);
// Call object._init if we have one.
v8::Local<v8::Function> init;
if (Dictionary(isolate, wrapper).Get("_init", &init))
init->Call(isolate->GetCurrentContext(), wrapper, 0, nullptr).IsEmpty();
}
六行核心代码,五个动作:
CHECK(wrapper_.IsEmpty()) —— 一个 C++ 对象只能绑一个 JS 对象。第二次调会崩。这个 CHECK 挡住的是"忘记检查是否已绑定就重复 Init"的 bug。
SetAlignedPointerInInternalField(0, this, v8::kEmbedderDataTypeTagDefault) —— 把 this 存进 internal field 0。
第三个参数 v8::kEmbedderDataTypeTagDefault 值得单独说。V8 的 sandbox(自 v8 11.x 起默认开启)把 internal field 从"可以存任意指针"改成了"只能存带类型标签的指针"。标签用于在 sandbox 里验证指针的用途——一个被用作 EmbedderDataTypeTag 的指针不能被当成 ExternalPointerTag 用。
这个机制是 V8 sandbox 的一部分:即使攻击者在 JS 里实现了任意读写,他也无法伪造一个能通过标签检查的指针。kEmbedderDataTypeTagDefault 是"默认标签",表示"这个字段存的是 embedder 自己的数据指针"。
wrapper_.Reset(isolate, wrapper) —— 建立 C++ → JS 的持久句柄。
SetWeak(this, FirstWeakCallback, WeakCallbackType::kInternalFields) —— 注册弱回调。
三个参数:
this—— 回调时通过data.GetParameter()拿回FirstWeakCallback—— 第一遍回调kInternalFields—— 关键。这个类型告诉 V8:"这个对象存活与否,要看它的 internal field 里有没有指针。如果 field 是 null,就当它死了。"
kInternalFields 与 kParameter 的区别:
| 类型 | V8 何时认为对象可回收 | 典型用途 |
|---|---|---|
kParameter | 对象本身不可达 | 简单数据 |
kInternalFields | 对象不可达 且 internal field 为 null | Wrappable(因为 MarkDestroyed 会把 field 置 null) |
为什么 Wrappable 用 kInternalFields?因为 Electron 需要"手动宣告死亡"的能力——TrackableObject::MarkDestroyed() 把 field 置 null,这样即使 JS 对象还被引用着,V8 也会认为它死了,触发弱回调,C++ 对象被销毁。这是 7.6 和 7.14 节的内容。
OnWrapped(isolate) —— 一个空的虚函数钩子,注释说明它的位置:
// Called by InitWith once GetWrapper() works, before the wrapper's JS _init
// (if it has one) runs.
virtual void OnWrapped(v8::Isolate* isolate) {}
"once GetWrapper() works" 是精确的:在这之前 GetWrapper() 返回空,在这之后可用。子类可以在这里做"我需要 wrapper 存在才能做的事"(比如把 wrapper 塞进某个 JS 侧的表)。
_init 的调用 —— wrapper 上若有 _init 属性,调它。这是从 native_mate(Electron 早期的绑定层)继承下来的:某些 API 的初始化逻辑写在 JS 里,C++ 侧在绑定完成后回调一次。
.IsEmpty() 被丢弃——_init 抛异常不传播。刻意的:内部机制的异常不该让构造过程失败。
7.4.2 SetInternalFieldCount(1) 与多字段版
单字段版(gin_helper::Wrappable<T>):
internal field 0 ──── void* → WrappableBase*
判断"这是不是我"需要两次检查(FromV8Impl,wrappable.cc:220):
void* FromV8Impl(v8::Isolate* isolate, v8::Local<v8::Value> val) {
if (!val->IsObject())
return nullptr;
v8::Local<v8::Object> obj = val.As<v8::Object>();
if (obj->InternalFieldCount() != 1)
return nullptr;
return obj->GetAlignedPointerFromInternalField(
0, v8::kEmbedderDataTypeTagDefault);
}
这个函数不安全。 它只检查"是不是有 1 个 internal field 的对象"。任何别的库(比如某个原生模块)如果用 1 个 internal field 存了自己的指针,Electron 会把那个指针当成 WrappableBase* 然后调虚函数——崩溃。
这就是多字段版存在的原因。
多字段版(gin::Wrappable<T>,即 DeprecatedWrappableBase):
internal field kWrapperInfoIndex ── WrapperInfo* (类型标签)
internal field kEncodedValueIndex ── 对象自身
这两个索引由 gin 定义(gin::kWrapperInfoIndex、gin::kEncodedValueIndex),总数是 gin::kNumberOfInternalFields。Electron 只按索引名访问,不硬编码数字——这也解释了为什么它能跟着 gin 的布局变化而不改代码。
FromV8Impl 的多字段版(wrappable.cc:229):
void* FromV8Impl(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gin::DeprecatedWrapperInfo* wrapper_info) {
if (!val->IsObject()) {
return nullptr;
}
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(val);
gin::DeprecatedWrapperInfo* info = gin::DeprecatedWrapperInfo::From(obj);
// If this fails, the object is not managed by Gin. It is either a normal JS
// object that's not wrapping any external C++ object, or it is wrapping some
// C++ object, but that object isn't managed by Gin (maybe Blink).
if (!info) {
return nullptr;
}
// If this fails, the object is managed by Gin, but it's not wrapping an
// instance of the C++ class associated with wrapper_info.
if (info != wrapper_info) {
return nullptr;
}
return obj->GetAlignedPointerFromInternalField(
gin::kEncodedValueIndex, v8::kEmbedderDataTypeTagDefault);
}
两道检查,各挡一类错误。
第一道 if (!info) 挡"不是 gin 管理的对象"。DeprecatedWrapperInfo::From 的实现(wrappable.cc:265):
DeprecatedWrapperInfo* DeprecatedWrapperInfo::From(
v8::Local<v8::Object> object) {
if (object->InternalFieldCount() != kNumberOfInternalFields)
return nullptr;
// A cppgc-managed gin::Wrappable has the same number of internal fields but
// leaves them null, keeping its native pointer on the unified heap instead,
// so the field can be null even though the count matched.
DeprecatedWrapperInfo* info = static_cast<DeprecatedWrapperInfo*>(
object->GetAlignedPointerFromInternalField(
kWrapperInfoIndex, v8::kEmbedderDataTypeTagDefault));
return info && info->embedder == kEmbedderNativeGin ? info : nullptr;
}
那句注释是本章最重要的一句话之一:
A cppgc-managed gin::Wrappable has the same number of internal fields but leaves them null, keeping its native pointer on the unified heap instead, so the field can be null even though the count matched.
新一代的 gin::Wrappable(cppgc 版)仍然分配同样数量的 internal field,但全部留空。 为什么?因为 InternalFieldCount 是模板上的属性,所有 gin 对象共用一套 ObjectTemplate 检查路径。如果新旧两代 field count 不同,From 的第一行 InternalFieldCount() != kNumberOfInternalFields 就会把新一代对象误判成"不是 gin 对象"。
留空后,info 是 null,From 走 return nullptr,然后 FromV8Impl 走 if (!info) return nullptr——新一代对象通过"多字段版 FromV8"会得到 nullptr,这是一次误判,但它是有意的。
因为新一代对象不应该走 FromV8Impl。它走的是 gin::Wrappable 自己的路径(v8::Object::Unwrap<T> 或 WrapperInfo 直接比较)。DeprecatedWrappableBase 的 FromV8Impl 只服务旧一代。
这是一个迁移期的"兼容空位":为了不让旧代码的 field count 检查失败,新一代对象分配了用不到的字段。7.6 节会展开这场迁移的全貌。
第二道 if (info != wrapper_info) 挡"是 gin 对象但类型不对"。比如把 BrowserWindow 的实例传给期望 Menu* 的函数——info 是 &BrowserWindow::kWrapperInfo,不等于 &Menu::kWrapperInfo,返回 nullptr,上层抛 TypeError: Illegal invocation。
这两道检查合起来,就是 IsValidWrappable:
wrappable.cc:19
bool IsValidWrappable(const v8::Local<v8::Value>& val,
const gin::DeprecatedWrapperInfo* wrapper_info) {
if (!val->IsObject())
return false;
v8::Local<v8::Object> port = val.As<v8::Object>();
if (port->InternalFieldCount() != gin::kNumberOfInternalFields)
return false;
const gin::DeprecatedWrapperInfo* info =
static_cast<gin::DeprecatedWrapperInfo*>(
port->GetAlignedPointerFromInternalField(
gin::kWrapperInfoIndex, v8::kEmbedderDataTypeTagDefault));
if (info != wrapper_info)
return false;
return true;
}
注意它不检查 kEncodedValueIndex 那个字段是否为 null。一个"已销毁但 wrapper 还活着"的对象,IsValidWrappable 返回 true,FromV8Impl 返回 nullptr(因为那个字段被置 null)。这个不对称是刻意的——IsValidWrappable 回答"形状对不对",FromV8Impl 回答"能不能用"。
7.4.3 Converter<T*>:自动化的双向转换
wrappable.h 的最后一段是整个机制能"自动工作"的原因:
namespace gin {
template <typename T>
struct Converter<
T*,
typename std::enable_if<
std::is_convertible<T*, gin_helper::WrappableBase*>::value>::type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, T* val) {
if (val)
return val->GetWrapper();
else
return v8::Null(isolate);
}
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, T** out) {
*out = static_cast<T*>(static_cast<gin_helper::WrappableBase*>(
gin_helper::internal::FromV8Impl(isolate, val)));
return *out != nullptr;
}
};
} // namespace gin
gin::Converter<T> 是 gin 的转换器模板:ToV8 是 C++ → JS,FromV8 是 JS → C++。Electron 为"任何继承 WrappableBase 的指针类型"特化了一份。
特化的条件用 std::enable_if + std::is_convertible——SFINAE。这意味着:只要一个类继承 WrappableBase,它就自动获得 JS ↔ C++ 的转换能力,不需要任何额外声明。
这就是为什么 dict.Set("app", app) 能工作:app 是 App*,App 继承 Wrappable<App>(继承 WrappableBase),Converter<App*> 存在,ToV8 调 app->GetWrapper()。
同样,process->SetMethod("start", &PowerSaveBlocker::Start) 里 Start 的第一个参数是 PowerSaveBlocker*(从 JS 的 this 来),FromV8 把 this 转成 C++ 指针。
于是一个 C++ 成员函数指针,就自动变成了一个可被 JS 调用的方法。 这中间没有手写的胶水代码。这是 gin 这一层最本质的价值。
而 C++ 成员函数指针 → JS 方法 这个转换的细节,在 ObjectTemplateBuilder::SetMethod 里:
template <typename T>
ObjectTemplateBuilder& SetMethod(const std::string_view name,
const T& callback) {
return SetImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, callback));
}
CallbackTraits 对成员函数指针有专门特化(function_template.h:555):
template <typename T>
struct CallbackTraits<
T,
typename std::enable_if<std::is_member_function_pointer<T>::value>::type> {
static v8::Local<v8::FunctionTemplate> CreateTemplate(v8::Isolate* isolate,
T callback) {
InvokerOptions invoker_options = {.holder_is_first_argument = true};
return gin_helper::CreateFunctionTemplate(
isolate, base::BindRepeating(callback), std::move(invoker_options));
}
};
holder_is_first_argument = true 是全部的秘密:成员函数的第一个参数(this)从 JS 的 this 取,不从参数列表取。
于是 win.setTitle('x') 的调用链是:
JS: win.setTitle('x')
│
├─ V8 找到 win 的 prototype 上的 setTitle(一个 FunctionTemplate 实例)
│
├─ FunctionCallbackInfo: this = win, args = ['x']
│
├─ gin::Arguments args(info)
│
├─ Arguments::GetHolder(PowerSaveBlocker** / BaseWindow**)
│ └─ FromV8Impl(isolate, holder, &BaseWindow::kWrapperInfo)
│ ├─ IsObject? ✔
│ ├─ InternalFieldCount == 3? ✔
│ ├─ info == &BaseWindow::kWrapperInfo? ✔
│ └─ return field[2] → BaseWindow*
│
├─ Arguments::GetNext(std::string*) → 'x'
│
└─ BaseWindow::SetTitle('x') → NativeWindow::SetTitle
每一步都可能失败,每种失败有独立的错误消息——这是 7.8 节的内容。
7.5 弱回调的两遍协议:为什么不能在第一遍里 delete
SetWeak(this, FirstWeakCallback, kInternalFields) 注册的是一个两遍回调。V8 的弱回调协议要求:
- 第一遍(
FirstWeakCallback):对象已被判定为垃圾,但尚未被回收。此时可以访问对象,但不能让对象复活(除非调SetSecondPassCallback之外的复活 API)。 - 第二遍(
SecondWeakCallback):对象即将被回收。此时禁止访问对象本身(它的内存可能已经被复用)。
两遍之间 V8 会做一次完整的 GC 循环,确保第一遍里的任何操作(比如 ClearWeak 复活)都被正确处理。
Electron 的实现:
wrappable.cc:76
// static
void WrappableBase::FirstWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
WrappableBase* wrappable = data.GetParameter();
auto* wrappable_from_field =
static_cast<WrappableBase*>(data.GetInternalField(0));
if (wrappable && wrappable == wrappable_from_field) {
wrappable->wrapper_.Reset();
data.SetSecondPassCallback(SecondWeakCallback);
}
}
wrappable == wrappable_from_field 这个判断是核心。
data.GetParameter() 是第一遍回调注册时传的 this(SetWeak 的第一个参数)。data.GetInternalField(0) 是此刻 JS 对象的 internal field 0。
正常情况两者相同。什么情况不同?
Destroyable::destroy() 被调用的场景:
destroyable.cc:41
void DestroyFunc(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.This();
if (Destroyable::IsDestroyed(holder))
return;
...
delete static_cast<gin_helper::WrappableBase*>(
holder->GetAlignedPointerFromInternalField(0, v8::kEmbedderDataTypeTagDefault));
holder->SetAlignedPointerInInternalField(0, nullptr, v8::kEmbedderDataTypeTagDefault);
}
C++ 对象被立即 delete,field 0 被置 null。但那个 v8::Global 的弱回调还挂着——它会在下一次 GC 时触发,data.GetParameter() 会是那个已经被 delete 的指针。
如果不检查 wrappable == wrappable_from_field,wrappable->wrapper_.Reset() 就是对已释放内存的写入——use-after-free。
检查通过后:wrapper_.Reset() 释放 C++ → JS 的持久句柄(因为对象要死了,句柄没用了),然后注册第二遍。
7.5.1 第二遍:为什么必须 DeleteSoon
wrappable.cc:90
// static
void WrappableBase::SecondWeakCallback(
const v8::WeakCallbackInfo<WrappableBase>& data) {
if (gin::IsolateHolder::DestroyedMicrotasksRunner()) {
return;
}
// Defer destruction to a posted task. V8's second-pass weak callbacks run
// inside a DisallowJavascriptExecutionScope (they may touch the V8 API but
// must not invoke JS). Several Electron Wrappables (e.g. WebContents) emit
// JS events from their destructors, so deleting synchronously here can
// crash with "Invoke in DisallowJavascriptExecutionScope" — see
// https://github.com/electron/electron/issues/47420. Posting via the
// current sequence's task runner ensures the destructor runs once V8 has
// left the GC scope. If no task runner is available (e.g. early/late in
// process lifetime), fall back to synchronous deletion.
auto* wrappable = static_cast<WrappableBase*>(data.GetInternalField(0));
if (base::SequencedTaskRunner::HasCurrentDefault()) {
base::SequencedTaskRunner::GetCurrentDefault()->DeleteSoon(FROM_HERE,
wrappable);
} else {
delete wrappable;
}
}
这段注释是本章最值得逐字读的段落之一。拆开:
"V8's second-pass weak callbacks run inside a DisallowJavascriptExecutionScope"
V8 在执行第二遍弱回调时,会进入一个 DisallowJavascriptExecutionScope——这个 scope 的作用是禁止在该作用域内调用任何 JS(v8::Function::Call、v8::Script::Run、访问 accessor 等等)。理由是:此时 GC 正在进行,对象的可达性图上还有未清理的边,调 JS 会让新的对象从"已死"状态复活,破坏 GC 的不变量。
"Several Electron Wrappables (e.g. WebContents) emit JS events from their destructors"
WebContents 的析构函数里有类似这样的代码:
WebContents::~WebContents() {
...
Emit("destroyed");
...
}
Emit 最终会走到 node_event_emitter 或 event_emitter_caller 里的 obj.emit(...),那是一次真正的 JS 调用。
于是冲突: 弱回调里 delete → 析构函数里 emit → 在 DisallowJavascriptExecutionScope 里调 JS → V8 直接 FATAL:
# Fatal error in ../v8/src/api/api.cc
# Invoke in DisallowJavascriptExecutionScope
解法:把 delete 推迟到一个 post 出去的 task。 DeleteSoon(FROM_HERE, wrappable) 把指针塞进任务队列,等当前 GC 完成、V8 退出 DisallowJavascriptExecutionScope、消息循环处理下一个 task 时才真正 delete。那时调 JS 完全合法。
这是 issue #47420 的修复。注释里给了完整链接,这是好实践——把"为什么这么写"追溯到一份可查的 bug 报告。
if (gin::IsolateHolder::DestroyedMicrotasksRunner()) return;
这一行在最前面,是一个"进程正在退出"的探测。
isolate 拆除时,gin::IsolateHolder 会先销毁 microtasks runner。如果弱回调在这个阶段触发(V8 在 Dispose() 时会跑一轮 finalization),那么:
DeleteSoon需要 task runner —— 但消息循环已经停了,task 永远不会跑,对象泄漏delete同步执行 —— 析构函数里 emit JS,但微任务 runner 已经没了,node::CallbackScope的析构会崩
所以直接 return,让它泄漏。进程都要退出了,泄漏是正确选择。
这个"先探测再决定"的模式在 Electron 里反复出现(第 6 章的 IsolateHolder::DestroyedMicrotasksRunner() 在 ShareEnvironmentWithContext 里也用过)。
HasCurrentDefault() 的 fallback
if (base::SequencedTaskRunner::HasCurrentDefault()) {
base::SequencedTaskRunner::GetCurrentDefault()->DeleteSoon(FROM_HERE, wrappable);
} else {
delete wrappable;
}
什么时候没有默认 task runner?注释说 "early/late in process lifetime"。具体是:
- 早期:
PostEarlyInitialization之前,主线程还没绑定 task runner(第 5 章 5.5.1 的DCHECK(SingleThreadTaskRooter::HasCurrentDefault())说的就是这个)。但这时期几乎没有 Wrappable 被创建,所以基本不会触发。 - 晚期:
PostMainMessageLoopRun之后,主线程的 task runner 已经 detach。这时 GC 触发的弱回调会走delete分支——但那时期 isolate 通常已经DestroyedMicrotasksRunner(),所以更早的return已经把它挡住了。
这个 fallback 的分支几乎不可达,但必须存在。 因为如果不写,GetCurrentDefault() 会 CHECK 失败——而这正是那些最难复现的"退出时偶发崩溃"。
7.5.2 多字段版的差异
DeprecatedWrappableBase 的两个回调略有不同(wrappable.cc:148):
void DeprecatedWrappableBase::FirstWeakCallback(
const v8::WeakCallbackInfo<DeprecatedWrappableBase>& data) {
DeprecatedWrappableBase* wrappable = data.GetParameter();
DeprecatedWrappableBase* wrappable_from_field =
static_cast<DeprecatedWrappableBase*>(data.GetInternalField(1));
if (wrappable && wrappable == wrappable_from_field) {
wrappable->dead_ = true;
wrappable->wrapper_.Reset();
data.SetSecondPassCallback(SecondWeakCallback);
}
}
两处差异:
GetInternalField(1) 而不是 (0)。 多字段版的指针存在 kEncodedValueIndex(此处为 1),kWrapperInfoIndex(0)存的是 WrapperInfo。
dead_ = true。 多了一个"已死"标志。用途在 GetWrapperImpl:
wrappable.cc:170-171
if (dead_) {
return v8::MaybeLocal<v8::Object>();
}
为什么需要这个标志?因为多字段版的 GetWrapperImpl 会"没有 wrapper 就造一个"。如果一个已死的对象再次被要求 GetWrapper,不检查 dead_ 就会造出一个新 wrapper——而这个新 wrapper 的弱回调会指向一个正在销毁的 C++ 对象。
单字段版没有这个问题,因为它的 GetWrapper() 只是"返回已有句柄",不造新的。
SecondWeakCallback 用 data.GetParameter() 而不是 GetInternalField:
void DeprecatedWrappableBase::SecondWeakCallback(
const v8::WeakCallbackInfo<DeprecatedWrappableBase>& data) {
if (gin::IsolateHolder::DestroyedMicrotasksRunner())
return;
DeprecatedWrappableBase* wrappable = data.GetParameter();
if (!wrappable)
return;
if (base::SequencedTaskRunner::HasCurrentDefault()) {
base::SequencedTaskRunner::GetCurrentDefault()->DeleteSoon(FROM_HERE, wrappable);
} else {
delete wrappable;
}
}
第二遍里 internal field 可能已经被 V8 清空了(对象即将回收),所以用 GetParameter()——它指向的是 C++ 对象,与 JS 对象无关。
单字段版的第二遍用的是 data.GetInternalField(0)——field 0 就是那个 C++ 指针本身。这不矛盾:kInternalFields 的语义保证 field 的值参与了生死判定,所以在第二遍里它必然可见(否则 DeleteSoon(nullptr) 会崩)。多字段版用 GetParameter() 更保守,因为它有 dead_ 兜底。
7.6 cppgc 迁移:为什么"活着"的定义变了
现在讲本章最重要的结构变化。
$ grep -rl "public gin::Wrappable<" shell/ --include=*.h | wc -l
39
$ grep -rl "gin_helper::DeprecatedWrappable<" shell/ --include=*.h | wc -l
3
$ grep -rl "cppgc::MakeGarbageCollected" shell/ --include=*.cc | wc -l
44
39 个文件用新一代,只有 3 个还用旧一代——而那 3 个里有 2 个是 gin_helper 自己的基础设施(constructible.h 的注释、event_emitter_caller.h 的重载),真正还用旧一代的业务代码只有 electron_api_web_contents.h 一个。
这是一场接近完成的迁移。理解它,才能理解为什么代码里同时存在两套 wrapper 机制、两套 FromV8Impl、两套 WrapperInfo 类型。
7.6.1 两代的核心差别
| 维度 | 旧:gin_helper::Wrappable<T> | 新:gin::Wrappable<T> |
|---|---|---|
| C++ 对象内存 | new / delete(malloc 堆) | cppgc::MakeGarbageCollected(unified heap) |
| 指针存放 | internal field 0 | cppgc 的 heap object header |
| internal field | 1 个,存指针 | 3 个,全部留空 |
| 类型标签 | DeprecatedWrapperInfo* | WrapperInfo + WrappablePointerTag |
| 生死判定 | 手动 delete / 弱回调 | GC 遍历可达性图 |
| JS 引用成员 | v8::Global | v8::TracedReference |
| 需要实现 | BuildPrototype | GetObjectTemplateBuilder + Trace + wrapper_info |
| 销毁时机 | 弱回调里 | GC 回收时(自动) |
最关键的一行是"JS 引用成员"。 旧一代用 v8::Global<v8::Value>,而 Global 是根(root)——GC 从根出发标记可达对象,所以 Global 引用的对象永远不会被回收。新一代必须用 v8::TracedReference:
electron_api_app.h:265
v8::TracedReference<v8::Value> dock_;
v8::TracedReference<v8::Value> command_line_;
v8::TracedReference<v8::Value> app_path_value_; // Reset by SetAppPath.
v8::TracedReference<v8::Function> client_cert_password_handler_;
TracedReference 是边(edge),不是根。它告诉 cppgc:"我这个 C++ 对象引用着那个 JS 对象,请在遍历时把我的引用算进去。"
为什么必须这样?因为 cppgc 的对象本身是被 GC 管理的。如果 App 用 Global 引用一个 JS 函数:
cppgc 堆: App ──[Global]──> ???
│
V8 堆: JS function
GC 标记 App(从某个根)→ 到达 App → App 里的 Global 是一个 V8 根 → 标记那个 function。看起来没问题。
但反过来:如果 App 不可达了,App 里的 Global 依然是一个根。 cppgc 回收 App 时会调它的析构函数,析构函数里 Global 才被 Reset。在那之前,那个 JS function 一直被这个"已死的 App"钉住。
更糟的是:cppgc 的回收是增量的、并发的。在 App 被判定垃圾但尚未回收的窗口里,GC 还需要扫描 App 的内存。如果 App 里是 Global,V8 的 GC 需要知道"这个 cppgc 对象里有一个 Global"——但它不知道,因为 V8 只会扫 roots 和 traced references。
结果是:cppgc 和 V8 堆的跨堆引用在 Global 下完全不可预测。可能泄漏,可能读到已回收的内存。
TracedReference + Trace(cppgc::Visitor*) 是唯一正确的做法:
// electron_api_app.cc
void App::Trace(cppgc::Visitor* visitor) const {
gin::Wrappable<App>::Trace(visitor);
visitor->Trace(command_line_);
visitor->Trace(client_cert_password_handler_);
visitor->Trace(name_string_);
visitor->Trace(version_string_);
visitor->Trace(app_path_value_);
#if BUILDFLAG(IS_MAC)
visitor->Trace(dock_);
visitor->Trace(dock_menu_);
#endif
}
Trace 必须列出每一个 TracedReference 成员。
漏一个的后果是:那个 JS 值会被当成不可达而回收,C++ 侧留下一个悬垂的 TracedReference。下次 TracedReference::Get(isolate) 会返回空——不是崩溃,是静默丢失。这类 bug 极难查,因为漏 Trace 不会有任何编译期或运行期警告。
gin::Wrappable<App>::Trace(visitor) 第一行调基类的 Trace,它会 trace gin 自己内部的引用(如果有)。这是 C++ 里 Trace 链的标准写法:先调基类,再 trace 自己的成员。
7.6.2 一个必须理解的细节:internal field 为什么留空
回到 DeprecatedWrapperInfo::From 的那句注释:
// A cppgc-managed gin::Wrappable has the same number of internal fields but
// leaves them null, keeping its native pointer on the unified heap instead,
// so the field can be null even though the count matched.
三个事实:
- 新一代对象也分配同样数量的 internal field(
gin::kNumberOfInternalFields)。 - 但这 3 个 field 全部是 null。
- 指针在 "unified heap" 上——即 cppgc 管理的那块内存的对象头里。
为什么要分配用不到的 field?因为 ObjectTemplate 的 InternalFieldCount 是模板级属性,它在 v8::ObjectTemplate 创建时定下,所有用该模板创建的实例共享。
如果新一代用 0 个 field、旧一代用 3 个,会有两个后果:
DeprecatedWrapperInfo::From的第一行if (object->InternalFieldCount() != kNumberOfInternalFields) return nullptr;会把新一代对象正确拒绝——这是好事。- 但所有"通用检查"代码(比如
destroyable.cc:69-74里的holder->InternalFieldCount() != 1、IsDestroyed里的InternalFieldCount() == 0)都会对新一代对象做出错误判断。
具体地,Destroyable::IsDestroyed:
destroyable.cc:79
// static
bool Destroyable::IsDestroyed(v8::Local<v8::Object> object) {
// cppgc-managed objects keep their native pointer on the V8 unified heap and
// deliberately leave the gin internal fields null, so the internal-field
// heuristic below does not apply to them. Their native object is kept alive
// by the unified heap for as long as the wrapper is reachable, so such an
// object is never considered destroyed through this mechanism.
if (IsCppHeapWrappable(object))
return false;
// An object is considered destroyed if it has no internal pointer or its
// internal has been destroyed.
return object->InternalFieldCount() == 0 ||
object->GetAlignedPointerFromInternalField(
0, v8::kEmbedderDataTypeTagDefault) == nullptr;
}
IsCppHeapWrappable 是一次显式的"你属于哪一代"探测:
bool IsCppHeapWrappable(v8::Local<v8::Object> object) {
if (!object->IsApiWrapper())
return false;
return v8::Object::Unwrap<v8::Object::Wrappable>(
v8::Isolate::GetCurrent(), object, v8::kAnyCppHeapPointer) !=
nullptr;
}
object->IsApiWrapper() 判断这是不是一个 API 对象(即从 ObjectTemplate 创建的,而非普通 JS 对象)。Unwrap<Wrappable>(..., kAnyCppHeapPointer) 尝试从 cppgc 堆上取回 native 指针。
kAnyCppHeapPointer 这个 tag 是"任何 cppgc 指针"——用它做探测,命中说明是 cppgc 管理的对象。
于是 IsDestroyed 的语义分叉了:
- cppgc 对象 → 永远
false。理由注释说得清楚:"Their native object is kept alive by the unified heap for as long as the wrapper is reachable"。cppgc 的对象生死由 GC 统一管理,JS 对象可达 ⇒ C++ 对象可达 ⇒ 不可能"已销毁"。 - 旧一代对象 → 看 internal field 0 是否为 null。
这个分叉导致一个行为差异,可以实测:
const { PowerSaveBlocker } = require('electron')
const b = new PowerSaveBlocker() // cppgc 版
b.destroy()
b.isDestroyed() // true —— 因为 DestroyFunc 把 field 置 null 了?
等等,DestroyFunc 里:
if (IsCppHeapWrappable(holder))
return;
对 cppgc 对象,destroy() 是个 no-op。 因为它无法也无需手动销毁——GC 会处理。
那 b.isDestroyed() 返回什么?Destroyable::IsDestroyed 对 cppgc 对象返回 false。所以:
b.destroy()
b.isDestroyed() // false
这看起来像 bug,但它是正确的:cppgc 对象的生命周期不该被 JS 手动干预。destroy() 在新一代对象上保留只是为了 API 兼容(不抛错),实际什么都不做。
7.6.3 cppgc::Persistent 与 cppgc::Member
新一代还有两种引用方式,和 TracedReference 不同:
cppgc::Persistent<T> —— 强引用,相当于 cppgc 世界的 v8::Global。用在"必须永远活着"的地方:
App* App::Get() {
static base::NoDestructor<cppgc::Persistent<App>> instance([] {
v8::Isolate* const isolate = JavascriptEnvironment::GetIsolate();
return cppgc::Persistent<App>(cppgc::MakeGarbageCollected<App>(
isolate->GetCppHeap()->GetAllocationHandle()));
}());
return instance->Get();
}
cppgc::Persistent<App> 持有一个根,所以 App 永远不会被回收。单例的正确写法。
cppgc::Member<T> —— 弱化版,用在 cppgc 对象内部的 C++ 成员引用(C++ 对象 → C++ 对象)。它参与 tracing,但不阻止回收(依赖于持有者的可达性)。
Electron 里 cppgc::Member 用得少,因为大部分 C++ 对象是 std::unique_ptr 管理的普通堆对象,不在 cppgc 堆上。
SafeV8Function 里的用法值得单独看(callback.h):
class SafeV8Function {
public:
SafeV8Function(v8::Isolate* isolate, v8::Local<v8::Value> value);
SafeV8Function(const SafeV8Function& other);
~SafeV8Function();
bool IsAlive() const;
v8::Local<v8::Function> NewHandle(v8::Isolate* isolate) const;
private:
cppgc::Persistent<SafeV8FunctionHandle> v8_function_;
};
SafeV8FunctionHandle 是一个 cppgc 分配的小对象,它内部持有 v8::TracedReference<v8::Function>。SafeV8Function 用 cppgc::Persistent 引用那个 handle。
为什么要绕一层? 因为 SafeV8Function 是可拷贝的(它有拷贝构造函数),而且会作为 base::RepeatingCallback 的捕获值被到处传。如果它直接持有 TracedReference,拷贝时两个 TracedReference 指向同一个 JS 函数——V8 的 TracedReference 不支持这种"多个独立副本"的语义(它内部是一个链表节点)。
绕一层 cppgc handle 之后:拷贝 SafeV8Function 只是增加 Persistent 的引用计数,底层只有一个 TracedReference。引用计数归零时 handle 被回收,TracedReference 被销毁。
这是一个"共享所有权 + 唯一 traced edge"的模式,在跨堆引用里很常见。
7.6.4 迁移还没完成的地方
electron_api_web_contents.h 是最后一个大用户:
$ grep -n "DeprecatedWrappable" shell/browser/api/electron_api_web_contents.h
class WebContents : public gin_helper::DeprecatedWrappable<WebContents>,
不迁的理由:WebContents 持有几十个 v8::Global(事件监听器、executeJavaScript 回调、preload 异常 handler),生命周期与 content::WebContents 强耦合,且显式依赖 SetWeak 语义(destroyed 后 JS 对象活着但语义已死)。迁移要改几十个 Global、写一个巨大的 Trace、重验所有"JS 活着但 WebContents 已死"的路径。风险远大于收益。
issue #47922 是这个迁移的追踪号。代码里两处注释都指向它:
// Copied from https://chromium-review.googlesource.com/c/chromium/src/+/6799157
// Will be removed as part of https://github.com/electron/electron/issues/47922
"Copied from" 这四个字值得注意。 DeprecatedWrappableBase、DeprecatedWrapperInfo、DeprecatedSetFunctionTemplate、DeprecatedGetFunctionTemplate 这些 Deprecated 前缀的 API,是 Electron 从 Chromium 的 gin 里拷贝过来的——因为 Chromium 上游把旧 API 删了,而 Electron 还需要它来支撑未迁移的代码。
这是一次真实的"上游删除 API → 下游 fork 一份"的操作。它和 7.1 节讲的 function_template.h fork 是同一类事:
// This file is forked from gin/function_template.h with 2 differences:
// 1. Support for additional types of arguments.
// 2. Support for warning using destroyed objects.
Electron 与 Chromium 的关系里,这种"fork 一小块"是常态。fork 的成本是维护负担,收益是"可以慢慢迁"。第 4 章的 380 个补丁里有相当一部分就是这类 fork 的产物。
7.7 WrappablePointerTag:45 个类型标签与三条断言
上一节说 cppgc 对象"指针在 unified heap 的对象头里"。那么"这个对象是什么类型"怎么判断?
答案在 wrappable_pointer_tags.h:
namespace electron {
// Electron-specific WrappablePointerTag values that extend gin's tag range.
enum ElectronWrappablePointerTag : uint16_t {
kElectronApp = gin::kLastPointerTag + 1, // electron::api::App
kElectronAppShimHost, // electron::api::AppShimHost
kElectronAutoUpdater, // electron::api::AutoUpdater
kElectronChunkedDataPipeReadableStream, // ChunkedDataPipeReadableStream
kElectronClipboardItem, // electron::api::ClipboardItem
kElectronCookies, // electron::api::Cookies
...
kElectronWebSocket, // electron::api::WebSocketWrapper
kLastElectronPointerTag = kElectronWebSocket,
};
45 个枚举值,每个对应一个 Electron API 类型,每个后面跟着注释写着真实类名。
7.7.1 为什么需要类型标签
V8 的 sandbox(2024 年起默认开启)把堆内存和外部的指针隔离开。为了在 sandbox 里仍然能安全地做类型转换,V8 引入了 pointer tag 机制:
每一个从 V8 对象里取出的指针都带一个标签(16 位整数)。V8 在取出指针时会验证标签是否匹配请求的类型——不匹配就返回 null 或崩溃。
这挡住了什么攻击?假设攻击者在 JS 里实现了任意读写,他能改写一个 API 对象的 native 指针字段,指向他控制的假对象。如果没有标签检查,win.setTitle() 会调用假对象上的虚函数——直接 RCE。
有标签检查后,攻击者必须让假对象带有正确的标签。而标签是编译期常量,写在对象的 cppgc header 里,攻击者无法伪造(因为 tag 存在 V8 管理的内存里,且写入 tag 的路径受 sandbox 保护)。
所以类型标签不是"性能优化",它是安全边界的一部分。 这是理解这个文件的关键。
7.7.2 MakeWrapperInfo:从 tag 造 WrapperInfo
// Constructs a gin::WrapperInfo from an ElectronWrappablePointerTag,
constexpr gin::WrapperInfo MakeWrapperInfo(ElectronWrappablePointerTag tag) {
return {{gin::kEmbedderNativeGin},
static_cast<gin::WrappablePointerTag>(tag)};
}
gin::WrapperInfo 有两个字段:
struct WrapperInfo {
gin::GinEmbedder embedder; // 谁创建的(gin / Blink / PDFium / Electron)
gin::WrappablePointerTag pointer_tag; // 类型标签
};
{gin::kEmbedderNativeGin} 是第一个字段的初始化(embedder = kEmbedderNativeGin),第二个是 tag。
注意 kEmbedderNativeGin 而不是 kEmbedderElectron。虽然 gin_embedders.h 里定义了:
// Extend gin embedder range.
enum ElectronGinEmbedder : uint16_t {
kEmbedderElectron = gin::kEmbedderFuchsia + 1,
};
但 MakeWrapperInfo 用的是 kEmbedderNativeGin。为什么定义了 kEmbedderElectron 却不用?
因为 kEmbedderElectron 的用途不同:它是给 gin::PerIsolateData 的 embedder 分类用的(在 V8Initializer 之类的地方标记"这个 isolate 是 Electron 的"),而 WrapperInfo.embedder 是"这个 wrapper 是谁创建的"——Electron 的 wrapper 都是 gin 创建的,所以是 kEmbedderNativeGin。
gin_embedders.h 里还有一段精巧的代码:
namespace internal {
// Keep this switch exhaustive so adding a GinEmbedder upstream fails
// the build instead of silently colliding with kEmbedderElectron.
constexpr bool IsKnownGinEmbedder(gin::GinEmbedder embedder) {
switch (embedder) {
case gin::kEmbedderNativeGin:
case gin::kEmbedderBlink:
case gin::kEmbedderPDFium:
case gin::kEmbedderFuchsia:
return true;
}
return false;
}
} // namespace internal
enum ElectronGinEmbedder : uint16_t {
kEmbedderElectron = gin::kEmbedderFuchsia + 1,
};
static_assert(internal::IsKnownGinEmbedder(gin::kEmbedderFuchsia));
这是一个"上游加值我要知道"的哨兵。
switch 没有 default 分支,而函数返回 bool。在 GCC/Clang 的 -Wswitch 下(Chromium 构建默认开),如果上游给 GinEmbedder 加了一个新枚举值,这个 switch 会报"未处理的枚举值"警告,警告升级为错误,构建失败。
失败信息会指向这个文件,注释立刻告诉你原因:"上游加了 embedder,Electron 的 kEmbedderFuchsia + 1 现在撞上了"。
static_assert(IsKnownGinEmbedder(kEmbedderFuchsia)) 是第二道保险:确认 kEmbedderFuchsia 仍然是最后一个已知值(如果上游在 Fuchsia 之后加了新值,ElectronGinEmbedder 的 +1 就撞了)。
这两行代码解决的是一个跨仓库的 API 演进问题。 Electron 依赖 Chromium 的一个枚举的当前最大值——这是脆弱的耦合。用编译期断言把"脆弱"变成"构建失败",是这类问题的标准解法。
7.7.3 三条 static_assert
wrappable_pointer_tags.h 的末尾有三条断言,一条比一条严格:
第一条:Electron 的 tag 必须在 gin 之后。
static_assert(static_cast<uint16_t>(kElectronApp) >
static_cast<uint16_t>(gin::kLastPointerTag),
"Electron tags must start after gin's last tag.");
这条断言检查的是枚举定义里那个 = gin::kLastPointerTag + 1。如果上游给 gin 加了新 tag,kLastPointerTag 变大,kElectronApp 自动跟着变大——断言永远成立。这条断言其实是给"有人手改了 +1 为 +0"这种情况兜底。
第二条:全部 tag 必须在 V8 的合法范围里。
static_assert(
kLastElectronPointerTag <
static_cast<uint16_t>(v8::CppHeapPointerTag::kZappedEntryTag),
"The defined Electron type tags exceed the range of allowed tags. "
"Reduce the number of tags or adjust gin::kFirstPointerTag so that "
"all values fit.");
v8::CppHeapPointerTag::kZappedEntryTag 是 V8 保留的上界("zapped" 表示已清除的条目)。所有合法的 tag 必须小于它。
这条断言的错误消息给出了解法:"Reduce the number of tags or adjust gin::kFirstPointerTag"。错误消息里带解法,是 Chromium 代码库的惯例,值得学。
第三条:必须避开 Node 的 cppgc tag。
static_assert(static_cast<uint16_t>(kLastElectronPointerTag) <
EMBEDDER_CPPHEAP_POINTER_TAG,
"gin + Electron tags must stay below the CppHeapPointerTag "
"used by Node.js for cppgc wrappables.");
这是三条里最微妙的一条,注释解释了背景:
Electron's tags extend gin's range (they start at gin::kLastPointerTag + 1), so the combined gin + Electron tag range must stay below the tag Node.js uses for its cppgc wrappables. That value is provided by the EMBEDDER_CPPHEAP_POINTER_TAG define on the libnode GN target (see third_party/electron_node/unofficial.gni and src/cppgc_helpers.h). If this fires, the gin + Electron tag range has grown into Node's tag.
三个系统共用一套 tag 空间: gin(Chromium 的绑定库)、Electron(45 个 API 类型)、Node(它的 cppgc wrappables)。
分配是:
[gin 的范围] [Electron 的 45 个] [ ... 空隙 ... ] [Node 的 EMBEDDER_CPPHEAP_POINTER_TAG]
↑
Electon 不能长到这里
为什么这很重要?因为 Electron 的进程里同时有 gin 对象和 Node 的 cppgc 对象,它们在同一个 V8 heap 上。如果一个 Electron 对象的 tag 恰好等于 Node 的 tag,那么 v8::Object::Unwrap<...> 在判断"这是不是 Node 的 cppgc 对象"时会误判——把一个 BrowserWindow 当成 Node 的某个内部对象,调用错误的虚函数。
这不是理论风险。blink::ProcessHeap::TotalAllocatedObjectSize() 之类的地方会遍历 cppgc 堆,按 tag 分类统计。tag 撞了,统计就错了。
EMBEDDER_CPPHEAP_POINTER_TAG 是一个编译期宏,由 GN 目标 libnode 定义(third_party/electron_node/unofficial.gni)。这意味着这条 static_assert 是两个构建目标之间的契约——electron_lib 和 libnode 的 tag 分配必须协调。
这也是第 3 章讲的"380 个补丁"里 Node 补丁集的一部分:EMBEDDER_CPPHEAP_POINTER_TAG 这个宏是 Electron 给 Node 加的,用来让两边能编译期对齐。
7.7.4 wrapper_info() 与 kWrapperInfo
每个 cppgc 版 API 类都有三个静态成员:
// electron_api_event.h
class Event final : public gin::Wrappable<Event>,
public gin_helper::Constructible<Event> {
public:
static gin::WrapperInfo kWrapperInfo;
const gin::WrapperInfo* wrapper_info() const override;
const char* GetHumanReadableName() const override;
...
};
实现:
// event.cc
gin::WrapperInfo Event::kWrapperInfo =
electron::MakeWrapperInfo(electron::kElectronEvent);
const gin::WrapperInfo* Event::wrapper_info() const {
return &kWrapperInfo;
}
const char* Event::GetHumanReadableName() const {
return "Electron / Event";
}
kWrapperInfo 是静态的、全局唯一的——每个类型一份。V8 在创建 wrapper 时把这个指针写进对象的 cppgc header(或 internal field 0,取决于 gin 的版本)。
wrapper_info() 是虚函数,返回 &kWrapperInfo。它存在的原因是:基类指针(gin::Wrappable<T>*)需要能问到实际类型的 tag。如果 T 是多态的(比如 BrowserWindow 继承 BaseWindow,两者都是 gin::Wrappable),虚函数保证拿到的是最派生类的 tag。
这解释了一个现象:
const win = new BrowserWindow()
// 传给期望 BaseWindow 的 API
BaseWindow.fromId(win.id) // 能工作
BaseWindow::FromId 走 FromV8Impl(isolate, val, &BaseWindow::kWrapperInfo)。win 的 tag 是 kElectronBrowserWindow,不等于 kElectronBaseWindow——检查失败?
不。 因为 BrowserWindow 的 CreateConstructor 里 Inherit(BaseWindow::GetConstructorTemplate(isolate))。Inherit 让 BrowserWindow 的实例模板继承 BaseWindow 的——但 tag 是实例上的,不是模板上的。
真正的机制在 gin::Wrappable<T> 的 FromV8:它不只比较 tag,还会沿着类的继承链尝试。具体实现依赖 gin 的版本,但语义是"如果 T 是 U 的基类,U 的实例能转成 T*"。
这条路径在 Electron 里被反复使用:BrowserWindow → BaseWindow、WebContentsView → View、Menu → MenuItem。每一次转换都依赖 tag + 继承信息的双重判断。
7.8 function_template.h:一个模板替掉十五个宏
function_template.h 有 573 行,是整个 gin_helper 里最长的文件。它的职责单一:把一次 JS 调用变成一次 C++ 调用,并把参数搬过去、把返回值搬回来。
Electron 早期用 native_mate 的宏体系做这件事:
// 早期写法(已删除)
MATE_METHOD(WebContents, LoadURL) {
std::string url;
mate::Dictionary options;
if (!args->GetNext(&url) || !args->GetNext(&options))
return;
self->LoadURL(GURL(url), ...);
}
每个方法一个宏,每个宏展开成一段 v8::FunctionCallback 的样板代码:取参数、检查数量、转类型、调方法、处理返回值、抛异常。重复、易错、无法静态检查。
现在的写法是一行:
.SetMethod("loadURL", &WebContents::LoadURL)
从宏到模板,省掉的是"样板",但补上的是"三件宏做不到的事"。文件头的注释只说了两件:
// This file is forked from gin/function_template.h with 2 differences:
// 1. Support for additional types of arguments.
// 2. Support for warning using destroyed objects.
第三件注释没说,但在代码里:微任务检查点的正确性(MaybeMicrotasksScope)。
7.8.1 Invoker 的继承技巧
最精妙的一段是这个:
template <size_t... indices, typename... ArgTypes>
class Invoker<std::index_sequence<indices...>, ArgTypes...>
: public ArgumentHolder<indices, ArgTypes>... {
CPPGC_STACK_ALLOCATED();
public:
// Invoker<> inherits from ArgumentHolder<> for each argument.
// C++ has always been strict about the class initialization order,
// so it is guaranteed ArgumentHolders will be initialized (and thus, will
// extract arguments from Arguments) in the right order.
Invoker(gin::Arguments* args, const InvokerOptions& invoker_options)
: ArgumentHolder<indices, ArgTypes>(args, invoker_options)...,
args_(args) {}
多重继承 + 变参展开,用来保证"参数按顺序提取"。
Invoker<index_sequence<0,1,2>, string, int, bool> 展开成:
class Invoker : public ArgumentHolder<0, string>,
public ArgumentHolder<1, int>,
public ArgumentHolder<2, bool> {
Invoker(args) : ArgumentHolder<0, string>(args),
ArgumentHolder<1, int>(args),
ArgumentHolder<2, bool>(args) {}
};
C++ 标准规定:基类的初始化顺序由基类列表中的出现顺序决定,与成员初始化列表的书写顺序无关(成员则由声明顺序决定,这也是第 5 章 5.4 节提到的那个坑)。
所以 ArgumentHolder<0> 先构造 → 调 GetNextArgument(args, 0) → args->GetNext(&value)。gin::Arguments 内部有一个游标 next_,每次 GetNext 取一个并前进。三个 ArgumentHolder 依次构造,就依次取走了三个参数。
这个技巧的价值在于:不需要手写 N 个特化。
朴素做法是给 1 参、2 参、3 参……各写一个特化,写到 12 个参数就没人维护了。变参 + 多重继承让一个模板覆盖任意参数个数。
代价是可读性。 一个刚接触这段代码的人看到 ArgumentHolder<indices, ArgTypes>... 会愣住。注释里那句 "C++ has always been strict about the class initialization order" 就是在解释这个"为什么这样能工作"。
CPPGC_STACK_ALLOCATED() 是 V8 的宏,展开成 operator new 被删除——防止有人在堆上分配 Invoker。它必须在栈上(它的生命周期就是一次调用)。
std::optional<v8::LocalVector<T>> 那个特化是为了不可默认构造的类型:
template <size_t index, typename ArgType>
struct ArgumentHolder<
index,
ArgType,
std::enable_if_t<!std::is_default_constructible_v<
typename CallbackParamTraits<ArgType>::LocalType> &&
std::is_constructible_v<
typename CallbackParamTraits<ArgType>::LocalType,
v8::Isolate*>>> {
ArgLocalType value;
bool ok;
ArgumentHolder(gin::Arguments* args, const InvokerOptions& invoker_options)
: value(args->isolate()),
ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
v8::LocalVector<T> 没有默认构造函数(它需要一个 isolate 来分配 backing store),所以 value 必须在初始化列表里用 args->isolate() 构造。这个特化让"返回 std::vector<v8::Local<v8::Value>>"这类 API 成为可能。
7.8.2 Dispatcher 与 DirectDispatcher:有 holder 与没 holder
两条路径,取决于目标是不是编译期已知。
路径一:CreateFunctionTemplate(isolate, callback) —— 有 CallbackHolder。
template <typename Sig>
v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
v8::Isolate* isolate,
base::RepeatingCallback<Sig> callback,
InvokerOptions invoker_options = {}) {
typedef CallbackHolder<Sig> HolderT;
HolderT* holder =
new HolderT(isolate, std::move(callback), std::move(invoker_options));
v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
isolate, &Dispatcher<Sig>::DispatchToCallback,
gin::ConvertToV8<v8::Local<v8::External>>(isolate,
holder->GetHandle(isolate)),
v8::Local<v8::Signature>(), 0, v8::ConstructorBehavior::kAllow);
return tmpl;
}
holder 是一个堆上分配的 CallbackHolder<Sig>,它持有 base::RepeatingCallback<Sig> 和 InvokerOptions。它被包装成一个 v8::External,作为 v8::FunctionTemplate 的 data。
调用时(Dispatcher::DispatchToCallbackImpl):
static void DispatchToCallbackImpl(gin::Arguments* args) {
v8::Local<v8::External> v8_holder;
CHECK(args->GetData(&v8_holder));
CallbackHolderBase* holder_base = reinterpret_cast<CallbackHolderBase*>(
v8_holder->Value(v8::kExternalPointerTypeTagDefault));
typedef CallbackHolder<ReturnType(ArgTypes...)> HolderT;
HolderT* holder = static_cast<HolderT*>(holder_base);
using Indices = std::index_sequence_for<ArgTypes...>;
Invoker<Indices, ArgTypes...> invoker(args, holder->invoker_options);
if (invoker.IsOK())
invoker.DispatchToCallback(holder->callback);
}
四步:取 data → 转 holder → 造 invoker → 调。每一步都是固定的。
CallbackHolderBase 的生命周期是个独立问题。 它由谁释放?
// CallbackHolderBase 有两个清理路径:
// - If the garbage collector finds that it's garbage and collects it. (But note
// that even _if_ we become garbage, we might never get collected!)
// - If the isolate gets disposed.
注释里的感叹号是真诚的:GC 不保证跑。所以每个 holder 都注册了一个 DisposeObserver,在 isolate 拆除时统一释放。
而 CallbackHolderBase 还有一个静态方法专门处理"没有 gin 的 isolate":
// Frees the holders created in `isolate` when it has no gin::PerIsolateData,
// as a Node.js worker's isolate does. gin never reports the disposal of such
// an isolate, and V8 does not run weak callbacks when it disposes one, so
// without this the holders leak. Call it on the isolate's thread once no
// more JavaScript will run there.
static void DisposeAllInIsolateWithoutGin(v8::Isolate* isolate);
这是第 6 章 worker 问题的另一面。 Node 的 worker 线程里创建的 isolate 没有 gin::PerIsolateData(因为那个 isolate 不是 gin 创建的)。而 gin 的 DisposeObserver 依赖 PerIsolateData。所以 worker 销毁时,没人通知 holder。
DisposeAllInIsolateWithoutGin 是手工补的清理点,由 WebWorkerObserver 在 worker 关闭时调用。
路径二:CreateFunctionTemplate<&T::Method>(isolate) —— 没有 holder。
template <auto kTarget>
requires(kIsFunctionOrMethodPointer<decltype(kTarget)>)
v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(v8::Isolate* isolate) {
return v8::FunctionTemplate::New(
isolate, &DirectDispatcher<kTarget>::DispatchToTarget,
v8::Local<v8::Value>(), v8::Local<v8::Signature>(), 0,
v8::ConstructorBehavior::kAllow);
}
v8::FunctionTemplate::New 的第三个参数(data)是空的 v8::Local<v8::Value>()——没有 holder,没有堆分配。
目标函数是模板参数 kTarget,编译期已知,直接生成一个 thunk:
template <auto kTarget>
struct DirectDispatcher {
static void DispatchToTarget(
const v8::FunctionCallbackInfo<v8::Value>& info) {
SignatureDispatcher<decltype(kTarget)>::Run(info, kTarget);
}
};
Run 里唯一和路径一不同的是 InvokerOptions:
static void Run(gin::Arguments* args, Target target) {
static constexpr InvokerOptions kOptions = {.holder_is_first_argument =
is_method};
Invoker<std::index_sequence<indices...>, RunArgs...> invoker(args, kOptions);
if (invoker.IsOK()) {
invoker.DispatchToTarget(target);
}
}
is_method 是模板参数(成员函数为 true,自由函数为 false),kOptions 是 constexpr——编译器能把它完全内联。
这就是为什么 ObjectTemplateBuilder 有两个 SetMethod 重载:
template <typename T>
ObjectTemplateBuilder& SetMethod(const std::string_view name,
const T& callback) {
return SetImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, callback));
}
// Naming the target as a template argument instead of passing it as a value
// lets the call go straight from V8 to it, with no callback object to store,
// unwrap and run through. Prefer it wherever the target is a plain function
// or member function; the overload above is still what a bound callback
// needs.
template <auto kTarget>
ObjectTemplateBuilder& SetMethod(const std::string_view name) {
return SetImpl(name, CreateFunctionTemplate<kTarget>(isolate_));
}
注释说得很清楚:优先用模板参数版本。差别是:
| 值参数版 | 模板参数版 | |
|---|---|---|
| 堆分配 | 每个方法一个 CallbackHolder | 零 |
| 每次调用 | 取 data、reinterpret_cast、解引用 | 直接跳转 |
| 参数绑定 | 可以 base::BindRepeating 带状态 | 必须无状态 |
| 代码大小 | 小(共享 Dispatcher) | 大(每个方法一个 thunk) |
"代码大小"是后者唯一的代价:DirectDispatcher<kTarget> 每个目标实例化一个 thunk,几百个方法几百个 thunk,但每个只有几条指令。收益是每次 SetMethod 少一次堆分配、每次调用少两次间接寻址,乘以几百个方法后可测。
有意思的是:并不是所有地方都换成了模板版本。 比如 electron_api_power_save_blocker.cc 还是:
.SetMethod("start", &PowerSaveBlocker::Start)
这里 &PowerSaveBlocker::Start 匹配的是值参数重载(const T& callback),不是模板版本(模板版本要写 SetMethod<&PowerSaveBlocker::Start>("start"))。
所以代码库现在两种写法并存。这是一次进行中的优化——和 7.6 节的 cppgc 迁移一样,结构改了一半。
7.8.3 MaybeMicrotasksScope:一个没人注意的正确性问题
// Blink runs microtasks when the outermost MicrotasksScope closes (kScoped),
// so a bound call in the renderer needs one. Where Node owns the checkpoint
// (kExplicit: the browser and utility processes) a scope never runs anything
// and every native-to-JS entry point already holds one, so skip it there,
// along with the creation-context lookup it needs.
class MaybeMicrotasksScope {
CPPGC_STACK_ALLOCATED();
public:
explicit MaybeMicrotasksScope(gin::Arguments* args);
~MaybeMicrotasksScope();
private:
std::optional<v8::MicrotasksScope> scope_;
};
这是第 6 章 6.8 节"微任务三层仲裁"在调用层的落地。
问题:JS 调 C++ → C++ 里调了一个 JS 回调(比如 Menu 的 click handler)→ 回调里 Promise.resolve().then(fn) → fn 什么时候跑?
答案取决于谁负责检查点:
- browser / utility 进程(
kExplicit):Node 负责。每次从 C++ 进 JS 都开一个node::CallbackScope(NodeEntryScope做这事),它的析构会跑process.nextTick队列和微任务队列。 - renderer(
kScoped):Blink 负责。v8::MicrotasksScope的最外层析构时自动跑微任务。
如果 renderer 里不创建 scope,微任务会延迟到下一个 Blink 任务才跑——await 之后的代码看起来"卡了一帧"。这就是为什么 MaybeMicrotasksScope 在 kScoped 下必须存在。
如果 browser 里创建了 scope,它什么也不做(kExplicit 下 MicrotasksScope 是 no-op),但构造时要做一次 holder->GetCreationContext() 的查找——白花的开销。所以 skip。
判断条件在 .cc 里(MaybeMicrotasksScope 的构造函数):
MaybeMicrotasksScope::MaybeMicrotasksScope(gin::Arguments* args) {
if (args->isolate()->GetMicrotasksPolicy() != v8::MicrotasksPolicy::kScoped)
return;
...创建 scope_...
}
GetMicrotasksPolicy() 是 isolate 级的查询——这就是第 6 章说的"按入口切换"。第 6 章的 ExplicitMicrotasksScope 在 uv 回调入口临时把策略切成 kExplicit,这里读到的就是切换后的值。
同一个 isolate,同一个 GetMicrotasksPolicy(),在第 6 章和第 7 章分别被两个组件读。 一个写、一个读,接口就是一个 enum。
7.8.4 ThrowConversionError:一条能救命的错误消息
function_template.cc:144
void ThrowConversionError(gin::Arguments* args,
const InvokerOptions& invoker_options,
size_t index) {
if (index == 0 && invoker_options.holder_is_first_argument) {
// Failed to get the appropriate `this` object. Either the native object
// behind it has been destroyed - its wrapper then no longer converts - or
// the method was invoked using Function.prototype.[call|apply] with an
// invalid (or null) `this` argument. Telling the two apart here, after
// the conversion has failed, keeps the check off every successful call.
v8::Local<v8::Object> holder;
if (args->GetHolder(&holder) && Destroyable::IsDestroyed(holder)) {
args->ThrowTypeError("Object has been destroyed");
return;
}
std::string error =
invoker_options.holder_type
? base::StrCat({"Illegal invocation: Function must be "
"called on an object of type ",
invoker_options.holder_type})
: "Illegal invocation";
args->ThrowTypeError(error);
} else {
// Otherwise, this failed parsing on a different argument.
// Arguments::ThrowError() will try to include appropriate information.
// Ideally we would include the expected c++ type in the error message
// here, too (which we can access via typeid(ArgType).name()), however we
// compile with no-rtti, which disables typeid.
args->ThrowError();
}
}
三个设计决策,每个都值得学。
决策一:只在失败后判断,不在成功路径上加检查。
注释写明:"Telling the two apart here, after the conversion has failed, keeps the check off every successful call."
如果每次调用都先检查 IsDestroyed,那是几百万次调用里的一次多余分支。放到失败路径上,正常情况零成本。
这是错误处理的基本功:错误路径可以慢,成功路径不行。
决策二:区分"已销毁"和"非法调用"。
两种失败长得一样(FromV8 都返回 nullptr),但原因完全不同:
- 对象已销毁 →
TypeError: Object has been destroyed fn.call(null)或fn.call({})→TypeError: Illegal invocation: Function must be called on an object of type BaseWindow
错误消息不同,用户能查到的方向就不同。第一条会让人去查"我是不是在窗口关闭后还调了它",第二条会让人去查"我的 this 为什么丢了"。
注意 holder_type 可能为 null:InvokerOptions 里
struct InvokerOptions {
bool holder_is_first_argument = false;
const char* holder_type = nullptr; // Null if unknown or not applicable.
};
holder_type 由 CallbackTraits 的成员函数特化传入吗?回看 7.4.3 节——没有传:
InvokerOptions invoker_options = {.holder_is_first_argument = true};
所以大部分方法是 Illegal invocation,没有类型名。只有显式传了 holder_type 的地方(少数手写 CreateFunctionTemplate 调用)才有详细消息。
这是一个可以改进但一直没改进的地方。 技术原因:要拿到类型名,需要一个 per-type 的字符串;CallbackTraits 只有 T(成员函数指针的类型),提取 C 需要额外的模板元编程。可以用 typeid(C).name(),但注释说了 "we compile with no-rtti, which disables typeid"。
no-rtti 是 Chromium 的构建约定(省二进制大小 + 避免 RTTI 的失败模式)。所以只能靠手写字符串,而手写要改几百个 SetMethod 调用。
决策三:非 holder 参数失败一律 args->ThrowError()。
gin::Arguments::ThrowError() 会生成 Error: Invalid arguments 之类的通用消息。注释承认这不理想,但又说明了为什么不做更好:没有 RTTI,拿不到 C++ 类型名。
这条注释是技术写作的范本:它不掩饰缺陷,说明了缺陷的成因,并给出了"如果要修该修哪里"。
7.9 EventEmitter:三个名字,一套语义
app.on('ready') 能工作,背后有三个不同的东西叫 "EventEmitter":
| 名字 | 位置 | 是什么 |
|---|---|---|
gin_helper::EventEmitter<T> | event_emitter.h | 旧一代的 C++ mixin(Emit + Wrappable) |
gin_helper::EventEmitterMixin<T> | event_emitter_mixin.h | 新一代的 C++ mixin(同时支持两代 wrapper) |
gin_helper::CreateNodeEventEmitterConstructor | node_event_emitter.h | 纯 C++ 实现的 Node EventEmitter(无 Node 环境时用) |
加上 JS 侧那个真正的 EventEmitter.prototype,一共四份。搞清它们的分工,才能理解 app.emit('x') 到底走到哪。
7.9.1 EventEmitterMixin:if constexpr 兼容两代
event_emitter_mixin.h:20
template <typename T>
class EventEmitterMixin {
public:
template <typename... Args>
bool Emit(const std::string_view name, Args&&... args) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;
if (!static_cast<T*>(this)->GetWrapper(isolate).ToLocal(&wrapper))
return false;
internal::Event* event = internal::Event::New(isolate);
v8::Local<v8::Object> event_object =
event->GetWrapper(isolate).ToLocalChecked();
gin_helper::EmitEvent(isolate, wrapper, name, event_object,
std::forward<Args>(args)...);
return event->GetDefaultPrevented();
}
Emit 做四件事:
GetWrapper(isolate)—— 拿 JS 对象。拿不到就return false(对象已死,事件无人可发)。internal::Event::New(isolate)—— 造一个Event对象(gin_helper::internal::Event,一个 cppgc 版 wrappable)。EmitEvent(...)—— 调wrapper.emit(name, event, ...args)。event->GetDefaultPrevented()—— 返回事件是否被preventDefault()。
preventDefault 的语义值得说。Electron 的 Event 对象(不是 DOM 的 Event)有两个方法:
// gin_helper/event.cc
v8::Local<v8::ObjectTemplate> Event::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
return gin::ObjectTemplateBuilder(isolate, GetClassName(), templ)
.SetMethod("preventDefault", &Event::PreventDefault)
.SetProperty("defaultPrevented", &Event::GetDefaultPrevented)
.Build();
}
void PreventDefault() { default_prevented_ = true; }
bool GetDefaultPrevented() { return default_prevented_; }
于是 app.quit() 的实现可以这样:
bool App::Quit() {
if (Emit("before-quit")) // 有人 preventDefault 了
return false; // 取消退出
...
}
Emit 返回 bool 而不是 void,就是为了这个。 这是从 DOM 借来的模式(event.preventDefault() + dispatchEvent 返回 false),但在 Node 的 EventEmitter 里不存在——Node 的 emit 只返回"有没有监听器"。
Electron 把两者混在了一起:emit 的返回值既是"有没有监听器"又是"有没有被 preventDefault"。这在 JS 侧会造成困惑:
app.on('before-quit', (e) => e.preventDefault())
app.emit('before-quit') // 返回什么?
App::Quit() 里拿到 true(被 prevent),但 JS 侧 app.emit(...) 的返回值来自 Node 的 EventEmitter.prototype.emit,它返回"有没有监听器"(true)。
所以 C++ 的 Emit 和 JS 的 emit 返回语义不同。 这是一个真实的、长期存在的不一致,文档里没写,只能读源码发现。
GetObjectTemplateBuilder 里的 if constexpr 是兼容两代的关键:
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate* isolate) {
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
auto* wrapper_info = &(static_cast<T*>(this)->kWrapperInfo);
// DeprecatedWrapperInfo support will be removed as part of
// https://github.com/electron/electron/issues/47922
constexpr bool is_deprecated_wrapper =
std::is_same_v<decltype(wrapper_info), gin::DeprecatedWrapperInfo*>;
v8::Local<v8::FunctionTemplate> constructor;
if constexpr (is_deprecated_wrapper) {
constructor = data->DeprecatedGetFunctionTemplate(wrapper_info);
} else {
constructor = data->GetFunctionTemplate(wrapper_info);
}
const char* class_name = "";
if constexpr (is_deprecated_wrapper) {
class_name = static_cast<T*>(this)->GetTypeName();
} else {
class_name = static_cast<T*>(this)->GetClassName();
}
...
}
std::is_same_v<decltype(wrapper_info), gin::DeprecatedWrapperInfo*> 这个判断本身就是一门手艺。
T::kWrapperInfo 的类型决定了一切:
- 旧一代:
static gin::DeprecatedWrapperInfo kWrapperInfo;→decltype(&kWrapperInfo)=DeprecatedWrapperInfo* - 新一代:
static gin::WrapperInfo kWrapperInfo;→decltype(&kWrapperInfo)=WrapperInfo*
if constexpr 保证另一个分支不被实例化——所以旧一代的 T 不需要有 GetClassName()(它只有 GetTypeName()),新一代的 T 不需要有 GetTypeName()。
如果用普通的 if,两个分支都会编译,两代类型都会缺一个方法,编译失败。 这是 if constexpr 存在的核心理由:类型分派,而不是值分派。
而且注意 constexpr bool 那一行——它不是 if constexpr (std::is_same_v<...>) 直接写,而是先赋给一个 constexpr 变量。这样错误消息里会出现 is_deprecated_wrapper 这个名字,比一长串 std::is_same_v<...> 可读。
constructor->Inherit(internal::GetEventEmitterTemplate(isolate)) 是 prototype 链接的 C++ 侧:
// event_emitter_template.cc
v8::Local<v8::FunctionTemplate> GetEventEmitterTemplate(v8::Isolate* isolate) {
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
v8::Local<v8::FunctionTemplate> tmpl =
data->DeprecatedGetFunctionTemplate(&kWrapperInfo);
if (tmpl.IsEmpty()) {
tmpl = v8::FunctionTemplate::New(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Function> func = tmpl->GetFunction(context).ToLocalChecked();
v8::Local<v8::Object> eventemitter_prototype =
electron::GetEventEmitterPrototype(isolate);
v8::Local<v8::Value> func_prototype;
CHECK(func->Get(context, gin::StringToSymbol(isolate, "prototype"))
.ToLocal(&func_prototype));
CHECK(func_prototype.As<v8::Object>()
->SetPrototype(context, eventemitter_prototype)
.ToChecked());
data->DeprecatedSetFunctionTemplate(&kWrapperInfo, tmpl);
}
return tmpl;
}
这段代码做了一件 V8 里不太常见的事:把一个 FunctionTemplate 的 prototype 对象的 [[Prototype]] 指向一个运行时的 JS 对象。
tmpl (FunctionTemplate)
└─ .prototype (普通对象)
└─ [[Prototype]] ──> Node 的 EventEmitter.prototype
于是 Inherit(tmpl) 之后,任何继承它的类的实例,原型链是:
win ──> BrowserWindow.prototype ──> BaseWindow.prototype
└─ [[Prototype]] ──> EventEmitter.prototype
这就是为什么 win.on('closed') 能工作——on 来自 EventEmitter.prototype,而它是运行时从 JS 侧塞进来的(第 5 章 5.7.2 第 1 段)。
这个设计的脆弱性:GetEventEmitterPrototype 里有个 CHECK:
v8::Local<v8::Object> GetEventEmitterPrototype(v8::Isolate* isolate) {
CHECK(!GetEventEmitterPrototypeReference()->IsEmpty());
return GetEventEmitterPrototypeReference()->Get(isolate);
}
如果 lib/browser/init.ts 那行 setEventEmitterPrototype 没有在第一个 EventEmitterMixin 对象创建之前跑,就会 CHECK 失败。
这就是为什么那行必须是 init.ts 的第一行(第 5 章 5.7.2 讲的"第 1 段")。顺序错了,整个应用起不来,而且错误信息是 CHECK failed 而不是"prototype 没设置"。
7.9.2 EmitEvent:v8::EscapableHandleScope 的双重作用
event_emitter_caller.h:24
template <typename... Args>
v8::Local<v8::Value> EmitEvent(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const std::string_view name,
Args&&... args) {
v8::EscapableHandleScope scope{isolate};
std::array<v8::Local<v8::Value>, 1U + sizeof...(args)> converted_args = {
gin::StringToSymbol(isolate, name),
gin::ConvertToV8(isolate, std::forward<Args>(args))...,
};
return internal::CallMethodWithArgs(scope, isolate, obj, "emit",
converted_args);
}
v8::EscapableHandleScope 只能 escape 一个 handle。CallMethodWithArgs 把这个约束变成了编译期强制——第一个参数是 v8::EscapableHandleScope&(引用,不是指针):
// Allocates handles in (and escapes the result through) the caller's |scope|,
// so a caller that forgets to open one is a compile error rather than a slow
// per-call handle leak.
v8::Local<v8::Value> CallMethodWithArgs(v8::EscapableHandleScope& scope, ...);
忘了开 HandleScope 的症状是内存缓慢增长,不是崩溃,在生产里要几周才被注意到。用类型系统强制它,是零成本的正确性。
converted_args 是编译期定长的 std::array(事件名占第 0 位),没有 vector、没有堆分配。StringToSymbol 每次重新内部化事件名——InternedString(7.11.2)就是为此而生的优化,但事件名通常只有几十个,V8 的内部化表会缓存,实际开销很小。
7.9.3 node_event_emitter:沙箱渲染进程里的纯 C++ EventEmitter
第四个 EventEmitter 是最特殊的一个。看它的注释:
// shell/common/gin_helper/node_event_emitter.h
// Creates a native implementation of Node.js's `EventEmitter` class for
// `context`, for use in script contexts that have no Node.js environment
// (sandboxed renderers and service worker preload realms). It provides the
// instance API (on/once/off/emit/prependListener/removeAllListeners/
// listeners/rawListeners/listenerCount/eventNames/setMaxListeners/
// getMaxListeners, the 'newListener' and 'removeListener' events and the
// max-listener warning) and `EventEmitter.defaultMaxListeners`; the module
// level helpers of `node:events` are not included.
场景:沙箱化的渲染进程(sandbox: true)。这种进程里没有 Node 环境——require('events') 不可用,EventEmitter.prototype 不存在。
但 ipcRenderer 需要 on('message')。所以需要一份 C++ 实现的 EventEmitter。
实现要点(注释第二段):
// As in lib/events.js, listener state lives in the instance's own `_events` /
// `_eventsCount` / `_maxListeners` properties, so the methods are generic over
// their receiver and JavaScript classes can extend the constructor.
三个内部属性名照抄 Node 的实现:_events、_eventsCount、_maxListeners。
为什么必须照抄? 因为真实的库会读它们:
class MyEmitter extends EventEmitter {}
const e = new MyEmitter()
e.on('x', fn)
console.log(e._events) // 用户会读这个
if (emitter._events.error) {} // 库会这样探测
_events 是一个无原型对象,键是事件名,值是函数或函数数组。换一种内部结构就会破坏这些库,所以照抄。
EmitEvent 的第三个函数:
// `emitter.emit(type, ...args)`. When `emitter` is an instance of the class
// above the listeners are invoked directly from C++; for any other object
// (a Node.js EventEmitter in a renderer with Node.js integration) its `emit`
// method is called. Returns false if an exception was thrown; it is left
// pending for the caller's v8::TryCatch.
bool EmitEvent(v8::Isolate* isolate,
v8::Local<v8::Object> emitter,
v8::Local<v8::Value> type,
base::span<v8::Local<v8::Value>> args);
双路径分派:如果 emitter 是 C++ 版 EventEmitter 的实例,直接 C++ 调用监听器(快);否则调它的 emit 方法(兼容 Node 的 EventEmitter)。
返回值语义也不同:"Returns false if an exception was thrown; it is left pending for the caller's v8::TryCatch"——返回 false 表示有异常,而且异常留在 isolate 里,调用方必须自己 TryCatch 处理。
这是 C++ 里传递异常的标准做法:不要吞掉,也不要 ReThrow(那会破坏调用方的栈展开),让它 pending,由最近的有能力处理的人处理。
7.10 Promise 与 SafeV8Function:两个方向的异步
调用是同步的,异步需要另外两个机制:C++ 要给 JS 一个 Promise,JS 要给 C++ 一个回调。
7.10.1 PromiseBase::SettleScope 的四件套
promise.h:95
struct SettleScope {
CPPGC_STACK_ALLOCATED();
public:
explicit SettleScope(const PromiseBase& base);
~SettleScope();
v8::HandleScope handle_scope_;
v8::Local<v8::Context> context_;
v8::MicrotasksScope microtasks_scope_;
v8::Context::Scope context_scope_;
};
四个成员,声明顺序就是构造顺序,也是析构的逆序。
构造顺序:HandleScope → Local<Context> → MicrotasksScope → Context::Scope。
为什么是这个顺序?
HandleScope必须最先。后续所有 V8 操作都在它里面分配 handle。没有它,handle 泄漏到外层(可能是整个进程的生命周期)。context_必须在Context::Scope之前初始化。Context::Scope的构造函数需要一个 context 参数。MicrotasksScope在Context::Scope之前。这是 V8 的要求:MicrotasksScope绑定到当前 context 的微任务队列,所以 context 必须已经"准备好"——但"准备好"是指 isolate 知道它是哪个 context,不是指它被 Enter。V8 的文档说MicrotasksScope应该在 context 已进入后创建……
析构顺序(逆序):Context::Scope → MicrotasksScope → context_ → HandleScope。
关键在 MicrotasksScope 的析构:它会跑微任务队列(在 kScoped 策略下)。而此时 Context::Scope 已经退出——微任务在"不是当前 context"的状态下跑?
不。 因为 Context::Scope 的析构是"恢复到进入前的 context",而 SettleScope 通常在一个更大的 scope 里。所以微任务仍然在正确的 context 里跑。
这个顺序上的微妙之处没有注释解释。它是一个"必须这样,但没人写为什么"的地方——典型的隐性知识。改动它会在某些边界场景下崩溃,而崩溃原因极难定位。
PromiseBase::Resolve 的用法:
template <typename T>
v8::Maybe<bool> Resolve(const T& value) {
if (!IsAlive())
return v8::Nothing<bool>();
SettleScope settle_scope{*this};
return GetInner()->Resolve(settle_scope.context_,
gin::ConvertToV8(isolate(), value));
}
IsAlive() 在最前面:
bool PromiseBase::IsAlive() const {
return !handle_.Get()->isolate_.IsEmpty() && ...;
}
一个 Promise 可能"已死" —— 如果它所属的 context 被销毁了(比如 frame 导航走了),promise 的 resolver 就无效了。这时 Resolve 必须静默失败,不能崩。
v8::Maybe<bool> 而不是 bool:区分"成功"(Just(true))、"失败"(Just(false))、"无法执行"(Nothing())。V8 的三态返回值是它 API 的一贯风格。
7.10.2 cppgc::Persistent<PromiseHandle>
class PromiseBase {
...
private:
raw_ptr<v8::Isolate> isolate_;
cppgc::Persistent<PromiseHandle> handle_;
};
PromiseHandle 是一个 cppgc 对象,内部持有 v8::Global<v8::Promise::Resolver>。
为什么不用 v8::Global 直接存?
因为 PromiseBase 是可移动的(PromiseBase(PromiseBase&&)),而且会作为参数传进 base::BindOnce:
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(promise), base::GetCurrentProcId())
v8::Global 是可移动的,但移动之后源对象变成空——而 base::BindOnce 在某些路径上会拷贝而不是移动(比如 base::RepeatingCallback 的绑定)。
cppgc::Persistent 是可拷贝的(引用计数)。所以 PromiseBase 即使被拷贝,两个副本指向同一个 PromiseHandle,底层只有一个 Global。
这和 7.6.3 节讲的 SafeV8Function 是同一个模式:c++ 侧共享所有权,V8 侧唯一句柄。
7.10.3 ResolvePromise 的两个版本
template <typename RT>
class Promise : public PromiseBase {
public:
// Helper for resolving the promise with |result|.
static void ResolvePromise(Promise<RT> promise, RT result) {
if (auto task_runner = GetTaskRunner()) {
task_runner->PostTask(
FROM_HERE, base::BindOnce([](Promise<RT> promise,
RT result) { promise.Resolve(result); },
std::move(promise), std::move(result)));
} else {
promise.Resolve(result);
}
}
为什么要把 resolve post 出去?
因为 ResolvePromise 被调用的时机常常是"在别的线程上"或者"在 GC 作用域里"。v8::Promise::Resolver::Resolve 必须在 isolate 的线程上、在合法的 JS 执行上下文里调。
PostTask 到当前 sequence → 保证在正确的线程、正确的时机执行。
GetTaskRunner() 的实现(promise.cc):
// static
scoped_refptr<base::TaskRunner> PromiseBase::GetTaskRunner() {
if (gin::IsolateHolder::DestroyedMicrotasksRunner())
return nullptr;
auto* task_runner = base::SequencedTaskRunner::HasCurrentDefault()
? base::SequencedTaskRunner::GetCurrentDefault().get()
: nullptr;
return task_runner;
}
和 7.5.1 节的 SecondWeakCallback 一模一样的两个判断:microtasks runner 已销毁 → 返回 null;没有默认 task runner → 返回 null。 两个 null 都让调用方走同步路径。
这是"进程退出期"的第三次出现(前面两次是 SecondWeakCallback 和 HasCurrentDefault 的 fallback)。一个模式重复三次,说明它是这类代码的通用结构:
if (进程还在正常跑) {
安全地异步
} else if (还能同步做) {
同步做
} else {
放弃(泄漏/manual cleanup)
}
Promise<void> 的特化只有一个 ResolvePromise:
template <>
class Promise<void> : public PromiseBase {
public:
using PromiseBase::PromiseBase;
static void ResolvePromise(Promise<void> promise);
static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate);
};
ResolvedPromise 是一个便利函数,返回"已经是 resolved 状态的 Promise"。用于"参数校验失败但仍然要返回 Promise"的场景:
if (!Browser::Get()->is_ready()) {
promise.RejectWithErrorMessage("Memory Info is available only after app ready");
return handle;
}
GetProcessMemoryInfo 就是这么用的:app 未 ready 时返回一个已 reject 的 promise,而不是抛异常。
7.10.4 SafeV8Function:JS 回调到 C++
反方向:C++ 要保存一个 JS 函数,稍后调用。
callback.h:23
class SafeV8Function {
public:
SafeV8Function(v8::Isolate* isolate, v8::Local<v8::Value> value);
SafeV8Function(const SafeV8Function& other);
~SafeV8Function();
bool IsAlive() const;
v8::Local<v8::Function> NewHandle(v8::Isolate* isolate) const;
private:
cppgc::Persistent<SafeV8FunctionHandle> v8_function_;
};
调用时的四件套(V8FunctionInvoker::Go):
static ReturnType Go(v8::Isolate* isolate,
const SafeV8Function& function,
ArgTypes... raw) {
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
ReturnType ret = ReturnType();
if (!function.IsAlive())
return ret;
v8::Local<v8::Function> holder = function.NewHandle(isolate);
v8::Local<v8::Context> context = holder->GetCreationContextChecked(isolate);
v8::Context::Scope context_scope(context);
NodeEntryScope node_scope(context, holder);
v8::MicrotasksScope microtasks_scope(context,
v8::MicrotasksScope::kRunMicrotasks);
std::array<v8::Local<v8::Value>, sizeof...(raw)> args{
gin::ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
v8::MaybeLocal<v8::Value> ret = holder->Call(
context, holder, args.size(), args.empty() ? nullptr : &args.front());
if (ret.IsEmpty())
return v8::Undefined(isolate);
else
return handle_scope.Escape(ret.ToLocalChecked());
}
七行 V8 仪式,每一行都有理由:
gin_helper::Locker locker(isolate) —— 见 7.10.5。
if (!function.IsAlive()) —— 函数可能已被 GC 回收(C++ 侧只有 TracedReference,不阻止回收)。已死就返回默认值。
holder->GetCreationContextChecked(isolate) —— 不是 isolate->GetCurrentContext()。
这是关键。一个从别处传来的 JS 函数,它的 context 是它被创建时的 context,不是当前 context。跨 context 调函数必须显式切换到它的 context——否则 V8 会抛 "Cannot access property of a different context" 或者更糟,静默地访问错误的全局对象。
Context::Scope context_scope(context) —— 切换。
NodeEntryScope node_scope(context, holder) —— Node 的 process.nextTick 队列和微任务检查点。见下面。
MicrotasksScope(context, kRunMicrotasks) —— 显式跑微任务。
注意这里和 7.8.3 节 MaybeMicrotasksScope 的区别:那里是 kScoped/kExplicit 判断后可能不创建,这里是无条件创建并明确要求 kRunMicrotasks。
为什么?因为 NodeEntryScope 和 MicrotasksScope 在这里是互补的:
NodeEntryScope(node_entry_scope.cc):
NodeEntryScope::NodeEntryScope(v8::Local<v8::Context> context,
v8::Local<v8::Object> resource) {
// Only where Node owns the microtask checkpoint. Under Blink's kScoped
// policy the caller's MicrotasksScope already runs microtasks on exit and
// Node's checkpoint must not run from here.
if (v8::Isolate::GetCurrent()->GetMicrotasksPolicy() !=
v8::MicrotasksPolicy::kExplicit) {
return;
}
node::Environment* env = node::Environment::GetCurrent(context);
if (!env || env->async_callback_scope_depth() > 0)
return;
// async_context{0, 0} with hooks skipped: the resource is not observable,
// same as gin_helper::EmitEvent.
scope_.emplace(env, resource, node::async_context{0, 0},
node::InternalCallbackScope::kSkipAsyncHooks);
}
三个早退条件,每个都有精确的原因:
- 不是
kExplicit策略 → 早退。Blink 的kScoped会自己跑。 - 没有 Node 环境 → 早退(沙箱渲染进程)。
async_callback_scope_depth() > 0→ 早退。已经在一个 Node 回调里了,外层的 scope 负责排空(Node 在 depth > 1 时跳过内部检查点)。
而 kSkipAsyncHooks 这个参数:process.nextTick 的 async_hooks 追踪会为每个 tick 生成 init/before/after 三个 hook 调用。这里用了 kSkipAsyncHooks——因为 resource 是内部对象(gin 的 wrapper),不该暴露给 async_hooks。注释说 "same as gin_helper::EmitEvent",是保持一致性。
两个 scope 的分工与顺序:NodeEntryScope 管 process.nextTick 队列,MicrotasksScope 管 promise 微任务。node_scope 先构造、microtasks_scope 后构造,所以析构时微任务先跑、nextTick 后跑——与 Node 的"先 nextTick 后微任务"相反。是否可观测,取决于 InternalCallbackScope 的析构是否在微任务之后补跑一轮 nextTick——这一点要读实现确认(练习 7.8)。
7.10.5 Locker:为什么只在主进程锁
// locker.cc
Locker::Locker(v8::Isolate* isolate) {
if (electron::IsBrowserProcess())
locker_.emplace(isolate);
}
v8::Locker 是 V8 的隔离锁,它会让 isolate 从"无锁模式"切到"有锁模式"(有成本)。为什么只有主进程要?因为主进程的 isolate 被两个线程碰到(JS 主线程 + embed 线程间接访问 uv loop),而渲染/utility 进程的 isolate 只属于一个线程。
std::optional<v8::Locker> locker_; 而非 v8::Locker locker_;——v8::Locker 没有"空"状态,必须用 optional 表达"不锁"。注释理由:"Inline storage — avoids a heap allocation per C++ -> JS callback."
7.11 两件小事:错误令牌与字典构造
两个组件各解决一个具体问题,代码量都不到 100 行,用处却极广。
7.11.1 ErrorThrower:为什么必须 STACK_ALLOCATED
class ErrorThrower {
STACK_ALLOCATED();
public:
constexpr explicit ErrorThrower(v8::Isolate* isolate) : isolate_{isolate} {}
constexpr ErrorThrower() = default;
~ErrorThrower() = default;
void ThrowError(std::string_view err_msg) const;
void ThrowTypeError(std::string_view err_msg) const;
void ThrowRangeError(std::string_view err_msg) const;
void ThrowReferenceError(std::string_view err_msg) const;
void ThrowSyntaxError(std::string_view err_msg) const;
ErrorThrower 是"能力令牌",不是值对象:GetNextArgument 遇到 ErrorThrower* 就无条件成功,于是 C++ 函数可以在参数列表里声明"我需要抛异常的能力",而不用多传一个 isolate。
STACK_ALLOCATED() 展开成删除 operator new——如果有人误把它存进成员变量,就会在 isolate 已销毁后调 ThrowError,段错误。
7.11.2 ObjectBuilder:比 Dictionary 快一倍的那一半
// object_builder.h
// Builds a plain object from a fixed set of fields, as own data properties
// with per-isolate cached keys. About half the cost of gin_helper::Dictionary
// (no prototype walk, no re-intern of the key on every call), and the
// result keeps the same shape and prototype as an object literal would.
//
// return gin_helper::ObjectBuilder(isolate)
// .Set("x", rect.x())
// .Set("y", rect.y())
// .Build();
三个加速点:
CreateDataProperty而不是Set—— 跳过 prototype 链上的 setter/interceptor 查找。InternedString复用键 —— 每次Set("x", ...)都要把"x"转成v8::String,普通做法是StringToSymbol(14ns),InternedString 是缓存查表(3ns)。STACK_ALLOCATED()+ 链式调用 —— 没有堆对象。
InternedString 的实现有个细节(interned_strings.cc):
v8::Local<v8::String> Get(v8::Isolate* isolate, std::string_view literal) {
if (isolate_ != isolate) [[unlikely]] {
Detach();
auto* const data = gin::PerIsolateData::From(isolate);
if (!data) {
// A Node.js worker's isolate has no PerIsolateData and never reports
// disposal, so a cached handle could outlive it. Don't cache.
return gin::StringToSymbol(isolate, literal);
}
缓存是 per-thread 的,只服务一个 isolate。 遇到不同 isolate 就整体清空。这个设计的前提是"一个线程同时只用一个 isolate"——对 Electron 的主线程和渲染主线程成立,对 worker 线程也成立。
而 worker 的 isolate 没有 PerIsolateData,所以不缓存(否则缓存里的 handle 会在 isolate 销毁后悬垂)。这和 7.8.2 节 DisposeAllInIsolateWithoutGin 是同一个问题的两个面。
缓存 key 是字符串字面量的地址,所以 InternedString 的签名用数组引用:
template <size_t N>
v8::Local<v8::String> InternedString(v8::Isolate* isolate,
const char (&literal)[N]) {
return internal::InternedStringImpl(isolate, std::string_view{literal, N - 1});
}
const char (&)[N] 排除了 std::string、std::string_view、const char*——只有真正的字面量能传进来,因为只有字面量有稳定的地址。用类型系统强制"只传字面量",和 7.9.2 节的 EscapableHandleScope& 是同一类手艺。
7.12 两个逃生舱:TrackableObject 与 CleanedUpAtExit
默认规则是"JS 的 GC 决定 C++ 的生死"。但有三种情况这条规则不成立,需要逃生舱。
7.12.1 情况一:isolate 拆除时弱回调不跑
CleanedUpAtExit 的头文件注释:
// Objects of this type will be destroyed immediately prior to disposing the V8
// Isolate. This should only be used for gin_helper::Wrappable objects, whose
// lifetime is otherwise managed by V8.
//
// NB. This is only needed because v8::Global objects that have SetWeak
// finalization callbacks do not have their finalization callbacks invoked at
// Isolate teardown.
"do not have their finalization callbacks invoked at Isolate teardown" —— 这是 V8 的既定行为:Isolate::Dispose() 不会跑弱回调。
后果:进程退出时,所有还活着的 Wrappable 的 C++ 对象泄漏。对进程退出而言泄漏无害(操作系统会回收),但如果析构函数里有必须做的事(比如 flush 日志、关闭文件、发退出事件),就丢了。
CleanedUpAtExit 的实现是一个全局链表:
namespace {
std::vector<CleanedUpAtExit*>& GetDoomed() {
static base::NoDestructor<std::vector<CleanedUpAtExit*>> doomed;
return *doomed;
}
}
CleanedUpAtExit::CleanedUpAtExit() { GetDoomed().emplace_back(this); }
CleanedUpAtExit::~CleanedUpAtExit() { std::erase(GetDoomed(), this); }
// static
void CleanedUpAtExit::DoCleanup() {
auto& doomed = GetDoomed();
while (!doomed.empty()) {
CleanedUpAtExit* next = doomed.back();
next->WillBeDestroyed();
delete next;
}
}
while (!doomed.empty()) 而不是 for (auto* p : doomed)。
因为 delete next 会调析构函数,析构函数里 std::erase(GetDoomed(), this) 修改了正在遍历的 vector。范围 for 会失效(迭代器失效 → UB)。
从尾部取(back())然后删,erase 移除的正是刚刚取出的元素——下次循环取新的尾部。这个循环的正确性依赖于 erase 删掉的是末尾元素。
如果 WillBeDestroyed() 或析构函数里创建了新的 CleanedUpAtExit 对象,它会 push 到 vector 末尾,下一轮就被处理——循环不会漏。这也是 while 而不是 for 的必要性。
DoCleanup() 在 JavascriptEnvironment 的析构里被调(第 5 章 5.11 节的 js_env_.reset())。
7.12.2 情况二:需要从 ID 找回对象
TrackableObject 的头注释只有两行:
// All instances of TrackableObject will be kept in a weak map and can be got
// from its ID.
映射由 KeyWeakMap<int32_t> 提供(key_weak_map.h):Set 里建一个 v8::Global<v8::Object> 并 SetWeak(&mapped, OnObjectGC, kParameter);Get 直接 Local::New。Get 不检查"这个 Global 是否已被清空"——因为记录本身会被 GC 删掉(OnObjectGC 调 self->Remove),"找不到"和"已死"是同一件事。
代价是 Remove 在弱回调里改 map_,而 Values() 可能正在遍历它:base::ToVector 先拷一份出来把窗口压到最小,理论上仍存在窄竞态。析构函数里的那行 ClearWeak 是同一类防御——不先断开弱回调,析构中若发生 GC,OnObjectGC 会访问已销毁的 map_。
7.13 十条规则
把本章的机制压缩成十条可执行的规则。每一条都能在前面的小节里找到出处。
规则一:C++ 对象的生死由 JS 的 GC 决定,除非它自己申请了逃生舱。
WrappableBase 的弱回调里 delete this。TrackableObject、CleanedUpAtExit、cppgc::Persistent 是三个例外(7.12、7.6.3)。
规则二:C++ 想留住一个 JS 值,用 TracedReference;用 Global 会泄漏。
TracedReference 是边,Global 是根。cppgc 对象里用根,等于给自己造一个永不释放的引用(7.6.1)。
规则三:析构函数里不能假定可以调 JS。
V8 的第二遍弱回调在 DisallowJavascriptExecutionScope 里。要调 JS,必须 DeleteSoon 推迟(7.5.1,issue #47420)。
规则四:每个 TracedReference 成员都必须在 Trace 里出现。
漏了不会报错,只会静默丢失那个引用(7.6.1)。
规则五:错误路径可以慢,成功路径不能慢。
ThrowConversionError 只在转换失败后才查 IsDestroyed(7.8.4)。MaybeMicrotasksScope 在 kExplicit 下直接不创建(7.8.3)。
规则六:类型系统能表达的约束,不要用注释表达。
CallMethodWithArgs(v8::EscapableHandleScope&, ...) 让"忘了开 scope"变成编译错误(7.9.2)。InternedString(const char (&)[N]) 让"传了非字面量"变成编译错误(7.11.2)。
规则七:if constexpr 是类型分派,if 是值分派。二者不能互换。
EventEmitterMixin 用 if constexpr (is_deprecated_wrapper) 让两代 wrapper 各自只编译自己需要的分支(7.9.1)。用普通 if 会两边都编译,两边都缺方法。
规则八:跨 context 调 JS,必须切到函数创建时的 context。
holder->GetCreationContextChecked(isolate) + Context::Scope,不是 GetCurrentContext()(7.10.4)。
规则九:进程退出期的代码有第三种选择——放弃。
DestroyedMicrotasksRunner() 返回时直接 return,让对象泄漏。泄漏比崩溃好(7.5.1、7.10.3)。
规则十:能编译期断言的上游依赖,就不要留到运行期。
三条 static_assert 把"gin / Electron / Node 的 tag 空间重叠"变成构建失败(7.7.3)。IsKnownGinEmbedder 的穷尽 switch 把"上游加了 embedder"变成构建失败(7.7.2)。
7.14 八个坑速查
Q1:win.setTitle() 抛 Object has been destroyed,但我明明还持有 win 引用。
引用只是让 JS 对象活着,不代表 C++ 对象活着。窗口被 close() 后,NativeWindow 销毁,WrappableBase 的 internal field 被置 null(7.8.4)。检查 win.isDestroyed()。
Q2:app.on is not a function。
EventEmitter.prototype 没有在 init.ts 第一行注入(7.9.1)。检查你的应用是否绕过了 lib/browser/init.ts(比如直接跑 ELECTRON_RUN_AS_NODE)。
Q3:TypeError: Illegal invocation。
方法丢了 this。常见于 const { setTitle } = win; setTitle('x')。C++ 方法的第一个参数从 JS 的 this 取,不是从参数列表(7.4.3)。
Q4:b.destroy(); b.isDestroyed() 返回 false。
b 是 cppgc 版对象,destroy() 是 no-op,isDestroyed() 永远 false(7.6.2)。这是迁移期的行为差异。
Q5:C++ 侧的 Emit('x') 返回值是 true,但 JS 侧 emit('x') 返回的也是 true,含义不同。
C++ 的 true 是"被 preventDefault",JS 的 true 是"有监听器"(7.9.1)。
Q6:在 app.whenReady() 之前 new BrowserWindow() 崩溃。
不是 gin 层的问题——Browser 还没初始化(第 5 章 5.9)。gin 层只负责转换,不负责前置条件。
Q7:worker 线程里创建的对象泄漏。
worker 的 isolate 没有 PerIsolateData,CallbackHolder 不会被自动清理(7.8.2)。需要显式 DisposeAllInIsolateWithoutGin。
Q8:改了 Trace 之后偶发"某个属性变成 undefined"。
Trace 漏了那个成员,它的 TracedReference 被当成不可达(7.6.1)。
7.15 练习题
练习 7.1(入门) 在控制台执行 Object.keys(new BrowserWindow({show:false})) 和 Object.getOwnPropertyNames(BrowserWindow.prototype),解释两者的差异与本章讲的 internal field 的关系。
练习 7.2(入门) 用 process._linkedBinding('electron_browser_app') 和 process._linkedBinding('electron_common_native_image') 分别在主进程和渲染进程里取模块,解释为什么一个返回空对象、一个不空(7.2.2)。
练习 7.3(进阶) 写一个 JS 侧探测:"这个对象是新一代(cppgc)还是旧一代 Wrappable"。提示:Destroyable::IsDestroyed 的行为差异(7.6.2)。用 PowerSaveBlocker 和 WebContents 验证。
练习 7.4(进阶) 在 electron_api_power_save_blocker.cc 里把 .SetMethod("start", &PowerSaveBlocker::Start) 改成模板版本 .SetMethod<&PowerSaveBlocker::Start>("start"),编译并用 nm -C 或 objdump 确认 CallbackHolder 相关的符号消失了。
练习 7.5(进阶) 读 ThrowConversionError,构造一个能触发 Illegal invocation: Function must be called on an object of type ... 的场景(需要 holder_type 不为 null)。然后找出代码库里哪些地方传了 holder_type。
练习 7.6(深入) 7.5.1 节说 DeleteSoon 是为了避开 DisallowJavascriptExecutionScope。构造一个复现:让某个 Wrappable 的析构函数 Emit 一个事件,然后触发 GC(global.gc(),需要 --js-flags=--expose-gc),观察不 DeleteSoon 时的崩溃信息。
练习 7.7(深入) 7.7.3 的第三条 static_assert 依赖 EMBEDDER_CPPHEAP_POINTER_TAG。在 third_party/electron_node/unofficial.gni 里找到它的定义,算出 Electron 的 tag 空间还剩多少余量。
练习 7.8(深入) 7.10.4 节末尾留了一个问题:NodeEntryScope 先构造、MicrotasksScope 后构造,析构时微任务先跑。读 V8 的 MicrotasksScope 和 Node 的 InternalCallbackScope 析构实现,判断这是否与 Node 的"先 nextTick 后微任务"语义冲突。
练习 7.9(挑战) 自己写一个最小的 Wrappable(不用 gin_helper),用 v8::ObjectTemplate + 1 个 internal field + 弱回调实现"C++ 对象随 JS 对象一起死"。跑通后用 ASAN 验证 FirstWeakCallback 里那个 wrappable == wrappable_from_field 检查的必要性。
练习 7.10(挑战) KeyWeakMap 的 Remove 在 GC 弱回调里执行,可能 invalidate 正在遍历的 unordered_map。写一个能触发这个竞态的压力测试(大量对象 + 频繁 GC + 并发 Values()),判断它是否需要修。
7.16 下一章预告
第 8 章《模块加载:js2c、require 钩子与 electron 模块的真身》接住本章的三条尾巴。
尾巴一:7.1 节的 browserModuleList + defineProperties 惰性 getter。为什么 require('electron') 在 preload 里返回的东西和在主进程里不同?答案是 lib/renderer/api/module-list.ts 是另一张表——同一个模块名,在两个进程里指向不同的 C++ binding。
尾巴二:7.9.1 节的 EventEmitter.prototype 注入。那是 init.ts 的第一行,而 init.ts 本身是一个 js2c bundle。第 8 章会讲 require('electron') 这个不是文件路径的请求怎么被 Node 的 Module._load 拦截,以及 pass_all_globals_through_require.patch(第 4 章提过)为什么是这条链的前提。
尾巴三:7.2 节的 NODE_LINKED_BINDING_CONTEXT_AWARE。它把 C++ 模块注册进 Node 的链表,而 require('electron') 走的是完全不同的路径(JS 层的 module-list)。两条路径在哪一层汇合?第 8 章会画出完整的分叉与汇合图。
一句话预告第 8 章的立论:Electron 的"模块"有两个互不相通的注册表——C++ 的 linked binding 表和 JS 的 module list 表。require('electron') 只走后者,process._linkedBinding() 只走前者,而 lib/ 的代码是唯一同时看得见两边的地方。
7.17 本章源码落点索引
下列位置全部来自本仓库源码树,按实现层归集;每个
路径:行号指向该文件中与本章论述对应的声明或实现行,可逐条复核。
- API 文档与类型:
power-save-blocker.md:5 browser-window.md:5 web-contents-view.md:5 web-contents.md:5 browser-window-options.md:3 - JS 门面与运行时:
power-save-blocker.ts:1 asar-fs-wrapper.ts:9 - 浏览器进程 C++ 层:
electron_api_power_save_blocker.h:15 electron_api_browser_window.h:14 electron_api_event_emitter.h:10 electron_api_web_contents.cc:249 electron_api_web_contents_impl.cc:19 electron_api_web_contents_mac.mm:16 electron_api_web_contents_view.cc:38 electron_api_web_contents_view.h:17 -
child_web_contents_tracker.cc:13 child_web_contents_tracker.h:16 electron_web_contents_utility_handler_impl.cc:23 electron_web_contents_utility_handler_impl.h:15 extended_web_contents_observer.h:13 web_contents_permission_helper.cc:35 web_contents_permission_helper.h:20 web_contents_preferences.cc:41 -
web_contents_preferences.h:22 web_contents_zoom_controller.cc:27 web_contents_zoom_controller.h:19 web_contents_zoom_observer.h:15 electron_extension_web_contents_observer.cc:10 electron_extension_web_contents_observer.h:14 file_system_access_web_contents_helper.cc:11 file_system_access_web_contents_helper.h:11 -
osr_web_contents_view.cc:18 osr_web_contents_view.h:20 osr_web_contents_view_mac.mm:9 inspectable_web_contents.cc:111 inspectable_web_contents.h:28 inspectable_web_contents_delegate.h:12 inspectable_web_contents_view.cc:37 inspectable_web_contents_view.h:18 -
inspectable_web_contents_view_delegate.cc:10 inspectable_web_contents_view_delegate.h:15 electron_api_data_pipe_holder.cc:37 electron_api_data_pipe_holder.h:19 load_url_promises.cc:27 load_url_promises.h:32 - 其他相关位置:
api-power-save-blocker.spec.ts:5 api-browser-window-ignore-mouse-events.spec.ts:27 api-browser-window-posted-click.spec.ts:16 api-browser-window.spec.ts:5 api-web-contents-view.spec.ts:12 api-web-contents.spec.ts:8 node-event-emitter.spec.ts:13 - shell 其余实现:
event_emitter_caller.cc:11 event_emitter_template.cc:15 event_emitter_template.h:9 function_template_extensions.h:22 node_event_emitter.cc:58 web_contents_utility.mojom:8 persistent_dictionary.cc:9 persistent_dictionary.h:22 -
electron_login_helper.mm:11