《Electron 45.2.3 内核解剖》第 20 章 自动更新、崩溃报告与 Fuses:打包期决策如何在运行时生效

6 阅读42分钟

《Electron 45.2.3 内核解剖》第 20 章 自动更新、崩溃报告与 Fuses:打包期决策如何在运行时生效

20.0 三条边界面

前十九章处理的都是「运行时」:一个对象怎么构造、一次请求怎么走、一帧像素怎么取出来。这一章要处理的是另一类问题——有些决定在你写 JS 之前就已经做完了,运行时只能读到结果,没有机会改。

Electron 里有三条这样的边界,它们互不重叠,但经常被混为一谈:

边界决策做出于运行时能否改载体读它的代码
Fuse打包(flip fuses)时不能,二进制里的一串 ASCII 字节,且代码签名后会校验Electron 可执行文件里的 kFuseWire主进程启动前、启动中、每进程
autoUpdater 实现打包成哪种安装包(MSIX / Squirrel / mac app)不能,模块加载时就选定了auto-updater.ts 的 if/else主进程启动时 require
crashReporter 后端进程启动的时机部分能(start() 一次),但窗口极窄每个进程的 Crashpad handler主进程等 JS、子进程开机即装

把三者放在一起看,是因为它们共用同一个设计手法:把「能不能」变成一个在 JS 里查不到、也改不了的前置条件。前十九章反复出现「这个选项设了没生效」,那些多半是某条路径上少了一个判据;而这一章里的「设了没生效」往往是更根本的——那段代码根本没被编译进这个二进制,或者根本没被加载进这个进程。

本章要回答四个问题:

  1. build.py:24-44 生成的那串字节到底长什么样,为什么 volatile 一个关键字决定了整个机制成不成立;
  2. autoUpdater 在 macOS、Squirrel.Windows、MSIX、Linux 上是四套完全不共享的实现,为什么连 update-downloaded 事件的参数都对不齐;
  3. crashReporter.start() 为什么必须"尽可能早",以及主进程与子进程的初始化时序为什么是反的;
  4. 打包时翻转的那 9 个位,各自在源码的哪一行被读、读了之后具体改变了什么。

先用一张图把三条边界的读取位置钉死(后面 20.3 会逐条展开):

可执行文件字节
  └─ kFuseWire[0..31]   sentinel "dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX"
     kFuseWire[32]      fuse_version = 0x01
     kFuseWire[33]      fuse_wire_length = 0x09
     kFuseWire[34..42]  '1' / '0' / 'r'  × 9
          │
          ├─ main() 之前       IsRunAsNodeEnabled()          → 是否走 NodeMain
          ├─ MainDelegate      IsEmbeddedAsar...Enabled()    → 校验 V8 snapshot
          │                    IsLoadBrowser...Enabled()     → 换 snapshot 文件
          ├─ BrowserMainParts  IsWasmTrapHandlersEnabled()   → V8 isolate 之前
          ├─ BrowserClient     IsGrantFile...Enabled()       → scheme 列表 / asar factory
          ├─ NetworkService    IsCookieEncryptionEnabled()   → network context params
          ├─ NodeBindings      IsNodeOptionsEnabled()        → 环境变量 / 进程 flags
          │                    IsNodeCliInspectEnabled()     → debug 选项 / SIGUSR1
          └─ features.cc       IsRunAsNodeEnabled()          → 唯一暴露给 JS 的 fuse

注意最后一行:9 个 fuse 里只有 1 个能在 JS 里查到。这不是遗漏,是这套机制的必然结果——fuse 的设计目标就是让应用代码无法探测、无法绕过,只让操作系统通过代码签名来保证它没被改回去。


20.1 Fuse Wire:一串被代码生成出来的字节

20.1.1 定义只有一个文件

全部 fuse 的定义在 fuses.json5:2-9,只有 14 行:

{
  "_comment": "Modifying the fuse schema in any breaking way should result in the _version prop being incremented.  NEVER remove a fuse or change its meaning, instead mark it as removed with 'r'",
  "_schema": "0 == off, 1 == on, r == removed fuse",
  "_version": 1,
  "run_as_node": "1",
  "cookie_encryption": "0",
  "node_options": "1",
  "node_cli_inspect": "1",
  "embedded_asar_integrity_validation": "0",
  "only_load_app_from_asar": "0",
  "load_browser_process_specific_v8_snapshot": "0",
  "grant_file_protocol_extra_privileges": "1",
  "wasm_trap_handlers": "1"
}

三个下划线开头的键是元数据,剩下 9 个才是 fuse。这个数字要记牢,因为 fuse_wire_length 就是它,而 @electron/fuses 翻转时按下标定位,不是按名字——_version 加一可以,删掉一个 fuse 不行,改顺序也不行。_comment 里那句 NEVER remove a fuse or change its meaning 就是在说这件事:wire 是位置寻址的,不是键值寻址的。

json5 后缀有点误导:build.py:51 读它的方式是

fuse_defaults = json.loads(''.join(
    line for line in f.readlines() if not line.strip()[0] == "/"),
    object_pairs_hook=OrderedDict)

它只是把以 / 开头的行丢掉,然后当严格 JSON 解析,OrderedDict 保证 key 顺序不丢。所以这个文件里不能写尾逗号、不能写注释、不能写单引号——_comment 是数据不是注释这一点,正是为了让文件仍能被标准 JSON 解析器吃掉。

20.1.2 build.py 生成的两份代码

BUILD.gn:458-466 声明了一个 action("electron_fuses"),输入是这个 json5,输出是 $target_gen_dir/fuses.h 与 fuses.cc。这两份文件不是仓库里的源码,是每次构建现生成的。脚本 111 行,核心是三个模板字符串。

生成的头文件长这样(把 9 个 getter 展开):

build.py:22-27

#ifndef ELECTRON_FUSES_H_
#define ELECTRON_FUSES_H_
#if defined(WIN32)
#define FUSE_EXPORT __declspec(dllexport)
#else
#define FUSE_EXPORT __attribute__((visibility("default")))
#endif
namespace electron::fuses {
extern const volatile char kFuseWire[];
FUSE_EXPORT bool IsRunAsNodeEnabled();
FUSE_EXPORT bool IsCookieEncryptionEnabled();
/* ... 共 9 个 ... */
}  // namespace electron::fuses
#endif

生成的 .cc 里,数组初始化是:

const volatile char kFuseWire[] = {
    /* sentinel */  0x64,0x4c,0x37,0x70, /* ... 32 字节 ... */ 0x74,0x73,0x58,
    /* fuse_version */      0x01,
    /* fuse_wire_length */  0x09,
    /* fuse_wire */  0x31,0x30,0x31,0x31,0x30,0x30,0x30,0x31,0x31
};

0x31 是字符 '1',0x30 是 '0'。fuse 状态存的是可打印 ASCII,不是 bit,这一点很关键:@electron/fuses 翻转一个 fuse 就是把这个字节在 0x30 和 0x31 之间改一下,人用十六进制编辑器也能改,改完二进制还可以重新签名。如果存的是 bit,一次翻转要读-改-写一个字节,还要处理大小端和相邻位,工具链会复杂得多。

getters_cc 的生成逻辑里有个容易看漏的下标计算:

build.py:67-70

index = len(SENTINEL) + 1
for fuse in fuses:
  index += 1
  ...
  getters_cc += "... return kFuseWire[{index}] == '1';".replace(...)

SENTINEL 是 32 字符,初值 index = 33,循环里先自增,所以第一个 fuse 读 kFuseWire[34],第九个读 kFuseWire[42]。而数组布局是 sentinel 占 0..31、version 占 32、length 占 33、wire 从 34 开始。刚好对上。写成 len(SENTINEL) + 1 而不是 + 2,是因为循环体开头那次 += 1;这个 +1 看着像 off-by-one,实际是配套的。

getter 本体(生成结果)值得逐行看:

features.cc:33-40

bool IsRunAsNodeEnabled() {
#if DCHECK_IS_ON()
  // RunAsNode is checked so early that base::CommandLine isn't yet
  // initialized, so guard here to avoid a CHECK.
  if (base::CommandLine::InitializedForCurrentProcess()) {
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch("set-fuse-run_as_node")) {
      std::string switch_value =
          command_line->GetSwitchValueASCII("set-fuse-run_as_node");
      return switch_value == "1";
    }
  }
#endif
  return kFuseWire[34] == '1';
}

四个细节:

  1. 只有 DCHECK_IS_ON() 构建才有命令行覆盖。发布版里 --set-fuse-run_as_node=1 什么也做不了。这是个测试钩子,不是配置接口。
  2. 开关名是 set-fuse- 加 fuse.lower(),所以保留下划线:--set-fuse-run_as_node,不是 --set-fuse-run-as-node。九个开关的名字都能从 fuses.json5 的 key 直接推出来。
  3. base::CommandLine::InitializedForCurrentProcess() 的守卫不是防御性编程。RunAsNode 在 main() 最开头、命令行对象还没建好时就会被查(electron_main_linux.cc:55),此时若直接调 ForCurrentProcess() 会触发 CHECK 崩掉。源码注释把原因写得很清楚。
  4. 覆盖值判据是 switch_value == "1",传 true、on、空值都等于关闭。

20.1.3 volatile 是整个机制的地基

kFuseWire 的声明是 const volatile char[],两个限定符各管一件事:

  • const 让它落到只读数据段,符合"运行时不该改"的语义;
  • volatile 阻止编译器把 getter 优化成立即数。

设想去掉 volatile:kFuseWire 是同一个翻译单元里定义的 const 数组,内容在编译期完全已知,kFuseWire[34] == '1' 是一个常量表达式。开启了优化的编译器会直接把 IsRunAsNodeEnabled() 变成 return true;,数组本身可能因为没有被真正读取而被链接器丢弃。这样一来,打包工具就算把二进制里的某个字节从 0x31 改成 0x30,也不会有任何代码去读它,fuse 翻转彻底失效。

加上 volatile 之后,每次调用都必须真实地发起一次内存读取,读到的是被补丁修改过的那个字节。所以这不是一个风格选择,而是「二进制补丁能否生效」的充分必要条件。整个 fuse 机制能成立,靠的就是这一个关键字加上 FUSE_EXPORT 保证符号不被内联消除。

顺带说 FUSE_EXPORT:在 Windows 上是 __declspec(dllexport),其他平台是 __attribute__((visibility("default")))。它让这 9 个 getter 在动态库里可见,这样 @electron/fuses 之外(以及同一二进制里的其他链接单元)也能取到状态,编译器不能假定"没人调用所以可以删掉"。

20.1.4 'r' 的真相:运行时没有"已移除"这个概念

文档 fuses.md 里对 wire 字节写了三种取值:

"0" indicates the fuse is disabled, "1" indicates enabled, "r" indicates the fuse has been removed and changing the byte to either 1 or 0 will have no effect.

但生成的 getter 里唯一的判据是 == '1'。也就是说在这份运行时代码里,把 'r' 改成 '1' 会实打实地启用这个 fuse,改成 '0' 则禁用——并不存在"改了也没效果"的分支。

那文档在说什么?说的是打包工具的约定:@electron/fuses 读到 'r' 时会拒绝让你翻转那个位置,从而保证旧版本工具不会误改一个已经废弃的槽位。这是一层工具侧的策略,不是二进制里的保护。_comment 里 NEVER remove a fuse... instead mark it as removed with 'r' 也是同一个意思:槽位必须留着,因为后面 8 个 fuse 的下标全依赖它。

这个区别有实际后果:如果你绕过工具、直接用十六进制编辑器改字节,运行时不会拦你。而代码签名的意义就在这里——保护来自操作系统对二进制完整性的校验,不来自 Electron。文档开头那段 Gatekeeper / AppLocker 的说明,讲的正是这件事。

20.1.5 @electron/fuses 不在这个仓库里

一个容易白费功夫的点:flipFuses、FuseVersion、FuseV1Options 这些 API 属于独立 npm 包,仓库里只有被翻转的那一端——fuses.json5(schema)、build.py(生成 wire)、以及 9 个 getter 的调用点。所以:

  • 想查"翻转时怎么定位 sentinel",去看 @electron/fuses 的源码,这里没有;
  • 想查"某个 fuse 打开后到底改了什么",只能看这个仓库,这是本文 20.2 要做的事;
  • npx @electron/fuses read --app /Applications/Foo.app 之所以能读任意 Electron app,是因为 sentinel 和布局是跨版本公开的,与具体应用的构建无关。

fuses.md:227-231 里"the hard way"那节给出的手工翻转方法,与 build.py 生成的数组布局完全一致:搜 sentinel 的 32 个 ASCII 字节,往后一个字节是 version、再一个字节是长度,接着就是 wire。版本号必须小于 256(if fuse_version >= pow(2, 8): raise),长度字段也是单字节——这个 schema 最多只能容纳 255 个 fuse,且永远不会因为新增 fuse 而扩容,只能靠 _version 递增换一套新 schema。

20.1.6 把 wire 逐字节算一遍

上面所有下标都可以从仓库里两个文件复算,不需要猜。sentinel 长度用 len("dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX") 得 32;fuses.json5 去掉三个 _ 开头的键之后剩 9 项;于是:

偏移长度内容来源
0..3132dL7pKGdnNz796PbbjQWNKmHXBZaB9tsXbuild.py:10 的 SENTINEL
3210x01_version: 1
3310x09len(fuses)
34..429'1' '0' '1' '1' '0' '0' '0' '1' '1'9 个默认值,按 key 顺序

末行那串字符与 fuses.json5 的对应关系是:

34  run_as_node                               '1'
35  cookie_encryption                         '0'
36  node_options                              '1'
37  node_cli_inspect                          '1'
38  embedded_asar_integrity_validation        '0'
39  only_load_app_from_asar                   '0'
40  load_browser_process_specific_v8_snapshot '0'
41  grant_file_protocol_extra_privileges      '1'
42  wasm_trap_handlers                        '1'

一个可复现的验算方式:用 json.load(..., object_pairs_hook=OrderedDict) 读 fuses.json5:2-4,删掉 _version / _schema / _comment,把剩下 9 个值按顺序拼成字符串,再与 build.py:56 里 "".join(...) 生成的 initial_config 比。二者必须逐字节相等,否则 getter 的下标就与 schema 脱节了。

正因为布局如此简单,@electron/fuses 的 read 命令才能读任意 Electron app:搜那 32 个固定字节 → 读 version 与 length → 按 fuses.json5:2 的顺序把后面 N 个字节翻译回名字。名字本身不在二进制里——build.py:52 只在生成的 getter 函数名里用到它们,wire 里只有 '1'/'0'。所以一个 schema 版本升级后,旧工具读出来的名字会整体错位,这正是 _comment 要求"breaking change 必须递增 _version"的原因。


20.2 九个 fuse 逐个:默认值、检查点、关掉之后发生什么

fuses.json5 里 9 个键的顺序就是 wire 的顺序,下标从 34 开始。下面这张表把「默认状态 / 第一个读取点 / 关闭后的具体行为」列全,随后分组展开表里说不清的部分。

#wire 下标fuse默认主要读取点关闭(或开启)后改变了什么
134run_as_node开electron_main_{linux,mac,win}.cc、process_util.cc:44ELECTRON_RUN_AS_NODE 环境变量被忽略,child_process.fork() 在外层就断了
235cookie_encryption关network_context_service.cc:115enable_encrypted_cookies 不置位,cookie 明文落 SQLite
336node_options开node_bindings.cc:484/491/736、node_main.cc:130NODE_OPTIONS、NODE_EXTRA_CA_CERTS 被 unset,Node 进程加 kDisableNodeOptionsEnv
437node_cli_inspect开node_bindings.cc:457/906--inspect* 被拒,SIGUSR1 不再启动调试器
538embedded_asar_integrity_validation关main_delegate.cc:128、asar/archive.cc:145/276不校验 V8 snapshot 的 SHA-256,也不校验 asar 内容哈希
639only_load_app_from_asar关app_package.cc:92、asar_util.cc:54关时按 app.asar → app → default_app.asar 三选一
740load_browser_process_specific_v8_snapshot关main_delegate.cc:401主进程与渲染进程共用同一个 snapshot 文件
841grant_file_protocol_extra_privileges开electron_content_client.cc:151、protocol_registry.cc:29/56 等 5 处file:// 不进 service worker scheme 列表,asar factory 不再替换 file://
942wasm_trap_handlers开electron_browser_main_parts.cc:307、renderer_client_base 相关V8 改用显式边界检查,WASM 代码变大变慢

20.2.1 run_as_node:检查发生在 main() 最前面

三个平台各有一份,写法几乎一样。以 Linux 为例(electron_main_linux.cc:55):

if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
  return electron::NodeMain();
}

Windows 版在 electron_main_win.cc:154 把结果存进 bool run_as_node,mac 版在 electron_main_mac.cc:73。三者的共同点是:这一步在 Chromium 的 ContentMain 之前。所以它决定的不是"某个 API 能不能用",而是"这个进程到底是不是 Electron"——走 NodeMain() 的进程不会创建 BrowserMainLoop、不会加载 BrowserContext、不会初始化任何窗口系统。

第二处读取在 process_util.cc:43-46:

bool IsRunningAsNode() {
  static bool result = fuses::IsRunAsNodeEnabled() &&
                       base::Environment::Create()->HasVar(kRunAsNode);
  return result;
}

static 局部变量意味着整个进程只读一次 fuse,之后无论二进制字节怎么变(理论上 volatile 允许),这个值都固定了。这也是 20.1.4 那句"运行时改不了"的另一种体现:不只是不许改,很多地方连读都只读一次。

IsRunningAsNode() 又影响 crash_keys::SetCrashKeysFromCommandLine()(crash_keys.cc:94-105):它把 process_type 这个 crash key 写成 "node" 而不是从命令行解析。所以一个以 Node 模式运行的 Electron 进程,在崩溃报告里会被标成 node 进程。

文档明确写了关掉它的连带后果:child_process.fork() 依赖 ELECTRON_RUN_AS_NODE 来把 Electron 可执行文件当 Node 用,fuse 关掉后 fork 会抛错,官方建议改用 Utility Process。这里要补一层源码上的因果——fork 并没有任何特判,它只是照常用 process.execPath 加环境变量派生子进程;是子进程自己在启动时读了环境变量并拒绝进入 NodeMain,才让父进程那边的 fork 看起来"失效"。

20.2.2 cookie_encryption:一个传给 network service 的布尔

network_context_service.cc:113-122:

network_context_params->enable_encrypted_cookies =
    electron::fuses::IsCookieEncryptionEnabled();

if (network_context_params->enable_encrypted_cookies) {
  if (!cookie_encryption_provider_) {
    cookie_encryption_provider_ =
        std::make_unique<CookieEncryptionProviderImpl>(...);
  }
  ...
}

这个 fuse 与第 17 章讲过的 NetworkContext 参数装配直接接上:它只是 network::mojom::NetworkContextParams 里的一个字段,加上一个按需创建的加密 provider(macOS 走 Keychain,Windows 走 DPAPI,Linux 无 keyring 时退化为弱加密)。

文档特别强调这是单向迁移:打开后旧 cookie 会在写入时被加密,之后再关掉 fuse,读到的密文解不开,整个 cookie store 就废了。从源码看原因是没有降级路径——enable_encrypted_cookies = false 时根本不创建 provider,Crypto 侧没有"尝试解密再回退明文"的逻辑。

20.2.3 node_options 与 node_cli_inspect:两道独立的闸

这两个 fuse 经常一起关,但检查点完全不同。

node_options 有四个读取点:

  • node_main.cc:130-134:NodeMain() 开头,如果 fuse 关,UnSetVar("NODE_OPTIONS") 和 UnSetVar("NODE_EXTRA_CA_CERTS");
  • node_bindings.cc:483-487:SetNodeOptions() 里,只对 NODE_EXTRA_CA_CERTS 打一条 LOG(WARNING) << "NODE_OPTIONS ignored due to disabled nodeOptions fuse." 然后 unset(日志文案说的是 NODE_OPTIONS,实际清的是 CA 证书变量,这是处文案错配);
  • 同文件 :491:fuse 开着才进入 NODE_OPTIONS 的白名单解析;
  • node_bindings.cc:736:设 node::ProcessInitializationFlags::kDisableNodeOptionsEnv,把闸落到 Node.js 初始化层。

也就是说它做了三层:环境变量清理、Electron 侧解析跳过、Node 侧 flag 禁用。任何一层漏了,都可能从另一条路把选项注进来。

node_cli_inspect 的两个点:

node_bindings.cc:455-458

if (debug_options.contains(option))
  return electron::fuses::IsNodeCliInspectEnabled();

// node_bindings.cc:905-909
if (!electron::fuses::IsNodeCliInspectEnabled()) {
  env_flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler;
}

第一个是选项过滤器:--inspect、--inspect-brk 这类参数落在 debug_options 集合里,fuse 关时一律返回 false。第二个是文档里那句 "SIGUSR1 不再初始化 inspector" 的来源——kNoStartDebugSignalHandler 让 Node 不注册 SIGUSR1 处理器。两者必须同时做:只过滤命令行参数的话,一个信号就能把调试器拉起来。

顺带看 :452-461 附近的另一个分支:

node_bindings.cc:459-460

if (unpacked_options.contains(option))
  return !electron::api::App::IsPackaged();

--expose-internals 这类选项的判据不是 fuse,而是 app.isPackaged。这说明"能不能传某个 Node 参数"由两套彼此独立的规则决定:一套是打包期翻转的 fuse,一套是运行时根据 app 是否打包算出来的。排查"参数被吞了"时得先分清是哪一套。

20.2.4 三个与启动性能/完整性相关的 fuse

#5、#6、#7 都作用在"加载应用代码"这条链上,但层次不同。

embedded_asar_integrity_validation 的第一个检查点在 electron_main_delegate.cc:125-135,校验的是 V8 snapshot 而不是 asar 文件本身:

void ValidateV8Snapshot(v8::StartupData* data) {
  if (data->data &&
      electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled()) {
    CHECK_GT(data->raw_size, 0);
    UNSAFE_BUFFERS({
      base::span<const char> span_data(
          data->data, static_cast<unsigned long>(data->raw_size));
      CHECK(base::ToLowerASCII(base::HexEncode(
                crypto::hash::Sha256(base::as_bytes(span_data)))) ==
            electron::snapshot_checksum::kChecksum);
    })
  }
}

注意是 CHECK 不是 DCHECK,也不是返回错误——哈希对不上进程直接终止。编译期常量 snapshot_checksum::kChecksum 是构建时把 asar 头信息一起算进去的,所以改了 app.asar 就必须重新生成校验值,否则连窗口都出不来。另外两个检查点在 archive.cc:145 与 :276,负责读文件时的逐块校验,那是运行时路径。

only_load_app_from_asar 在 app_package.cc:90-101:

const bool only_asar = fuses::IsOnlyLoadAppFromAsarEnabled();
std::vector<base::FilePath::StringViewType> candidates;
if (only_asar) {
  candidates = {FILE_PATH_LITERAL("app.asar")};
} else {
  candidates = {FILE_PATH_LITERAL("app.asar"), FILE_PATH_LITERAL("app"),
                FILE_PATH_LITERAL("default_app.asar")};
}

默认三选一的顺序解释了为什么开发时把 resources/app 目录一放就能覆盖 app.asar——不,顺序其实是反的,app.asar 优先。真正的影响是:开了 fuse 后,即使有人往 resources/ 里塞了一个 app/ 目录,也完全不会被搜索。配合 #5 就形成文档里那句"不可能加载未校验的代码"。

但这个 fuse 还有第二处检查,在 asar_util.cc:50-66,这段注释把设计意图说透了:

// Whether |path| is the app's own archive in an app that may only load from
// one. Decided without looking at the disk, so that every process agrees: a
// directory at this path is then refused when opened, not read in place of
// the archive. Both spellings are accepted because the module loader asks
// about the resolved path.
bool IsRequiredAppArchive(const base::FilePath& path) {
  if (!electron::fuses::IsOnlyLoadAppFromAsarEnabled())
    return false;
  static const base::NoDestructor<std::pair<base::FilePath, base::FilePath>>
      s_paths([] { ... resources.Append(name),
                       base::MakeAbsoluteFilePath(resources).Append(name) ... }());
  return path == s_paths->first || path == s_paths->second;
}

三个要点:不看磁盘(避免 TOCTOU)、每个进程一致(相对路径和绝对路径两种拼写都算同一个 archive)、以及"如果 app.asar 这个路径上是个目录,就拒绝打开而不是当目录读"。最后这条是防替换攻击的关键:光把候选列表缩到 app.asar 还不够,Node 的模块解析器碰到一个同名目录照样会去读里面的 package.json。

load_browser_process_specific_v8_snapshot 在 main_delegate.cc:398-406:

std::string_view ElectronMainDelegate::GetBrowserV8SnapshotFilename() {
  bool load_browser_process_specific_v8_snapshot =
      IsBrowserProcess() &&
      electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled();
  if (load_browser_process_specific_v8_snapshot) {
    return "browser_v8_context_snapshot.bin";
  }
  return ContentMainDelegate::GetBrowserV8SnapshotFilename();
}

IsBrowserProcess() && 这个条件容易被忽略:fuse 是全局的,但只有主进程换文件。渲染进程、utility、gpu 仍然用 Chromium 默认的 v8_context_snapshot.bin。文档里解释动机是"避免渲染进程用到带 nodeIntegration 的 snapshot"。

代价文档里写了但源码里看不到:主进程用自定义 snapshot 后,Electron 得从源码引导 Node.js 环境,省下的启动时间要还回去一部分。

20.2.5 grant_file_protocol_extra_privileges:五处读取,关掉会白屏

这个 fuse 默认开,是唯一一个"关掉会让很多现有应用立刻坏掉"的。它在五个位置被读:

文件:行作用
electron_content_client.cc:151把 file:// 加进 service_worker_schemes
shell/browser/electron_browser_client.cc:519/521影响 AllowFileAccessFromFiles 之类的 renderer 侧的 file 权限
protocol_registry.cc:29用 AsarURLLoaderFactory 替换 file:// 的 factory
protocol_registry.cc:56非网络导航到 file:// 时返回 asar factory
renderer_client_base.cc:327renderer 侧对应的权限

第 17 章讲 asar 时说过:asar 不是一种新协议,而是顶替 file:// 的 URLLoaderFactory。看 protocol_registry.cc:26-44 就明白这个 fuse 为什么危险:

if (electron::fuses::IsGrantFileProtocolExtraPrivilegesEnabled()) {
  auto file_factory = factories->find(url::kFileScheme);
  if (file_factory != factories->end()) {
    file_factory->second = AsarURLLoaderFactory::Create();
  } else if (allow_file_access) {
    factories->emplace(url::kFileScheme, AsarURLLoaderFactory::Create());
  }
}

fuse 关掉 → 这段整块不执行 → 没有任何 factory 认识 .asar 文件内部的路径 → 用 file:// 加载 app.asar 里资源的应用直接白屏。所以文档给的迁移建议是"先改用自定义协议,再关这个 fuse",顺序不能反。

另一个容易踩的是 CreateNonNetworkNavigationURLLoaderFactory()(:51-62):它只处理 file:// 与非 file:// 两种分支,fuse 关且 scheme 是 file:// 时返回空 {}。导航路径和子资源路径是分开判断的,两处都得开着 fuse 才能一致。

grant_file_protocol_extra_privileges 的"额外权限"在文档里承认 "incompletely documented",源码里能确认的三条是:file:// 页面能 fetch 其他 file://、能注册 service worker、对同为 file:// 的子 frame 无视 sandbox 给予 universal access。第一条来自 asar factory 的替换,第二条来自 electron_content_client.cc:151 的 scheme 注册,第三条来自 browser client 的权限判定。

20.2.6 wasm_trap_handlers:必须在 V8 isolate 之前

electron_browser_main_parts.cc:300-311:

// Enable trap handlers before creating the V8 isolate. V8 initialization
// calls IsTrapHandlerEnabled() which prevents later EnableTrapHandler calls.
#if ((BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) && \
     defined(ARCH_CPU_X86_64)) ||                                       \
    ((BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)) && defined(ARCH_CPU_ARM64))
  if (electron::fuses::IsWasmTrapHandlersEnabled()) {
    electron::SetUpWebAssemblyTrapHandler();
  }
#endif

注释点明这是不可逆的时序窗口:V8 初始化时调 IsTrapHandlerEnabled() 拍下快照,之后再 EnableTrapHandler() 也没用。所以这个 fuse 只能在 BrowserMainParts::PreCreateMainMessageLoop 这类极早的位置读,不可能做成运行时开关。

外面那圈 #if 也值得注意:Windows ARM64 不在支持列表里(只有 Linux / macOS 的 ARM64)。在不受支持的架构上,即使 fuse 是 '1',也不会装 trap handler,V8 自然回落到显式边界检查——这是编译期条件与打包期开关叠加的结果,光看 fuses.json5 看不出来。

同样的调用还出现在 electron_renderer_client.cc:307 和 node_service.cc:148:三类进程各自装一次,因为每个进程都有自己的 V8 isolate。


20.3 读取时机、缓存与"JS 只能查到一个"

20.3.1 三类时机

把 20.2 的九个读取点按在进程生命周期的哪一段重排,会得到一个比按功能列表更有用的分类:

时机fuse为什么必须在这里
main() 最前、命令行对象建立前run_as_node决定这个进程走 NodeMain 还是 ContentMain,分叉之后无法回头
MainDelegate 阶段embedded_asar_integrity_validation、load_browser_process_specific_v8_snapshotsnapshot 在 V8 isolate 创建时就要加载完
BrowserMainParts / RendererClient 构造wasm_trap_handlers、grant_file_protocol_extra_privilegesV8 初始化与 ContentClient 的 scheme 列表都只读一次
每次创建 NetworkContext / 每次解析 Node 参数cookie_encryption、node_options、node_cli_inspect这些是"每次做这件事时查一下",理论上可能读多次

最后一类里,node_options 在 SetNodeOptions()、NodeMain()、node_bindings.cc:736 三处各读一次,cookie_encryption 每次建 NetworkContext 都读一次。但因为 kFuseWire 是只读数据,多次读不会有分歧——除非在 DCHECK 构建里用 --set-fuse-* 覆盖,那时同一个 getter 在不同调用点仍然返回同一个开关值,所以也没分歧。

真正有分歧的是 static 缓存:process_util.cc:43 的 IsRunningAsNode()、asar_util.cc:57-65 的 s_paths、crash_keys.cc 里的 static CrashKeyString。前两个把 fuse 结果永久钉死在第一次调用时,后面再改内存字节也没用。

20.3.2 features.cc 只暴露 1 个 fuse

features.cc:51-57 是 process._linkedBinding('electron_common_features') 的实现,共 62 行、导出 7 个方法:

dict.SetMethod<&IsBuiltinSpellCheckerEnabled>("isBuiltinSpellCheckerEnabled");
dict.SetMethod<&IsPDFViewerEnabled>("isPDFViewerEnabled");
dict.SetMethod<&IsPrintingEnabled>("isPrintingEnabled");
dict.SetMethod<&IsPromptAPIEnabled>("isPromptAPIEnabled");
dict.SetMethod<&IsComponentBuild>("isComponentBuild");
dict.SetMethod<&IsRunAsNodeEnabled>("isRunAsNodeEnabled");
dict.SetMethod<&IsExtensionsEnabled>("isExtensionsEnabled");

其中 IsBuiltinSpellCheckerEnabled、IsPDFViewerEnabled、IsPrintingEnabled、IsPromptAPIEnabled、IsExtensionsEnabled 这五个读的是 BUILDFLAG(...)——编译期 buildflag,不是 fuse;IsComponentBuild 读 #if defined(COMPONENT_BUILD);只有 isRunAsNodeEnabled() 转到了 electron::fuses::IsRunAsNodeEnabled()。

于是有一个相当反直觉的结论:在第 17 章里我们靠 ENABLE_PRINTING buildflag 区分打印构建,在第 20 章里靠 fuse 区分打包配置,但 JS 层只能查到后者中的一项。想判断 cookie_encryption 是否开启、onlyLoadAppFromAsar 是否开启,在应用代码里没有任何官方 API,只能自己读可执行文件的字节(或用 @electron/fuses 的 CLI 在打包流水线里记录)。

这不算缺陷,甚至是设计目标:fuse 的威胁模型里包含"应用代码被攻陷后试图探测/绕过安全配置",把状态藏起来是有意的。但排查问题时必须知道这一点——"我查不到"不等于"没开"。

20.3.3 buildflag、fuse、命令行开关是三套东西

这一章和前面几章反复出现三种"开关",容易混:

类型何时确定例子能否在已分发的二进制上改
GN buildflag编译 Electron 本身ENABLE_PRINTING、ENABLE_PDF_VIEWER、IS_MAS_BUILD()不能
fuse打包应用时翻转二进制上表 9 个能,但要重签名
命令行 / 环境变量每次启动--disable-http-cache、ELECTRON_RUN_AS_NODE能,且无需改二进制

三者的优先级不是简单的覆盖关系,而是在不同代码路径上各自生效。举两个例子:

  • ENABLE_PRINTING 决定 PrintToPDF() 这个 C++ 方法是否被编译(第 19 章),features.isPrintingEnabled() 只是把这个事实报给 JS;fuse 完全不参与。
  • ELECTRON_RUN_AS_NODE 是环境变量,但 run_as_node fuse 是它的前置闸门:fuse 关时环境变量还在,只是没人读它了。process_util.cc:44 的 static bool 把两个条件 && 在一起,就是这两套开关唯一的交汇点。

IS_MAS_BUILD() 属于第一类,却在 20.10 里扮演关键角色:Mac App Store 构建里整个 crashReporter 被编译成空壳。它和 fuse 无关,但造成的效果("调用了没反应")与 fuse 关掉几乎一模一样,排查时要能区分。

20.3.4 打包工具那一侧的最小契约

最后把 @electron/fuses 需要遵守的契约从 build.py 反推出来,这对写自己的打包脚本有用:

  1. 搜 32 字节 ASCII dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX;
  2. 下一个字节必须等于 FuseVersion.V1(0x01),否则 schema 不匹配,应拒绝翻转;
  3. 再下一个字节是 wire 长度,当前为 0x09;
  4. 往后 N 个字节,按 fuses.json5 的 key 顺序一一对应;
  5. 只把 '1'/'0' 互转,碰到 'r' 不动;
  6. 翻转之后必须重新代码签名,否则 macOS Gatekeeper / Windows AppLocker 会拒绝启动——这正是文档说"OS 成为保证这些位不被翻回去的责任方"的含义。

第 5 条再强调一次:这层保护在工具里。二进制里那 9 个 getter 只认 == '1'。


20.4 autoUpdater:一个 API,四套实现,外加一个空壳

20.4.1 分发器只有十行

auto-updater.ts:1-7 是整个模块的入口,全文如下:

if (process.platform === 'win32') {
  // windowsStore indicates whether the app is running as a packaged app (MSIX), even outside of the store
  if (process.windowsStore) {
    module.exports = require('./auto-updater/auto-updater-msix');
  } else {
    module.exports = require('./auto-updater/auto-updater-win');
  }
} else {
  module.exports = require('./auto-updater/auto-updater-native');
}

lib/browser/api/module-list.ts:6 把这个模块注册成 autoUpdater。所以 require('electron').autoUpdater 拿到的不是同一个类,甚至不是同一门语言写的:

平台 / 打包方式实际模块语言行数后端
macOS(非 MAS)auto-updater-native → C++ 绑定Objective-C++ (auto_updater_mac.mm)188Squirrel.Mac
macOS(MAS)同上,但 C++ 层是空函数C++ stub41无
Windows(Squirrel 安装)auto-updater-winTypeScript80 + 95Update.exe
Windows(MSIX)auto-updater-msixTypeScript + C++/WinRT477 + 840PackageManager WinRT API
Linuxauto-updater-native → C++ 绑定C++ stub41无

四套实现不共享任何代码,除了 auto-updater.md 里那份事件契约。这就解释了为什么后文会看到参数顺序、错误对象形状、日期来源全都对不齐——它们是在不同年代、由不同人按同一份文档分别补出来的。

auto-updater.md:13 开篇只说"Currently, only macOS and Windows are supported. There is no built-in support for auto-updater on Linux",但从代码看,Linux 上并不是"没有这个模块",而是有一个方法齐全、行为为空的模块。这个区别在 20.4.4 会变成真实故障。

20.4.2 process.windowsStore 不是"是否来自商店"

electron_bindings.cc:65-69:

#if BUILDFLAG(IS_WIN)
  if (IsRunningInDesktopBridge())
    process->SetReadOnly("windowsStore", true);
#endif

两个要点:一是只在 Windows 定义,其他平台上 process.windowsStore 是 undefined(falsy),所以外层 process.platform === 'win32' 其实已经保证了这一点;二是判据叫 IsRunningInDesktopBridge(),即进程是否具备 MSIX/Desktop Bridge 包身份,application_info_win.cc:75 里实现。它和"是不是从 Microsoft Store 下载的"无关——侧载的 MSIX 包、企业分发的 AppX 一样会返回 true。TS 入口那行注释专门点了这一点:even outside of the store。

顺带一个构建差异:IS_MAS_BUILD() 时 process 上会多一个只读的 mas = true(electron_bindings.cc:62-64),而 windowsStore 只在 Windows 分支里。这两个标志都只用于模块分发与能力判断,不是给用户代码做特性检测的通用字段。

20.4.3 C++ 绑定无条件存在,方法却可能是空的

electron_api_auto_updater.cc:166-172 的 Initialize 没有任何平台条件:

void Initialize(v8::Local<v8::Object> exports, ...) {
  v8::Isolate* const isolate = electron::JavascriptEnvironment::GetIsolate();
  gin_helper::Dictionary dict{isolate, exports};
  dict.Set("autoUpdater", AutoUpdater::Create(isolate));
}

AutoUpdater::Create 用 cppgc::MakeGarbageCollected 造一个 api::AutoUpdater,构造时把自己设成全局 delegate 并注册 PerIsolateData::DisposeObserver。所以任何平台上 _linkedBinding('electron_browser_auto_updater') 都能拿到一个 EventEmitter 形态的对象。

但 GetObjectTemplateBuilder()(:137-149)绑的四个方法里,有三个来自 auto_updater::AutoUpdater 的静态方法:

electron_api_auto_updater.cc:140-145

.SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates)
.SetMethod("getFeedURL",     &auto_updater::AutoUpdater::GetFeedURL)
.SetMethod("setFeedURL",     &auto_updater::AutoUpdater::SetFeedURL)
#if DCHECK_IS_ON()
.SetMethod("isVersionAllowedForUpdate",
           &auto_updater::AutoUpdater::IsVersionAllowedForUpdate)
#endif
.SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall);

而 auto_updater.cc:26-38 把这四台静态方法在非 mac(或 MAS)构建里全部编译成空壳:

#if !BUILDFLAG(IS_MAC) || IS_MAS_BUILD()
void AutoUpdater::SetFeedURL(gin::Arguments* args) {}
void AutoUpdater::CheckForUpdates() {}
void AutoUpdater::QuitAndInstall() {}
bool AutoUpdater::IsVersionAllowedForUpdate(const std::string&,
                                            const std::string&) {
  return false;
}
#endif

GetFeedURL() 不在这个 #if 里,它返回 static base::NoDestructor<std::string> feed_url,一个进程级空字符串——没人写过它就是 ""。

于是 Linux 上的行为清单是:

调用结果
autoUpdater.setFeedURL({url})静默成功,URL 不被保存(空函数连参数都不看)
autoUpdater.getFeedURL()恒返回 ''
autoUpdater.checkForUpdates()静默无操作,不 emit 任何事件
autoUpdater.on('update-downloaded', ...)正常注册,永远不会触发
autoUpdater.isVersionAllowedForUpdate(...)方法根本不存在(只在 DCHECK_IS_ON() 且 mac 上有)
autoUpdater.quitAndInstall()见下一节

注意 setFeedURL 的空实现不抛类型错误。macOS 版会对缺 url、非法 serverType、非法 URL 抛 TypeError(20.5.1),Windows 两个 TS 版也抛;唯独 Linux 什么都不做。想写跨平台 smoke test 判断"平台是否支持自动更新",用 setFeedURL 的返回值或异常都是错的,只能查 process.platform。

20.4.4 Linux 上 quitAndInstall() 会关掉你所有的窗口

这是本章最值得记住的一条。上面那张方法表里,quitAndInstall 绑的是 api::AutoUpdater::QuitAndInstall(api 层自己的成员),不是 auto_updater::AutoUpdater::QuitAndInstall(平台层静态空函数)。api 层实现见 electron_api_auto_updater.cc:120-132:

void AutoUpdater::QuitAndInstall() {
  Emit("before-quit-for-update");

  // If we don't have any window then quitAndInstall immediately.
  if (WindowList::IsEmpty()) {
    auto_updater::AutoUpdater::QuitAndInstall();
    return;
  }

  // Otherwise do the restart after all windows have been closed.
  WindowList::AddObserver(this);
  WindowList::CloseAllWindows();
}

这段代码在所有平台都编译,且没有任何「平台是否支持更新」的判断。所以在 Linux 上:

  1. Emit("before-quit-for-update") 照常发出;
  2. 如果当前没有窗口 → 调用平台层空函数 → 什么也不发生,进程也不退出;
  3. 如果有窗口 → 注册 WindowListObserver → CloseAllWindows() 把用户的窗口全部关掉 → window_list.cc:61 通知 OnWindowAllClosed() → api::AutoUpdater::OnWindowAllClosed() 又调 QuitAndInstall() → 此刻窗口已空 → 又调用一次空函数 → 结束。

最终状态:所有窗口没了,应用没重启,更新没装。auto-updater.md 里那句 "quitAndInstall() 会先关闭所有窗口,并在窗口都关闭后自动调用 app.quit()" 只对 mac / Windows 成立;在 Linux 上 app.quit() 从来没被调用——app.quit() 只写在两个 TS 实现里,C++ 的这条路径完全没有。

还有两个次要问题:WindowList::AddObserver(this) 在这里没有配对的 RemoveObserver,AutoUpdater 的析构是 = default,OnBeforeMicrotasksRunnerDispose() 只做了 SetDelegate(nullptr)。正常应用里这个对象跟 isolate 同寿、且 quitAndInstall 通常在退出前调一次,所以暴露不出来;但在一个进程里反复调 quitAndInstall() 会重复注册同一个 observer(base::ObserverList 允许重复添加取决于配置),OnWindowAllClosed 可能被回调多次。

头文件 electron_api_auto_updater.h:62 里还有一个私有的 std::string GetFeedURL(); 声明,既没有定义也没被 GetObjectTemplateBuilder 使用——模板里绑的是平台层那个静态版本。这是重构留下的痕迹,不影响行为,但读代码时容易误以为 JS 的 getFeedURL 走的是成员方法。

20.4.5 三套实现的事件契约,逐字段对照

把 Emit 与 this.emit 的实参按顺序抄出来,差异一目了然:

事件macOS(C++ Emit)Windows Squirrel(TS)Windows MSIX(TS)
checking-for-update无参无参无参
update-available无参无参无参
update-not-available无参无参无参
update-downloadedreleaseNotes, releaseName, releaseDate, updateURL, quitAndInstall{}, releaseNotes, version, new Date(), updateURL, quitAndInstall{}, releaseNotes, releaseName, releaseDate, updateUrl, quitAndInstall
before-quit-for-update无参(C++ 层发)不发无参(quitAndInstall 里发)
errorError, message(可带 code/domain)Error, messageError, message

文档声称 update-downloaded 的第一个参数是 event,但macOS 的 C++ 层第一个参数就是 releaseNotes 字符串,压根没传 event;两个 Windows 实现则都传了一个空对象 {} 填充。也就是说:

  • 按文档写 (event, releaseNotes, releaseName, releaseDate, updateURL) => {},在 macOS 上 releaseNotes 会拿到版本名、releaseName 会拿到日期,整体错位一位;
  • 在 Windows 上签名是对的,但 event 是 {} 而不是真正的 Event 对象,没有任何标准字段;
  • Squirrel.Windows 的第三个参数其实是 version(文档说 "With Squirrel.Windows only releaseName is available",其余字段形同虚设),第四个参数是调用时刻伪造的 new Date(),不是发布日期;
  • MSIX 的 releaseDate 来自 JSON 的 pub_date,解析不了也退化成 new Date()。

before-quit-for-update 更微妙:macOS 与 MSIX 都会发,Squirrel.Windows 的 quitAndInstall() 里只有 squirrelUpdate.processStart(); app.quit();,不发这个事件。而 auto-updater.md:137 把这个事件写成通用行为,还专门提醒"此时不会发 before-quit,所以要监听它来做清理"——在 Squirrel.Windows 上按这个建议写,清理逻辑永远不会执行。

一个可复用的结论:不要依赖 update-downloaded 的参数位置。跨平台的写法是自己调 getFeedURL() 拿 URL、把版本信息放在自己的 JSON 里再解析一次;或者干脆只把它当"可以提示用户重启了"的信号。


20.5 macOS:Squirrel.Mac 与一条 ReactiveObjC 信号链

auto_updater_mac.mm:39-46 188 行,是四个实现里唯一用原生框架、也是唯一在 C++ 编译单元里直接调 Objective-C 的。它依赖 ReactiveObjC(RACSignal / RACCommand)和 Squirrel 框架(SQRLUpdater)。

20.5.1 SetFeedURL 的两种签名与三条校验

auto_updater_mac.mm:29-68 兼容两套调用形式:

v8::Local<v8::Value> first_arg = args->PeekNext();
if (!first_arg.IsEmpty() && first_arg->IsString()) {
  if (args->GetNext(&feed)) {
    args->GetNext(&requestHeaders);       // 旧式:setFeedURL(url, headers)
  }
} else if (args->GetNext(&opts)) {
  if (!opts.Get("url", &feed)) {
    args->ThrowTypeError("Expected options object to contain a 'url' string property in setFeedUrl call");
    return;
  }
  opts.Get("headers", &requestHeaders);
  opts.Get("serverType", &serverType);  // 新式:setFeedURL({url, headers, serverType})
  if (serverType != "default" && serverType != "json") {
    args->ThrowTypeError("Expected serverType to be 'default' or 'json'");
    return;
  }
} else {
  args->ThrowTypeError("Expected an options object with a 'url' property to be provided");
  return;
}

区分新旧式靠的是 first_arg->IsString()——只看第一个参数的类型,不看参数个数。所以 setFeedURL({url}, headers) 这种混用会被当成新式,第二个参数被静默忽略。另外旧式签名里没有 serverType,它保持 "default"。

三条校验之后还有两条 URL 校验:base::SysUTF8ToNSString(feed) 返回 nil、或 [NSURL URLWithString:] 返回 nil,都抛 Expected 'url' to be a valid URL。注意后者不检查 scheme,一个 ftp:// 甚至任意字符串只要能被 NSURL 接受就过关,真正能不能用要等 Squirrel 发请求时才知道。

requestHeaders 的类型是 std::map<std::string, std::string>,逐个塞进 NSMutableURLRequest:

auto_updater_mac.mm:82-84

for (const auto& it : requestHeaders) {
  [urlRequest setValue:base::SysUTF8ToNSString(it.second)
      forHTTPHeaderField:base::SysUTF8ToNSString(it.first)];
}

因为用的是 setValue:forHTTPHeaderField: 而不是 addValue:,同名头会被覆盖;而 HeaderMap 本身是 std::map,JS 里重复键早就被合并了。文档把这个参数标成 _macOS_,确实只有这条路读取它——Windows Squirrel 的 setFeedURL 只接受 { url }(auto-updater-win.ts:32-46),MSIX 版额外接受 headers 与 allowAnyVersion。

serverType 决定用哪个 Squirrel 构造器:

auto_updater_mac.mm:92-96

if (serverType == "json") {
  NSString* nsAppVersion = base::SysUTF8ToNSString(electron::Browser::Get()->GetVersion());
  g_updater = [[SQRLUpdater alloc] initWithUpdateRequest:urlRequest forVersion:nsAppVersion];
} else {
  g_updater = [[SQRLUpdater alloc] initWithUpdateRequest:urlRequest];
}

"json" 分支把当前 app 版本传给 Squirrel,让它自己按版本查 JSON feed;"default" 分支不传,直接把 URL 的响应当更新描述。整个构造包在 @try/@catch (NSException*) 里,异常会转成 delegate->OnError(reason)——这是四个实现里唯一处理 Objective-C 异常的地方。

g_updater 是文件级 __strong 全局,SetFeedURL 每次都先 g_updater = nil 再重建。这意味着在检查更新的过程中重新 setFeedURL,旧 updater 会被直接丢弃,正在跑的 RACCommand 持有自己的引用所以不会崩,但结果回来后仍会向 delegate 发事件,而此时 JS 侧以为自己在等新的 URL。源码没有做代次(generation)校验。

20.5.2 状态订阅:两个状态,两次 dispatch_async

:96-107:

auto_updater_mac.mm:106-113

[[g_updater rac_valuesForKeyPath:@"state" observer:g_updater]
    subscribeNext:^(NSNumber* stateNumber) {
      int state = [stateNumber integerValue];
      // Dispatching the event on main thread.
      dispatch_async(dispatch_get_main_queue(), ^{
        if (state == SQRLUpdaterStateCheckingForUpdate)
          delegate->OnCheckingForUpdate();
        else if (state == SQRLUpdaterStateDownloadingUpdate)
          delegate->OnUpdateAvailable();
      });
    }];

三个值得注意的地方:

  1. 只有两个状态映射到事件。SQRLUpdaterStateIdle、AwaitingReplacement 等状态完全不发事件。所以 checking-for-update 与 update-available 是"状态机边沿",不是 API 调用的回调——如果 Squirrel 内部从检查直接跳到完成(比如命中缓存),可能只收到 update-downloaded。
  2. 每次状态变化都 dispatch_async 到主队列,所以这两个事件相对于 checkForUpdates() 的调用是异步且可能被合并/重排的。JS 里不能用"先收到 checking 再收到 available"来做状态断言。
  3. 订阅者写在 SetFeedURL 里、绑在 g_updater 这个对象上(observer:g_updater),但没有保存 disposable,也不取消订阅。g_updater 被置 nil 后订阅生命周期由 ARC 与 KVO 决定——这是一处典型的"靠对象生命周期管理订阅"的写法。

20.5.3 concat: + take:1:一个用来区分"没更新"的信号技巧

CheckForUpdates()(:110-150)是这段源码里最巧妙也最容易误读的部分:

auto_updater_mac.mm:125-132

[[[[g_updater.checkForUpdatesCommand execute:nil]
    // Send a `nil` after everything...
    concat:[RACSignal return:nil]]
    // But only take the first value. If an update is sent, we'll get that.
    // Otherwise, we'll get our inserted `nil` value.
    take:1]
    subscribeNext:^(SQRLDownloadedUpdate* downloadedUpdate) {
      if (downloadedUpdate) {
        g_update_available = true;
        SQRLUpdate* update = downloadedUpdate.update;
        delegate->OnUpdateDownloaded(...);
      } else {
        g_update_available = false;
        // When the completed event is sent with no update, then we know there
        // is no update available.
        delegate->OnUpdateNotAvailable();
      }
    }
    error:^(NSError* error) { ... delegate->OnError(...) }];

问题是:checkForUpdatesCommand 这个 RACSignal 在没有更新时不会发送任何 next 值,只会 completed。而 subscribeNext: 拿不到 completed。源码的办法是在信号后面 concat 一个 [RACSignal return:nil]:如果原信号发过值,那个值先到;如果原信号一个值都没发,补上的 nil 就到。再 take:1 保证 subscribeNext 最多执行一次。

于是 "nil" 被复用成了"无更新"的哨兵值。这是 ReactiveObjC 里处理"空完成"的标准手法,但副作用是:这个信号只认第一个 next 值。如果 Squirrel 将来改成先发一个进度对象、再发更新对象,这段代码会把进度对象当成 SQRLDownloadedUpdate* 用。

OnUpdateDownloaded 的四个字段全部来自 SQRLUpdate:releaseNotes、releaseName、releaseDate.timeIntervalSince1970(经 base::Time::FromSecondsSinceUnixEpoch 转成 base::Time,再由 time_converter 变成 JS Date)、updateURL.absoluteString。这是四个实现里唯一有真实发布日期的一条路。

error: 回调把三段 NSError 信息拼成一个字符串:

NSMutableString* failureString = [NSMutableString stringWithString:error.localizedDescription];
if (error.localizedFailureReason) { [failureString appendString:@": "]; ... }
if (error.localizedRecoverySuggestion) {
  if (![failureString hasSuffix:@"."]) [failureString appendString:@"."];
  [failureString appendString:@" "]; ...
}
delegate->OnError(failureString, error.code, error.domain);

连标点都要手工补,是因为 localizedRecoverySuggestion 通常是一句完整的话。这个拼接结果会同时作为 Error.message 与 error 事件的第二个字符串参数(20.8.2)。

20.5.4 g_update_available 是一把进程级锁

:157-170:

auto_updater_mac.mm:167-173

void AutoUpdater::QuitAndInstall() {
  Delegate* delegate = AutoUpdater::GetDelegate();
  if (g_update_available) {
    [[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) { ... }];
  } else {
    if (delegate)
      delegate->OnError("No update available, can't quit and install");
  }
}

g_update_available 只在 CheckForUpdates() 的 subscribeNext 里被写:有更新置 true、无更新置 false。它不随 SetFeedURL 重置,也不在 OnUpdateDownloaded 之后重置。后果:

  • 应用启动后第一次 quitAndInstall() 必然报 "No update available, can't quit and install";
  • 检查到有更新、装完并重启之后,进程重置为 false,符合预期;
  • 但检查到更新、用户拒绝重启、之后又调一次 setFeedURL 指向别处,这个 true 仍然留着,此时 quitAndInstall() 会对着旧的 g_updater 或新建的空 updater 调 relaunchToInstallUpdate。

Windows 两个 TS 实现用的是实例字段 this.updateAvailable,语义相同但作用域是模块单例;MSIX 版在 quitAndInstall 里无更新时还会额外 app.quit()(见 20.7.4),mac 版不会。三者的"无更新时怎么办"都不一样。

20.5.5 IsVersionAllowedForUpdate 只在调试构建存在

auto_updater_mac.mm:172-176:

bool AutoUpdater::IsVersionAllowedForUpdate(const std::string& current_version,
                                            const std::string& target_version) {
  return [SQRLUpdater isVersionAllowedForUpdate:... from:...];
}

而 electron_api_auto_updater.cc:145-147 只在 #if DCHECK_IS_ON() 里把它绑到 JS。所以发布版里 autoUpdater.isVersionAllowedForUpdate 是 undefined,尽管头文件 auto_updater.h:64 无条件声明、非 mac stub 也无条件实现了返回 false 的版本。这是个纯测试接口:内部测试用它验证 Squirrel 的版本比较逻辑(是否允许降级等),并不向外部承诺。

20.5.6 文档里那些新特性不在这份仓库里

auto-updater.md:34 的 macOS 段写了一串看起来很具体的行为:ZIP 流式写盘、ETag / Last-Modified + Range 断点续传、sha256 + size 校验、Sparkle BinaryDelta 差量补丁、from_version 与 CFBundleVersion 匹配、失败回退全量包。

这些全部属于 Squirrel.Mac 框架,不在 electron/electron 仓库里。auto_updater_mac.mm:125 只做了三件事:构造 SQRLUpdater、订阅 state、执行 checkForUpdatesCommand。所以:

  • 想改断点续传逻辑,改的是 Squirrel 依赖,不是这边;
  • sha256/size 校验失败时,这边只会收到 error: 回调,然后走 20.5.3 的三段字符串拼接;
  • DEPS 里锁定的 Squirrel 版本决定了这些能力有没有,升级 Electron 不一定升级框架。

文档还要求 macOS 自动更新必须代码签名——这也是 Squirrel 在解压后做的验证,Electron 侧没有对应检查。同理,ATS(NSAllowsArbitraryLoads)是 NSURLRequest 层面的系统策略,源码里只 setValue:forHTTPHeaderField:,没有碰 plist。


20.6 Windows / Squirrel:用 Update.exe 的 stdout 当 RPC

auto-updater-win.ts:5-7(80 行)与 squirrel-update-win.ts:6-8(95 行)加起来不到 180 行,却是绝大多数 Windows Electron 应用实际跑的代码。它们与 C++ 层没有任何关系:auto-updater.ts:2-3 在 win32 且非 windowsStore 时直接 require('./auto-updater/auto-updater-win'),后者继承 Node 的 EventEmitter,自己实现全部事件与方法。

20.6.1 Update.exe 的路径是从 process.execPath 反推的

squirrel-update-win.ts:5-8:

// i.e. my-app/app-0.1.13/
const appFolder = path.dirname(process.execPath);
// i.e. my-app/Update.exe
const updateExe = path.resolve(appFolder, '..', 'Update.exe');
const exeName = path.basename(process.execPath);

Squirrel.Windows 的安装布局是 根目录/app-x.y.z/你的app.exe 加 根目录/Update.exe,所以 Update.exe 就在可执行文件的上一级目录。这三条常量在模块加载时算一次,之后不再变。

supported()(:88-94)用 fs.accessSync(updateExe, fs.constants.R_OK) 同步检查文件存在且可读。这意味着:

  • 开发模式(node_modules/electron/dist/electron.exe)下 Update.exe 不存在,checkForUpdates() 会 emit 'Update URL is not set' 或 'Can not find Squirrel',取决于有没有先调 setFeedURL;
  • 只要 Update.exe 存在,supported() 就返回 true,不校验它是不是真的 Squirrel、版本是否匹配、能不能执行。一个同名空文件也能过关,错误会在 spawn 之后才暴露。

checkForUpdates() 里这两个检查的顺序是固定的(auto-updater-win.ts:49-57):先查 this.updateURL,再查 squirrelUpdate.supported(),然后才 emit('checking-for-update')。所以"更新 URL 没设"和"找不到 Squirrel"都不会触发 checking-for-update,只直接 emit error。

20.6.2 spawnUpdate 的并发控制有三条分支,其中两条有坑

squirrel-update-win.ts:22-60 是整个实现的核心:

const spawnUpdate = async function (args: string[], options: { detached: boolean }): Promise<string> {
  return new Promise((resolve, reject) => {
    // Process spawned, same args:        Attach events to already running process
    // Process spawned, different args:   Return with error
    // No process spawned:                Spawn new process
    if (spawnedProcess && !isSameArgs(args)) {
      throw new Error(`AutoUpdater process with arguments ${args} is already running`);
    } else if (!spawnedProcess) {
      spawnedProcess = spawn(updateExe, args, { detached: options.detached, windowsHide: true });
      spawnedArgs = args || [];
    }

    let stdout = '';
    let stderr = '';
    spawnedProcess.stdout.on('data', (data) => { stdout += data; });
    spawnedProcess.stderr.on('data', (data) => { stderr += data; });
    spawnedProcess.on('error', (error) => { spawnedProcess = undefined; spawnedArgs = []; reject(error); });
    spawnedProcess.on('exit', function (code, signal) {
      spawnedProcess = undefined; spawnedArgs = [];
      if (code !== 0) reject(new Error(`Command failed: ${signal ?? code}\n${stderr}`));
      else resolve(stdout);
    });
  });
};

分支一(同参数、进程还在)的注释说 "Attach events to already running process",但代码做的事是又挂了一整套 stdout.on('data') / stderr.on('data') / on('error') / on('exit') 监听器,而不是复用第一次的监听。后果:

  • 每次调用都有自己的局部 stdout 变量,所以数据本身不会串,但同一个子进程上有 N 套监听器,N 次并发调用会触发 Node 的 MaxListenersExceededWarning;
  • 任何一个 exit 都会把共享的 spawnedProcess 置为 undefined,而所有 N 个 Promise 都会用各自累积的 stdout resolve——因为每个监听器都从进程创建之后开始收数据(同参数分支通常发生在进程刚 spawn 之后),这份数据一般是完整的,所以功能上"碰巧能用";
  • on('error') 被挂 N 次,一次 spawn 失败会 reject N 个 Promise。

分支二(不同参数)里写的是 throw new Error(...),位置在 new Promise((resolve, reject) => {...}) 的执行器内部。这在 JS 里等价于 reject(error),不会真的抛到调用栈外——checkForUpdates() 的 catch 能接到它,最后变成 emit('error', err, err.message)。注释写 "Return with error",措辞比 throw 更准确。

还有一处:spawnUpdate 被声明为 async function 却 return new Promise(...),这层 async 是多余的包装,会让 Promise 多一层 assimilation。不影响正确性,但说明这段代码是后来改过形状的。

checkForUpdates() 里连续两次调用 spawnUpdate:checkForUpdate(url) 用 --checkForUpdate + {detached:false},成功后 update(url) 用 --update + {detached:false}。两次参数不同,但第一次的 Promise 已经 resolve、并把 spawnedProcess 清空了,所以不会撞上分支二。真正会撞的是应用同时调用两次 checkForUpdates()——第二次进来时第一次的进程可能还在跑,此时参数完全相同(同一个 url),走分支一,于是两套监听器、两个 update-downloaded 事件、两次 --update 下载。文档里那句 "Calling autoUpdater.checkForUpdates() twice will download the update two times" 说的正是这个;源码里没有任何去重或 in-flight 标记。

20.6.3 stdout 最后一行就是协议

:74-82:

squirrel-update-win.ts:71-77

export async function checkForUpdate(updateURL: string): Promise<any> {
  const stdout = await spawnUpdate(['--checkForUpdate', updateURL], { detached: false });
  try {
    // Last line of output is the JSON details about the releases
    const json = stdout.trim().split('\n').pop();
    return JSON.parse(json!)?.releasesToApply?.pop?.();
  } catch {
    throw new Error(`Invalid result:\n${stdout}`);
  }
}

Squirrel 的 Update.exe --checkForUpdate=<url> 会往 stdout 打一堆进度日志,最后一行是一个 JSON 对象,形如 { "releasesToApply": [ {...}, ... ] }。Electron 取最后一行、JSON.parse、releasesToApply.pop() 拿数组最后一项(Squirrel 按版本升序排,最后一个是目标版本)。

?.pop?.() 这个写法值得停一下:它不是 ?.pop(),而是在 pop 属性后面又加了一个可选调用。也就是说只要 releasesToApply 上有 pop 这个可调用属性就会执行,不检查是不是数组。配合外层 catch,任何解析失败、字段缺失、字段类型不符,全都被折叠成同一句 Invalid result:\n<完整 stdout>。错误信息里带上整个 stdout 是唯一的调试线索——排查 Squirrel 更新失败时,第一件事是把这个字符串打全,因为它里面有 Update.exe 自己的日志。

update()(:84-86)更粗暴:await spawnUpdate(['--update', url], { detached: false }),完全不解析 stdout,只看退出码。所以下载过程中的警告(比如某个 delta 包校验失败后回退全量)对 Electron 侧不可见,只要 Update.exe 以 0 退出就算成功。

20.6.4 事件参数与伪造的日期

auto-updater-win.ts:58-72:

this.emit('checking-for-update');
try {
  const update = await squirrelUpdate.checkForUpdate(url);
  if (update == null) return this.emit('update-not-available');
  this.updateAvailable = true;
  this.emit('update-available');
  await squirrelUpdate.update(url);
  const { releaseNotes, version } = update;
  // Date is not available on Windows, so fake it.
  const date = new Date();
  this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => {
    this.quitAndInstall();
  });
} catch (error) { this.emitError(error as Error); }

与 macOS 版对照,有四处实质差异:

  1. update-available 在下载之前发,语义是"服务端说有更新";macOS 版是在 state == SQRLUpdaterStateDownloadingUpdate 时发,语义是"已经开始下载"。同名事件,时刻不同。
  2. releaseNotes 来自 JSON,version 被放在 releaseName 的位置(文档说 "With Squirrel.Windows only releaseName is available",其实是反的——只有第 2、3 个参数有意义,其余形同虚设)。
  3. date 是 new Date(),源码注释直白写着 "Date is not available on Windows, so fake it."。把它当发布日期展示给用户会显示"刚刚"。
  4. 第一个参数 {} 是空对象,不是 Event。

emitError()(:75-77)的注释解释了为什么要发两个参数:

// Private: Emit both error object and message, this is to keep compatibility with Old APIs.
emitError(error: Error) {
  this.emit('error', error, error.message);
}

这与 C++ 层 OnError 的三参数版本刻意保持了一致(20.8.2 会展开)。error 事件有两个参数这件事,Node 的 EventEmitter 本身不关心,但很多日志代码写 autoUpdater.on('error', console.error) 时只会拿到第一个;也有不少人按 err.message 取,结果拿到的是字符串本身。

20.6.5 quitAndInstall() 是"先启动新版本,再退出自己"

auto-updater-win.ts:15-22:

quitAndInstall() {
  if (!this.updateAvailable) {
    return this.emitError(new Error("No update available, can't quit and install"));
  }
  squirrelUpdate.processStart();
  app.quit();
}

processStart() 是:

squirrel-update-win.ts:66-67

export function processStart() {
  spawnUpdate(['--processStartAndWait', exeName], { detached: true });
}

四个要点:

  • --processStartAndWait 让 Update.exe 启动当前应用的最新版本并等待它退出;它是 Squirrel 的安装后重启机制,不是 Electron 自己的 app.relaunch()。
  • detached: true + windowsHide: true:子进程脱离父进程、不显示控制台窗口。父进程退出不会带走它。
  • spawnUpdate(...) 返回的 Promise 被直接丢弃,既没有 await 也没有 .catch()。如果 Update.exe 此刻 spawn 失败(文件被删、权限变化),on('error') 会 reject 一个没人接的 Promise → unhandledRejection。supported() 在几秒前的检查并不能覆盖这个竞态。
  • app.quit() 紧接着同步调用,没有等 Update.exe 真正起来。这里依赖的是 spawn() 在调用内已经把进程创建请求交给系统、detached 子进程不会随父进程退出这一事实,而不是某个明确的同步点。

与 macOS 版(relaunchToInstallUpdate)和 C++ 层(WindowList::CloseAllWindows())都不一样:Squirrel.Windows 不主动关窗口,app.quit() 会走正常的 before-quit / will-quit 流程,窗口的 beforeunload 还能阻止退出。文档那句"quitAndInstall() 会先关闭所有窗口并自动调用 app.quit()"在这里的实现就是直接 app.quit(),由 app 自己处理窗口。

20.6.6 安装包事件与首次启动锁

Squirrel 的生命周期参数(--squirrel-install、--squirrel-firstrun 等)不在 Electron 源码里,由 electron-squirrel-startup 之类的包处理。源码里唯一相关的痕迹在 app_package.cc:87-89:

#if BUILDFLAG(IS_WIN)
  MaybeSetSquirrelAppUserModelId();
#endif

它在 LoadAppPackage()(加载 app.asar 的入口)里被调用,用来把 AppUserModelId 设成与 Squirrel 快捷方式一致的 com.squirrel.PACKAGE_ID.EXE名。这与 20.4 讲的 fuse only_load_app_from_asar 是同一个函数——也就是说每次 Electron 找应用代码时,顺手修一次 Windows 任务栏 ID。

文档提到的那个坑值得记:Squirrel 安装完首次启动会带 --squirrel-firstrun,此时 Update.exe 持有文件锁,autoUpdater 的请求会失败几秒。源码里没有任何等待或重试逻辑,规避只能靠应用自己判断 process.argv 或加超时。

20.6.7 getPackageInfo() 在这里是 undefined

auto-updater-win.ts:27-30:

getPackageInfo() {
  // Squirrel-based Windows apps don't have MSIX package information
  return undefined;
}

而 MSIX 版返回的是一个有 6 个字段的对象。文档把 getPackageInfo() 归到 "MSIX Packages" 那一节,但方法本身在非 MSIX 的 Windows 上也存在,只是返回 undefined。macOS/Linux 则完全没有这个方法(C++ 模板里没绑)。想写跨平台代码判断"当前是不是 MSIX",typeof autoUpdater.getPackageInfo === 'function' 会把 Squirrel.Windows 也算进去,得改成判返回值或判 process.windowsStore。


20.7 Windows / MSIX:477 行 TypeScript 加 840 行 WinRT

MSIX 是这套模块里最年轻、也最"不像 autoUpdater"的一支。auto-updater-msix.ts 有 477 行,底下 electron_api_msix_updater.cc 有 840 行 C++/WinRT。它不调用 Update.exe,而是直接调 Windows 的 Windows.Management.Deployment.PackageManager COM 接口。

20.7.1 两层分工

msix-update-win.ts:1-3 只有 8 行,把原生绑定的四个方法原样导出:

const { updateMsix, registerPackage, registerRestartOnUpdate, getPackageInfo } = process._linkedBinding(
  'electron_browser_msix_updater'
);
export { updateMsix, registerPackage, registerRestartOnUpdate, getPackageInfo };

electron_api_msix_updater.cc:824-836 的 Initialize 无条件导出这四个方法(没有 #if BUILDFLAG(IS_WIN) 包住导出本身),但每个方法内部在非 Windows 上走 #else 分支:UpdateMsix / RegisterPackage reject 一条 "MSIX updates are only supported on Windows with identity.",RegisterRestartOnUpdate 返回 false,GetPackageInfo 抛 TypeError 或返回空。绑定能拿到、调用会失败——与 20.4.3 的 "C++ 绑定无条件存在" 是同一种设计。

一个全局调试开关在文件开头(:36-38):

electron_api_msix_updater.cc:40-41

const bool debug_msix_updater =
    base::Environment::Create()->HasVar("ELECTRON_DEBUG_MSIX_UPDATER");

它是 const bool 全局,进程启动时读一次环境变量,之后所有 DebugLog() 都看它。不是运行时可切换的日志级别,想开日志必须在启动进程之前设好环境变量。

20.7.2 URL 校验:一次 HEAD,一次扩展名判断

validateMsixUrl()(auto-updater-msix.ts:128-158)是 MSIX 独有的前置检查:

const response = await net.fetch(url, {
  method: 'HEAD',
  headers: this.updateHeaders ? new Headers(this.updateHeaders) : undefined,
  redirect: 'follow' // Follow redirects to get the final URL
});
const finalUrl = response.url || url;
const urlObj = new URL(finalUrl);
const pathname = urlObj.pathname.toLowerCase();
const hasMsixExtension = pathname.endsWith('.msix') || pathname.endsWith('.msixbundle');
if (!hasMsixExtension) {
  throw new Error(`Update URL does not point to an MSIX file. Expected .msix or .msixbundle extension, got final URL: ${finalUrl}`);
}

三个值得说的点:

  • 用的是 net.fetch(第 17 章讲过的主进程 fetch 适配层),不是 Node 的 http 模块。它默认会带 session cookie(因为 net-fetch.ts:84-93 把 credentials 默认填成 same-origin,见 17.8),所以这个 HEAD 请求会携带应用的 cookie。
  • redirect: 'follow' 后取 response.url 是为了拿到最终地址,避免有人用一个短链指向 MSIX。但判据只看 pathname 的后缀,不看 Content-Type、不看响应状态码:服务器返回一个 404 页面但 URL 以 .msix 结尾,校验照样通过。
  • 反过来,很多真实的分发 URL 是 /download?id=123 或带签名的 /v2/releases/abc(无扩展名),会被判为非法。isDirectMsixUrl() 的 catch 还会把 TypeError 折叠成 Invalid MSIX URL: <url>,把原始原因藏掉:

auto-updater-msix.ts:160-163

} catch (error) {
  if (error instanceof TypeError) {
    throw new Error(`Invalid MSIX URL: ${url}`);
  }
  throw error;
}

net.fetch 网络失败抛的正是 TypeError(Fetch 规范:网络错误 → reject TypeError),所以断网、DNS 失败、证书错误都会被改写成一个看起来像"URL 格式有误"的消息。而 validateMsixUrl 里手工 throw new Error(...) 的是 Error 不是 TypeError,会原样透出。

getUpdateInfo() 的执行顺序还有一个隐藏成本:它先对 feed URL 调一次 isDirectMsixUrl(url)(发一个 HEAD),如果失败就走 fetchSquirrelJson(url)(发一个 GET),拿到 JSON 里的 updateTo.url 后再调一次 isDirectMsixUrl(updateUrl, true)(第三个 HEAD)。一次普通的 checkForUpdates() 最多发三次网络请求,其中两次是校验性的 HEAD。

20.7.3 两种 feed 格式与一个宽松到危险的版本比较

fetchSquirrelJson()(:286-320):

auto-updater-msix.ts:283-290

const headers: Record<string, string> = {
  ...this.updateHeaders,
  Accept: 'application/json' // Always set Accept header, overriding any user-provided Accept
};
const response = await net.fetch(url, { headers });
if (response.status === 204) return { ok: true, available: false };
else if (response.status === 200) {
  const updateJson = await response.json();
  if (Array.isArray(updateJson.releases)) {
    const packageInfo = msixUpdate.getPackageInfo();
    const currentVersion = packageInfo.version;
    if (!currentVersion) { this.emitError(new Error('Cannot determine current package version.')); return { ok: false, available: false }; }
    return this.parseStaticReleasFile(updateJson, currentVersion);
  } else {
    return this.parseDynamicReleasFile(updateJson);
  }
} else {
  this.emitError(new Error(`Unexpected response status: ${response.status}`));
  return { ok: false, available: false };
}

Accept 放在展开之后,无条件覆盖用户传的 Accept(源码注释明说)。204 被当作"无更新",这是 MSIX 独有的约定;200 之外一律报错,包括 304(尽管 net.fetch 可能已经处理了缓存)。

静态格式(函数名在源码里就拼成了 parseStaticReleasFile,少一个 e,动态版同样拼错)要求 json.releases 是数组且 json.currentRelease 是字符串,然后:

const versionComparison = this.compareVersions(json.currentRelease, currentVersion);
if (versionComparison === 0) return { ok: true, available: false };
if (versionComparison < 0) {
  if (this.allowAnyVersion) { /* Continue to find the release entry for downgrade */ }
  else return { ok: true, available: false };
}
const releaseEntry = json.releases.find((r: any) => r.version === json.currentRelease);
if (!releaseEntry || !releaseEntry.updateTo) { ... }

compareVersions()(:180-201)的实现是这段里最脆弱的:

auto-updater-msix.ts:184-186

const parts1 = v1.split('.').map((part) => {
  const parsed = parseInt(part, 10);
  return isNaN(parsed) ? 0 : parsed;
});
// ... 补齐到 maxLength,逐段比大小

问题有三个:

  1. parseInt 会吃掉尾部非数字:"1.2-beta" → [1, 2](因为 "2-beta" 解析成 2),与 "1.2" 相等;"1.0.0-beta.1" → [1,0,0,0,1],反而比 "1.0.0"(补齐后 [1,0,0,0,0])大,预发布版被判成更新版本。
  2. 非数字段一律当 0:"2.0.0-rc1" → [2,0,0]("0-rc1" 得 0),语义完全丢失。
  3. 只支持点分数字,注释说兼容 Windows 四段版本 x.y.z.a,这倒是做到了(maxLength 补齐)。

它比较的是 currentRelease 与 packageInfo.version,而 packageInfo.version 来自 WinRT 的 IPackageId,是 MSIX 清单里的四段版本字符串,不是 app.getVersion()。把 package.json 的 semver 填进 feed 里做比较,结果会莫名其妙。

另外 allowAnyVersion: true 只在 versionComparison < 0 时起作用(放行降级),但真正允许系统装旧包的是 forceUpdateFromAnyVersion——它同时被传给 updateMsix() 的 AddPackageOptions(:415-421)。TS 侧与原生侧各有一道,缺一不可。

20.7.4 两道前置拒绝

checkForUpdates()(:388-410)在任何网络请求之前先查包信息:

auto-updater-msix.ts:393-398

const packageInfo = msixUpdate.getPackageInfo();
if (!packageInfo.familyName) {
  return this.emitError(new Error('MSIX updates are not supported'));
}
// If appInstallerUri is set, Windows App Installer manages updates automatically
// Prevent updates here to avoid conflicts
if (packageInfo.appInstallerUri) {
  return this.emitError(new Error(
    'Auto-updates are managed by Windows App Installer. Updates are not allowed when installed via Application Manifest.'));
}

第二条尤其重要:如果 MSIX 包是通过 .appinstaller 清单分发、由 Windows App Installer 托管更新的,Electron 主动拒绝自己更新,避免两套机制抢同一个包。这是四个实现里唯一显式"礼让系统更新器"的逻辑。它意味着 process.windowsStore === true 并不足以保证 checkForUpdates() 能工作,还得看清单里有没有 appInstallerUri。

20.7.5 updateMsix():UI 线程解析,IO 线程执行,Promise 跨线程 settle

electron_api_msix_updater.cc:534-582:

v8::Local<v8::Promise> UpdateMsix(const std::string& package_uri,
                                  gin_helper::Dictionary options) {
  gin_helper::Promise<void> promise(isolate);
  v8::Local<v8::Promise> handle = promise.GetHandle();
#if BUILDFLAG(IS_WIN)
  if (!HasPackageIdentity()) {
    promise.RejectWithErrorMessage("The process has no package identity.");
    return handle;
  }
  boolean is_api_present = FALSE;
  if (FAILED(CheckApiContractPresent(10, &is_api_present)) || !is_api_present) {
    promise.RejectWithErrorMessage(
        "This Windows version does not support MSIX updates via this API. "
        "Windows 10 version 2004 or later is required.");
    return handle;
  }
  // Parse options on UI thread (where V8 is available)
  UpdateMsixOptions opts;
  options.Get("deferRegistration", &opts.defer_registration);
  /* ... 5 个布尔 ... */
  content::GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&DoUpdateMsix, package_uri, opts,
                                MakeSettleCallback(std::move(promise))));
#else
  promise.RejectWithErrorMessage("MSIX updates are only supported on Windows with identity.");
#endif
  return handle;
}

三层结构很清晰:

  • 两道同步 reject:HasPackageIdentity() 调 GetCurrentPackageFullName() 判断有无包身份;CheckApiContractPresent(10, ...) 查 WinRT API 契约(IPackageManager9 需要 Windows 10 2004 / contract v10)。这两条在 JS 调用当场就返回 rejected Promise,不进线程切换。
  • options 必须在 UI 线程解析:gin_helper::Dictionary 背后是 V8 对象,跨线程访问会崩。注释 // Parse options on UI thread (where V8 is available) 点明了这一点。解析出的 UpdateMsixOptions 是纯 POD(5 个 bool),可以安全值拷贝。
  • MakeSettleCallback 把 Promise 移到 IO 线程:SettlePromise() 里再用 base::BindPostTask 把结果投回 UI 线程 resolve/reject。这是 Electron 里处理"JS Promise + 后台线程"的标准手法,第 16 章讲 utility process 时也见过同构的写法。

TS 侧调用时传的是:

auto-updater-msix.ts:420-426

await msixUpdate.updateMsix(msixUrlInfo.updateUrl, {
  deferRegistration: true,
  developerMode: false,
  forceShutdown: false,
  forceTargetShutdown: false,
  forceUpdateFromAnyVersion: this.allowAnyVersion
} as UpdateMsixOptions);

as UpdateMsixOptions 只是 TypeScript 类型断言,运行时是个普通对象;C++ 侧用 options.Get(key, &out) 逐项取,缺项保持 POD 默认值 false,类型不符则 Get 失败也保持 false,不会抛错。所以把 deferRegistration 写成字符串 "true" 会静默变成 false。

DoUpdateMsix 走的是 AddPackageByUriAsync,源码 :115-131 有一段很有价值的注释:

In COM/WinRT, each interface version (IPackageManager, IPackageManager5, IPackageManager9, etc.) is a separate interface that must be queried independently. Unlike C++ inheritance, IPackageManager9 does NOT inherit methods from IPackageManager5 or the base IPackageManager.

所以 CreatePackageManager() 拿到 IPackageManager 之后,还得为需要用的每个方法单独 QueryInterface 到对应版本。GetPackageInfo() 里对 IPackage2 / IPackage4 / IPackage6 也重复了这个模式。这是 WinRT ABI 的约束,不是 Electron 的设计选择。

OnDeploymentCompleted()(:262-280)里有个 fire_and_forget 分支:

electron_api_msix_updater.cc:268-271

if (data->fire_and_forget) {
  DebugLog(op_name + " initiated. Force shutdown or target shutdown requested. Good bye!");
  std::move(data->settle).Run(std::string());
  return;
}

它在 :405 与 :511 被赋值为 opts.force_shutdown || opts.force_target_shutdown。也就是说一旦要求强制关闭应用,C++ 层就不再等 WinRT 异步操作的结果,直接把 Promise resolve 掉。原因很实际:进程马上要被 Windows 杀掉,等结果没有意义,而且等下去可能永远等不到。日志里那句 Good bye! 是源码原文。

20.7.6 quitAndInstall():靠系统重启,不靠 app.quit()

auto-updater-msix.ts:436-460:

async quitAndInstall() {
  if (!this.updateAvailable) {
    this.emitError(new Error("No update available, can't quit and install"));
    app.quit();
    return;
  }
  try {
    const packageInfo = msixUpdate.getPackageInfo();
    if (!packageInfo.familyName) return this.emitError(new Error('MSIX updates are not supported'));
    msixUpdate.registerRestartOnUpdate('');
    this.emit('before-quit-for-update');
    // force shutdown of the application and register the package to be installed on restart
    await msixUpdate.registerPackage(packageInfo.familyName, { forceShutdown: true });
  } catch (error) { this.emitError(error as Error); }
}

与另外两套实现完全不同:

  • 没有 app.quit()、没有 app.relaunch()、没有 WindowList::CloseAllWindows()。它靠 registerPackage(..., {forceShutdown: true}) 让 Windows 部署 API 强制结束本进程并完成注册。
  • registerRestartOnUpdate('') 对应 RegisterApplicationRestart(nullptr, 1|2|8)(:633-666),注释写明 flags 是 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_REBOOT,且刻意不设 RESTART_NO_PATCH——只有更新触发的重启才恢复应用,崩溃/挂起/系统重启都不恢复。
  • 无更新时它仍然调 app.quit()(emitError 之后),这是三套实现里唯一会这么做的;macOS 版只报错,Squirrel 版只 return。
  • before-quit-for-update 在这里发出,但没有关闭窗口,紧接着进程被系统杀掉,所以监听这个事件做异步清理(写文件、发请求)几乎没有机会完成。

getPackageInfo() 返回的 MSIXPackageInfo 有 7 个字段:id、familyName、developmentMode、version、signatureKind('developer' | 'enterprise' | 'none' | 'store' | 'system')、可选 appInstallerUri。其中 signatureKind 只在 WinRT contract 7(Windows 10 1703+)存在时才填,老系统上对象里可能缺这个键——TS 的类型声明把它写成必填,是类型比运行时乐观的一处。

20.7.7 MSIX 与 Squirrel 共享的那个坑

auto-updater-msix.ts:423-432 的 update-downloaded:

this.emit('update-downloaded', {}, msixUrlInfo.releaseNotes,
          msixUrlInfo.releaseName, msixUrlInfo.releaseDate,
          msixUrlInfo.updateUrl, () => { this.quitAndInstall(); });

与 Squirrel 版一模一样,第一个参数是 {}。字段名比 Squirrel 版规范(releaseName 真的来自 json.name,releaseDate 来自 pub_date),但整体契约仍然与 macOS 的 C++ Emit 差一位。

三套实现唯一的共识是最后一个参数是可调用的 quitAndInstall 闭包,且都用了 () => { this.quitAndInstall(); } 或 base::BindRepeating(&AutoUpdater::QuitAndInstall, base::Unretained(this)) 这种"绑定当前实例"的形式。C++ 侧注释写着 // Keep compatibility with old APIs.——早期 Electron 的 update-downloaded 不带回调,应用要自己调 autoUpdater.quitAndInstall();后来加了回调但没改参数位置,于是形成了现在这个"第一个参数时有时无"的局面。


20.8 C++ 粘合层:delegate 生命周期与两条发错误事件的路径

electron_api_auto_updater.cc:26-33 175 行,是把平台层的 C 风格 delegate 接到 gin 对象上的胶水。它只在 macOS 那条路上真正在工作(Windows 两份 TS 实现绕过了它),但里面的几个设计对理解 Electron 的对象生命周期很有代表性。

20.8.1 构造与析构:一个没有 SelfKeepAlive 的 cppgc 对象

electron_api_auto_updater.cc:26-33

AutoUpdater::AutoUpdater(v8::Isolate* isolate) {
  auto_updater::AutoUpdater::SetDelegate(this);
  gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
  data->AddDisposeObserver(this);
}
AutoUpdater::~AutoUpdater() = default;
void AutoUpdater::OnBeforeMicrotasksRunnerDispose(v8::Isolate* isolate) {
  gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
  data->RemoveDisposeObserver(this);
  auto_updater::AutoUpdater::SetDelegate(nullptr);
}

与第 18 章的 Tray(SelfKeepAlive{this} 导致永不 GC)和第 17 章的 Session(同样持有 SelfKeepAlive)不同,AutoUpdater 没有自保活。它由 Initialize 里 dict.Set("autoUpdater", AutoUpdater::Create(isolate)) 挂在 exports 上存活,一旦 exports 被回收,这个 cppgc 对象也可能被回收。

这就是 OnBeforeMicrotasksRunnerDispose 里那句 SetDelegate(nullptr) 的必要性:auto_updater::AutoUpdater::delegate_ 是一个裸静态指针(auto_updater.cc:12),如果对象被 GC 而 delegate 没清,平台层下一次回调就是 use-after-free。第 17 章讲 UserDataLink 用 cppgc::WeakPersistent<gin::WeakCell<Session>> 解决同类问题,这里用的是"在 isolate 销毁前主动解绑"。

auto_updater::Delegate 的所有虚函数都有空默认实现(auto_updater.h:19-37),protected: virtual ~Delegate() = default;。所以 delegate 为 nullptr 时平台层会直接 return(auto_updater_mac.mm 里每处都先 if (!delegate) return;),解绑之后不会有事件,也不会崩。

顺带一提:auto_updater.h:60-63 留着一条十年前的 FIXME,说 SetFeedURL 不该收 gin::Arguments*、参数解析应归 api 层。这条注释至今没兑现——auto_updater_mac.mm:33 里 gin::Arguments、gin_helper::Dictionary、v8::Local<v8::Value> 全用上了。它也解释了 Linux stub 为什么连参数都不看:签名是历史包袱,实现可以空。

20.8.2 两个 OnError 重载走的是完全不同的发射路径

electron_api_auto_updater.cc:42-88 有两个 OnError。第一个(单参数)刻意绕开了 gin::EmitEvent:

void AutoUpdater::OnError(const std::string& message) {
  // We do not use gin::EmitEvent here because we do not want to
  // put this in its own CallbackScope and delegate to Node.js'
  // specialized handling for Error objects.
  if (GetWrapper(isolate).ToLocal(&wrapper)) {
    auto error = v8::Exception::Error(gin::StringToV8(isolate, message));
    std::vector<v8::Local<v8::Value>> args = {
        gin::StringToV8(isolate, "error"),
        gin::ConvertToV8(isolate, error->ToObject(...).ToLocalChecked()),
        gin::StringToV8(isolate, message),
    };
    node::MakeCallback(isolate, wrapper, "emit", args.size(), args.data(), {0, 0});
  }
}

注释给的理由是:不想让 gin::EmitEvent 新建一个 CallbackScope,从而触发 Node.js 对 Error 对象的专门处理(Node 的 MakeCallback 会在回调期间接管 async_hooks、process._tickCallback、未捕获异常等)。这里手工调 node::MakeCallback 并传 {0, 0}(async_id / trigger_async_id),把这次 emit 挂在当前 async 上下文上。

第二个重载(三参数,带 code 与 domain)反而用了常规路径:

void AutoUpdater::OnError(const std::string& message, const int code,
                          const std::string& domain) {
  auto error = v8::Exception::Error(...);
  auto errorObject = error->ToObject(...).ToLocalChecked();
  errorObject->CreateDataProperty(context, gin::StringToV8(isolate, "code"),
                                  v8::Integer::New(isolate, code)).Check();
  errorObject->CreateDataProperty(context, gin::StringToV8(isolate, "domain"),
                                  gin::StringToV8(isolate, domain)).Check();
  gin_helper::EmitEvent(isolate, wrapper, "error", errorObject, message);
}

于是一个可观察的差异出现了:macOS 上来自 SetFeedURL 的 NSError / NSException、QuitAndInstall 的 "No update available" 走单参数重载;来自 checkForUpdatesCommand 的 error: 回调走三参数重载。后者 emit 出来的 Error 对象上多两个字段 code(数字,不是 Node 惯用的字符串)与 domain(如 SQRLUpdaterErrorDomain)。

而 Windows 两边都是 this.emit('error', error, error.message),Error 对象上没有 code/domain。所以按 err.code 做错误分支的代码在 Windows 上永远走 default。

CreateDataProperty 用的是 .Check(),意味着创建失败会直接 CHECK 崩进程——对 Error 对象加两个普通属性通常不会失败,这里没有留降级。

20.8.3 update-downloaded 末尾那个回调是 Unretained 的

electron_api_auto_updater.cc:102-108

void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes,
                                     const std::string& release_name,
                                     const base::Time& release_date,
                                     const std::string& url) {
  Emit("update-downloaded", release_notes, release_name, release_date, url,
       // Keep compatibility with old APIs.
       base::BindRepeating(&AutoUpdater::QuitAndInstall,
                           base::Unretained(this)));
}

base::Unretained(this) 绑定的是裸指针。这个回调被转成 JS 函数后,如果应用在 update-downloaded 里把它存起来、等很久以后再调用(比如用户点了"稍后重启"),而此时 AutoUpdater 已被 GC,就是悬垂调用。实践中它靠 exports 上的强引用保活,正常不会出问题——但这与 20.8.1 里"没有 SelfKeepAlive"是同一处风险的两种表现。

Windows 两份 TS 实现用的是箭头函数闭包 () => { this.quitAndInstall(); },this 是模块级单例,天然不会被回收。这是 TS 重写顺手解决掉的一个 C++ 侧遗留问题。

20.8.4 before-quit-for-update 的真实语义

auto-updater.md:137-148 说这个事件"在用户调用 quitAndInstall() 后发出,此时不会发 before-quit"。从 C++ 代码看,它发在 QuitAndInstall() 的第一行,早于 WindowList::IsEmpty() 判断、更早于 CloseAllWindows():

void AutoUpdater::QuitAndInstall() {
  Emit("before-quit-for-update");
  if (WindowList::IsEmpty()) { auto_updater::AutoUpdater::QuitAndInstall(); return; }
  WindowList::AddObserver(this);
  WindowList::CloseAllWindows();
}

所以监听者拿到事件时窗口还都在,可以做同步清理。但它是 Emit(同步派发),如果在监听器里做异步操作(写文件、发请求),CloseAllWindows() 不会等它。文档建议用它替代 before-quit 做退出前清理,前提是清理必须同步完成。

反过来,CloseAllWindows() 触发每个窗口的 close 事件,窗口的 beforeunload 处理器可以取消关闭。如果某个窗口拒绝关闭,OnWindowAllClosed() 永远不来,QuitAndInstall() 就卡在"注册了 observer、窗口还开着"的状态,不会重启也不会报错——源码里没有超时或失败通知。


20.9 crashReporter:主进程与子进程的初始化时序是反的

这一节是全章最容易误判的部分。直觉上"主进程先启动、子进程后启动,所以主进程先装好崩溃捕获",实际源码完全相反:主进程要等 JS 主动调 crashReporter.start(),子进程一开机就自己装好。

20.9.1 主进程:等 JS

electron_main_delegate.cc:283-297 的注释把设计写明白了:

#if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  // In the main process, we wait for JS to call crashReporter.start() before
  // initializing crashpad. If we're in the renderer, we want to initialize it
  // immediately at boot.
  if (!IsBrowserProcess()) {
    ElectronCrashReporterClient::Create();
    crash_reporter::InitializeCrashpad(false, process_type);
#if BUILDFLAG(IS_WIN)
    SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
#endif
  }
#endif

if (!IsBrowserProcess()) 把主进程排除在外。为什么?因为 crashReporter.start() 要传 submitURL、uploadToServer、extra 这些只有 JS 知道的参数;Crashpad 的 InitializeCrashpad() 一旦调用,上传 URL 和 consent 就定下来了,后面改要另走接口。所以主进程把初始化推迟到 JS 调用点(electron_api_crash_reporter.cc:145 的 crash_reporter::Start)。

代价就是文档里那句警告:"If the crash reporter is not initialized at the time a renderer process is created, then that renderer process will not be monitored by the crash reporter." 子进程要连的 handler socket 是主进程在 start() 时才建好的,晚于这个时机的子进程拿不到它。这就是"crashReporter.start() 要尽可能早,最好在 app.on('ready') 之前"的真正原因——不是性能,是子进程启动顺序。

Windows 那行 SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX) 与 20.13 的 WER 机制配套:沙箱 job 用 JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION 给子进程设了 SEM_NOGPFAULTERRORBOX,会让 Windows Error Reporting 不运行已注册的 helper。Crashpad 装好后必须把这个标志清掉,注释是 Crashpad is installed now, so let WER see those.

20.9.2 Linux:zygote 要单独处理,且多了两个条件

Linux 分支(:299-311)与 Win/Mac 不同:

electron_main_delegate.cc:302-307

#if BUILDFLAG(IS_LINUX)
  // Zygote needs to call InitCrashReporter() in RunZygote().
  if (!IsZygoteProcess() && !IsBrowserProcess()) {
    ElectronCrashReporterClient::Create();
    if (command_line->HasSwitch(crash_reporter::switches::kCrashpadHandlerPid)) {
      crash_reporter::InitializeCrashpad(false, process_type);
      crash_reporter::SetFirstChanceExceptionHandler(
          v8::TryHandleWebAssemblyTrapPosix);
    }
  }
#endif

两个额外条件:

  • !IsZygoteProcess():zygote 在 RunZygote() 里单独初始化,另有 ElectronMainDelegate::ZygoteForked()(:473-489)在 fork 之后重新 Create() + InitializeCrashpad() + SetCrashKeysFromCommandLine()。原因是 zygote fork 出的子进程需要重新建立与 handler 的连接,而且 DIR_USER_DATA 要到 BrowserMain 之后才可用。
  • HasSwitch(kCrashpadHandlerPid):没有这个命令行开关就完全不初始化。它是主进程在 electron_browser_client.cc:629-633 追加的:
#if BUILDFLAG(IS_LINUX)
  pid_t pid;
  if (crash_reporter::GetHandlerSocket(nullptr, &pid)) {
    command_line->AppendSwitchASCII(
        crash_reporter::switches::kCrashpadHandlerPid,
        base::NumberToString(pid));
  }

也就是说 Linux 上子进程的崩溃捕获依赖主进程已经 start() 过,否则 GetHandlerSocket 拿不到 pid、开关不追加、子进程跳过初始化。这比 Win/Mac 更严格:那边子进程无条件初始化,只是上传配置可能缺失。

SetFirstChanceExceptionHandler(v8::TryHandleWebAssemblyTrapPosix) 只在 Linux 有,它把 WASM 越界陷阱接到 Crashpad 之前——与 20.2.6 的 wasm_trap_handlers fuse 是配套的两层:fuse 决定 V8 用不用信号处理器(SetUpWebAssemblyTrapHandler()),这里决定信号先给谁处理。

20.9.3 Node 子进程:又一条独立路径

以 ELECTRON_RUN_AS_NODE 启动的进程走 NodeMain()(node_main.cc:244-251),崩溃捕获在 :240-262:

#if BUILDFLAG(IS_LINUX)
    // On Linux, initialize crashpad after Nodejs init phase so that
    // crash and termination signal handlers can be set by the crashpad client.
    if (pid != -1) {
      ElectronCrashReporterClient::Create();
      crash_reporter::InitializeCrashpad(false, "node");
      crash_keys::SetCrashKeysFromCommandLine(*base::CommandLine::ForCurrentProcess());
      crash_keys::SetPlatformCrashKey();
      command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
    }
#elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
    ElectronCrashReporterClient::Create();
    crash_reporter::InitializeCrashpad(false, "node");
    /* ... 同样设置 crash keys ... */
#endif

注意 Linux 分支特意等 Node.js 初始化阶段之后才装,注释说这样 Crashpad 才能装自己的 crash / termination 信号处理器(否则会被 Node 覆盖)。装完还把 kCrashpadHandlerPid 开关从命令行删掉,注释是 Ensure the flags and env variable does not propagate to userland——防止用户 JS 通过 process.argv 看到 handler pid。

process_type 在这里硬编码成字符串 "node",与 EnableBreakpadForProcess() 里的 process_type == "node" 对上(electron_crash_reporter_client.cc:262-267)。

20.9.4 EnableBreakpadForProcess 的白名单里没有 browser

electron_crash_reporter_client.cc:267-273

bool ElectronCrashReporterClient::EnableBreakpadForProcess(
    const std::string& process_type) {
  return process_type == switches::kRendererProcess ||
         process_type == switches::kZygoteProcess ||
         process_type == switches::kGpuProcess ||
         process_type == switches::kUtilityProcess ||
         process_type == "node";
}

这是 Chromium CrashReporterClient 的钩子,决定哪些子进程启用 Breakpad/Crashpad 客户端。browser 不在列表里,因为主进程走的是 crash_reporter::Start() 里的 InitializeCrashpad(IsBrowserProcess(), ...),第一个参数是 true,由 Chromium 侧单独处理。两条路径不能混。

20.9.5 幂等标志与 MAS 构建

electron_api_crash_reporter.cc:78-84:

bool g_crash_reporter_initialized = false;
bool IsCrashReporterEnabled() { return g_crash_reporter_initialized; }

置位发生在实际 Start() 的第一段:

electron_api_crash_reporter.cc:147-149

#if !IS_MAS_BUILD()
  if (g_crash_reporter_initialized)
    return;
  g_crash_reporter_initialized = true;
  ...
#endif

三个推论:

  1. crashReporter.start() 只有第一次有效。第二次调用会解析参数、可能抛类型错误、可能发弃用警告,但 Start() 立刻 return,新参数全部丢弃。文档说 "The crash reporter cannot be disabled once started" 是对的,但更准确是"连改配置都不能"。
  2. MAS 构建里这个标志永远是 false,因为置位语句在 #if !IS_MAS_BUILD() 内。于是 IsCrashReporterEnabled() 在 Mac App Store 构建里恒返回 false。
  3. IsCrashReporterEnabled() 在整个仓库里没有任何调用点:electron_browser_client.cc:85 include 了 electron_api_crash_reporter.h,但那个 include 只是为了 api::crash_reporter::GetClientId()(Linux 分支,:644)。也就是说这个导出函数目前是死代码,不要拿它当"能否上报"的判据。

MAS 构建的降级在 electron_api_crash_reporter.cc 里做得非常彻底:

APIMAS 构建
start()参数照常解析,但 Start() 整段不编译,g_crash_reporter_initialized 不置位
getUploadedReports()返回空 v8::Array
getLastCrashReport()返回 v8::Null
getUploadToServer()恒 false
setUploadToServer()空
addExtraParameter / removeExtraParameter绑到 NoOp() / SetCrashKeyStub
getParameters()空 map(#if !IS_MAS_BUILD() 包住填充逻辑)

这与 20.4.3 的 Linux autoUpdater 空壳是同一种"方法全在、行为全无"的降级,只是它由编译期 IS_MAS_BUILD() 决定,不由 fuse 决定。

20.9.6 Linux 的 client id 与 no_channel

GetClientId() 只在 #if BUILDFLAG(IS_LINUX) 编译(electron_api_crash_reporter.cc:96-131):

std::string GetClientId() {
  static base::NoDestructor<std::string> client_id;
  if (!client_id->empty()) return *client_id;
  *client_id = ReadClientId();
  if (client_id->empty()) {
    *client_id = base::Uuid::GenerateRandomV4().AsLowercaseString();
    WriteClientId(*client_id);
  }
  return *client_id;
}

它落在 DIR_CRASH_DUMPS/client_id 文件里,ReadClientId() 用 ReadFileToStringWithMaxSize(path, &id, 36) 且要求长度恰好 36(UUID v4 小写字符串长度)。文件被截断或污染就重新生成并覆盖。读写都包在 ScopedAllowBlockingForElectron 里——这是主线程上的同步文件 IO,Electron 显式放行的。

子进程拿到的命令行开关是 <client_id>,no_channel(browser_client.cc:640-645),zygote 例外:

// Zygote Process gets booted before any JS runs, accessing GetClientId
// will end up touching DIR_USER_DATA path provider and this will
// configure default value because app.name from browser_init has not run yet.
if (process_type != ::switches::kZygoteProcess) { ... }

注释点出一个启动顺序陷阱:zygote 比 JS 还早,此时读 GetClientId() 会触发 DIR_USER_DATA 路径提供器用默认 app name 初始化,后面 app.name 改了也来不及。所以宁可不给 zygote 传这个开关。这与 20.9.1 主进程要等 JS 是同一类约束——路径与身份类配置必须在 JS 设好之后才能固化。

20.9.7 配置是怎么从主进程走到子进程的:命令行装配

把 20.9.1 那句"晚于 start() 创建的 renderer 不受监控"追到底,落点在 electron_browser_client.cc:626-670 的子进程命令行装配处。它做的四件事把前面的因果补齐了:

#if BUILDFLAG(IS_LINUX)
  pid_t pid;
  if (crash_reporter::GetHandlerSocket(nullptr, &pid)) {
    command_line->AppendSwitchASCII(
        crash_reporter::switches::kCrashpadHandlerPid,
        base::NumberToString(pid));
  }
  if (process_type != ::switches::kZygoteProcess) {
    std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel";
    command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value);
  }
#endif
  // zygote 比 JS 还早,DIR_USER_DATA 不可用
  if (process_type != ::switches::kZygoteProcess) {
    base::FilePath user_data_dir;
    if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
      command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir);
  }

关键点在于这些开关是在创建子进程的那一刻,从主进程当前状态拷贝出来的快照:GetHandlerSocket() 要 handler 已经存在,GetClientId() 要 DIR_CRASH_DUMPS 已定,chrome::DIR_USER_DATA 要 app.name 已生效。所以 crashReporter.start() 不是"设个全局标志",而是必须在第一个子进程的命令行被拼装之前把这几样东西都准备好。事后补调 start(),已经跑起来的 renderer 拿不到 --crashpad-handler-pid,20.9.2 的 Linux 判据就直接跳过初始化。

同一段后面还有一组与本章无关、但和第 17 章直接接上的代码:

electron_browser_client.cc:659-666

  if (process_type == ::switches::kUtilityProcess ||
      process_type == ::switches::kRendererProcess) {
    // Copy following switches to child process.
    static constexpr std::array<const char*, 11U> kCommonSwitchNames = {
        switches::kStandardSchemes.c_str(), switches::kEnableSandbox.c_str(),
        switches::kSecureSchemes.c_str(), switches::kBypassCSPSchemes.c_str(),
        switches::kCORSSchemes.c_str(), switches::kFetchSchemes.c_str(),
        switches::kServiceWorkerSchemes.c_str(), switches::kStreamingSchemes.c_str(),
        switches::kNoStdioInit.c_str(), switches::kCodeCacheSchemes.c_str(),
        switches::kExtensionSchemes.c_str()};
    command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
                                   kCommonSwitchNames);

这 11 个开关大多是 protocol.registerSchemesAsPrivileged() 在命令行上留下的 scheme 列表。第 17 章讲过"为什么 privileges 必须走命令行"——因为 renderer 进程启动时也要调 url::Add*Scheme 把同样的 scheme 注册进自己的 Blink 实例,光在 browser 进程改内存没用。这里就是那条链的下游。

把两组开关放一起看会得到一条通用的 Electron 规律:凡是需要所有进程一致的状态,都通过 CopySwitchesFrom 在 fork 时快照下发,而不是靠运行时同步。fuse 之所以不用走这条路,是因为它写死在可执行文件里,每个进程读的是同一份字节——这恰好绕开了多进程一致性问题,也是 fuse 机制能做到"进程无关"的根本原因。


20.10 crashReporter.start():一次参数解析,两套注入机制

electron_api_crash_reporter.cc:282-289 里有两个都叫 Start 的函数:外层在匿名命名空间(:266-324),负责把 gin_helper::Dictionary 解析成 C++ 参数;内层在 electron::api::crash_reporter(:137-189),负责真正初始化。中间那层转换,藏着好几个"设了没生效"的原因。

20.10.1 read lambda 的三段判据

electron_api_crash_reporter.cc:282-289

auto read = [&](std::string_view key, auto* out, std::string_view type) {
  v8::Local<v8::Value> value;
  if (!options.Get(key, &value) || value->IsUndefined() ||
      gin::ConvertFromV8(thrower.isolate(), value, out)) {
    return true;
  }
  thrower.ThrowTypeError(base::StrCat({key, " must be ", type}));
  return false;
};
if (!read("productName", &product_name, "a string") ||
    !read("companyName", &company_name, "a string") ||
    !read("extra", &extra, "an object with string values") ||
    !read("globalExtra", &global_extra, "an object with string values") ||
    !read("ignoreSystemCrashHandler", &ignore_system_crash_handler, "a boolean") ||
    !read("submitURL", &submit_url, "a string") ||
    !read("uploadToServer", &upload_to_server, "a boolean") ||
    !read("rateLimit", &rate_limit, "a boolean") ||
    !read("compress", &compress, "a boolean")) {
  return;
}

ConvertFromV8 的返回值语义是"成功为 true",所以这个 lambda 在三种情况下返回 true:键不存在、undefined、转换成功;只有"键存在、不是 undefined、且转换失败"才抛 TypeError。于是:

  • start({ submitURL: undefined }) 与 start({}) 行为一致(当没传);
  • start({ submitURL: 123 }) 抛 "submitURL must be a string";
  • start({ extra: { a: 1 } }) 抛 "extra must be an object with string values"——std::map<std::string,std::string> 的转换器要求值也是字符串;
  • 未知键被静默忽略。start({ submiURL: '...' }) 拼错不会报错,只会在后面撞上 uploadToServer && submit_url.empty() 抛 submitURL must be specified...,还算有提示;但拼错 uploadToServr 就完全静默地用默认值 true。

九个选项的默认值在函数开头显式写出:product_name = Browser::Get()->GetName()、upload_to_server = true、compress = true、rate_limit = false、ignore_system_crash_handler = false,其余为空串/空 map。注意 productName 用的是 Browser::Get()->GetName() 而不是 app.getName(),两者在 app.name 被改过之后可能不同(第 18 章讲 ApplicationInfo 时提过这条链)。

20.10.2 两道校验与一条弃用警告

electron_api_crash_reporter.cc:304-311

if (upload_to_server && submit_url.empty()) {
  thrower.ThrowError("submitURL must be specified when uploadToServer is true");
  return;
}
if (upload_to_server && !compress) {
  electron::util::EmitDeprecationWarning(thrower.isolate(),
      "Sending uncompressed crash reports is deprecated and will be removed "
      "in a future version of Electron. Set { compress: true } to opt-in to "
      "the new behavior. Crash reports will be uploaded gzipped, ...");
}

第一道是硬错误:uploadToServer: true(默认)且没给 submitURL 就抛。文档说自 PR #28105 起 submitURL 在 uploadToServer: false 时可选,源码与之一致。

第二道只是警告,不改行为:compress: false 仍然生效(不压缩上传),只是发一条弃用提示。而且判据带 upload_to_server &&——不上报时设 compress: false 连警告都不会有,因为根本没有上传发生。

20.10.3 globalExtra 的三个自动注入与两个保留键

electron_api_crash_reporter.cc:317-320

if (!company_name.empty())
  global_extra.try_emplace("_companyName", company_name);
global_extra.try_emplace("_productName", product_name);
global_extra.try_emplace("_version", electron::Browser::Get()->GetVersion());

try_emplace 意味着用户已经设了同名键就不覆盖。所以想自定义 _productName 是可以的,自动注入不会抢。但 companyName 这个"已弃用别名"的处理是:只有非空才写 _companyName,且同样让位给用户值。

接着 Start() 把这 global_extra 交给 ElectronCrashReporterClient::SetGlobalAnnotations(),而 GetExtraProcessAnnotations()(electron_crash_reporter_client.cc:237-242)是:

std::map<std::string, std::string>
ElectronCrashReporterClient::GetExtraProcessAnnotations() {
  std::map<std::string, std::string> annotations = global_annotations_;
  annotations["prod"] = ELECTRON_PRODUCT_NAME;
  annotations["ver"] = ELECTRON_VERSION_STRING;
  return annotations;
}

这里用的是 operator[] 覆盖赋值,不是 try_emplace。所以:

  • prod 与 ver 是两个不可覆盖的保留键。在 globalExtra 里写 prod: 'MyApp' 会被强制改成 "Electron"(编译期常量 ELECTRON_PRODUCT_NAME),ver 被改成 Electron 版本字符串。想在报告里带自己的产品名/版本,必须用别的键,比如上面自动注入的 _productName / _version。
  • 文档说 globalExtra"默认包含 productName、app version、Electron version",从源码看是 _productName、_version(下划线前缀)与 prod / ver 四个键,命名与文档描述的对不上。

GetProductInfo() 同样返回 ProductInfo(ELECTRON_PRODUCT_NAME, ELECTRON_VERSION_STRING, /*channel=*/"")——channel 恒空,Windows 版的 GetProductNameAndVersion() 也把 special_build / channel_name 留空。这些字段是给 Chromium 崩溃上报体系用的,不读应用配置。

20.10.4 extra 与 globalExtra 是两套不同机制

Start() 内层(:150-188)里有三处几乎相同的循环:

electron_api_crash_reporter.cc:156-163

std::string process_type = is_node_process ? "node" : GetProcessType();
#if BUILDFLAG(IS_LINUX)
  for (const auto& pair : extra)
    electron::crash_keys::SetCrashKey(pair.first, pair.second);
  {
    electron::ScopedAllowBlockingForElectron allow_blocking;
    ::crash_reporter::InitializeCrashpad(IsBrowserProcess(), process_type);
  }
  if (ignore_system_crash_handler) { ... }
#elif BUILDFLAG(IS_MAC)
  for (const auto& pair : extra)
    electron::crash_keys::SetCrashKey(pair.first, pair.second);
  ::crash_reporter::InitializeCrashpad(IsBrowserProcess(), process_type);
  if (ignore_system_crash_handler) { ... }
#elif BUILDFLAG(IS_WIN)
  for (const auto& pair : extra)
    electron::crash_keys::SetCrashKey(pair.first, pair.second);
  ElectronCrashReporterClient::RegisterWerHelperModuleForCurrentUser();
  ...
  ::crash_reporter::InitializeCrashpadWithEmbeddedHandler(...);
#endif

对照一下两个参数的去向:

extraglobalExtra
存储crash_keys::SetCrashKey() → 进程内 std::deque<CrashKeyString>SetGlobalAnnotations() → client 的 global_annotations_ map
作用域只有调用 start() 的这个进程通过 Chromium 的进程启动参数传给所有子进程
是否能改能,addExtraParameter / removeExtraParameter不能,文档明说 "cannot be changed once the crash reporter has been started"
getParameters() 能查到吗能不能
谁优先—文档说 global 优先;源码里两者根本不进同一张表

文档里"如果 key 同时出现在 global 与进程级 extra 中,global 优先"这句话,从源码看并没有一个合并点来做优先级判断——它们走向两个不同的数据结构,最后都会被塞进同一个 minidump 的不同区域(annotation vs crash key)。同名时服务端看到哪个,取决于解析工具,不是 Electron 决定的。

三个平台分支的差异也要记:

  • Linux 与 macOS 都处理 ignore_system_crash_handler,设 crashpad::CrashpadInfo::...->set_system_crash_reporter_forwarding(kDisabled);Windows 分支完全没有这段,与文档 "_macOS_ _Linux_、This option has no effect on Windows" 一致。
  • Linux 的 InitializeCrashpad 额外包了 ScopedAllowBlockingForElectron(允许主线程阻塞 IO),另两个平台不需要。
  • Windows 走的是 InitializeCrashpadWithEmbeddedHandler,参数里带 user_data_dir 的 UTF-8 和一个空 base::FilePath();另外在初始化之前先 RegisterWerHelperModuleForCurrentUser()(20.13)。
  • is_node_process 参数在 JS 侧永远传 false(:322 的最后一个实参),只有 C++ 内部其他入口能传 true;process_type 实际取的是 GetProcessType(),主进程下是 "browser"。

20.10.5 setUploadToServer 的双写与一个反直觉的 getter

electron_api_crash_reporter.cc:327-329

void SetUploadToServer(bool upload) {
#if !IS_MAS_BUILD()
  ElectronCrashReporterClient::Get()->SetCollectStatsConsent(upload);
  // Reads the consent set above back through IsRunningUnattended().
  crash_reporter::SetUploadConsent(upload);
#endif
}

两处都要写:一处是 Electron 自己的 client(collect_stats_consent_),一处是 Chromium 的全局状态。注释说后者会通过 IsRunningUnattended() 把刚才设的值读回去——而 IsRunningUnattended() 的实现是:

electron_crash_reporter_client.cc:221-222

bool ElectronCrashReporterClient::IsRunningUnattended() {
  return !collect_stats_consent_;
}

即"不同意上报" ↔ "无人值守"。Chromium 用这个标志决定是否弹上传确认 UI。所以 uploadToServer: false 不只是"不上传",还会让 Crashpad 认为这是无人值守环境、跳过交互。

getUploadToServer() 读的是 GetCollectStatsConsent(),与 SetUploadToServer 写的第一个字段对应;但如果有人只调了 crash_reporter::SetUploadConsent()(比如 Chromium 内部),这两个值可能不同步。源码里没有一致性校验。

ShouldRateLimitUploads() / ShouldCompressUploads() / GetUploadUrl() / GetProductInfo() 都是同一个 client 上的简单 getter,把 start() 的参数转交给 Crashpad。整个 ElectronCrashReporterClient 用 base::NoDestructor 单例(:34-37),Create() 的实际作用是 crash_reporter::SetCrashReporterClient(Instance()) 加一次 BREAKPAD_DUMP_LOCATION 环境变量覆盖——它每次调用都会做这两件事,但因为是幂等的(同一个实例、同一个路径覆盖),多处调用没有副作用。

顺带记一个隐藏开关:Create() 会读环境变量 BREAKPAD_DUMP_LOCATION,非空就 PathService::Override(DIR_CRASH_DUMPS, ...)。它优先于 app.setPath('crashDumps', ...) 吗?不,两者都写同一个 PathService key,谁后执行谁生效;Create() 在 start() 里调用,所以如果 JS 在 start() 之前调 app.setPath,环境变量会覆盖它。文档只说"在启动 crash reporter 之前调 setPath",没提这个环境变量的存在。


20.11 crash keys:为什么这里必须用 std::deque

crash_keys.cc:32-38 只有 128 行,但开头那段注释是整章最直白的"为什么这么写":

// Do NOT replace with base::circular_deque. CrashKeyString wraps a
// crashpad::Annotation that holds self-referential pointers and registers
// in a process-global linked list; relocating elements (as circular_deque
// does on growth) corrupts that list and hangs the crashpad handler.
// std::deque never relocates existing elements. See #50795.
auto& GetExtraCrashKeys() {
  constexpr size_t kMaxCrashKeyValueSize = 20320;
  static_assert(kMaxCrashKeyValueSize < crashpad::Annotation::kValueMaxSize,
                "max crash key value length above what crashpad supports");
  using CrashKeyString = crash_reporter::CrashKeyString<kMaxCrashKeyValueSize>;
  static base::NoDestructor<std::deque<CrashKeyString>> extra_keys;
  return *extra_keys;
}

Crashpad::Annotation 内部持有指向自身的指针,并在进程级全局链表里注册。容器扩容时若搬移元素,那些自引用指针就指向旧地址,链表被写坏,崩溃时 handler 会挂住——注意这是崩溃路径上的死循环,比普通内存错误更难查,因为只有真崩了才触发。std::deque 的分段存储保证插入不搬移已有元素,所以这里不能用 std::vector,也不能用看起来更"现代"的 base::circular_deque。注释里直接给了 issue 编号 #50795,说明这是踩过坑之后加的。

kMaxCrashKeyNameLength = 40,SetCrashKey() 的判据是 key.size() >= 40 → 实际允许最长 39 字节,与文档一致。超长时:

crash_keys.cc:55-58

if (key.size() >= kMaxCrashKeyNameLength) {
  util::EmitWarning(base::StrCat({"The crash key name, '", key,
      "', is longer than 40 bytes, ignoring it."}), "electron");
  return;
}

发一条 warning 然后静默丢弃整个键值对,不抛错、不截断。值长度 20320 由模板参数固定,Crashpad 侧会截断超长值(文档说 "Values longer than the maximum length are truncated")——Electron 这边没有自己截,只是 static_assert 保证模板参数没超过 Annotation::kValueMaxSize。

两个 NoDestructor 容器(名字 deque 与 CrashKeyString deque)靠下标对齐:

crash_keys.cc:66-71

auto iter = std::ranges::find(crash_key_names, key);
if (iter == crash_key_names.end()) {
  crash_key_names.emplace_back(key);
  GetExtraCrashKeys().emplace_back(crash_key_names.back().c_str());
  iter = crash_key_names.end() - 1;
}
GetExtraCrashKeys()[iter - crash_key_names.begin()].Set(value);

CrashKeyString 构造时吃的是 crash_key_names.back().c_str()——指向名字 deque 里那个 std::string 的内部缓冲区。这里能成立,同样是因为 std::deque 不搬移元素;换成 std::vector,一次扩容就会让所有已注册 annotation 的 name 指针悬空。注释没有重复解释这一点,但它和前一段是同一个约束的两个面。

ClearCrashKey() 只调 .Clear(),不删名字、不缩容。所以 getParameters() 里必须过滤:

crash_keys.cc:84-87

void GetCrashKeys(std::map<std::string, std::string>* keys) {
  ...
  for (const auto& key : crash_key_names) {
    const auto& value = crash_keys[i++];
    if (value.is_set()) keys->emplace(key, value.value());
  }
}

后果是:一个进程里曾经用过的所有 key 名字会永久留在这两个 deque 里,反复 add/remove 同一个 key 不会泄漏新的 annotation,但不同 key 名用多了就是单调增长。这也是为什么这套容器是 NoDestructor——它跟进程同寿,不需要析构。

另外两个 crash key 是 Electron 自己加的兼容键,注释写得很坦诚:

crash_keys.cc:96-103

void SetCrashKeysFromCommandLine(const base::CommandLine& command_line) {
  // NB. this is redundant with the 'ptype' key that //components/crash
  // reports; it's present for backwards compatibility.
  static crash_reporter::CrashKeyString<16> process_type_key("process_type");
  if (IsRunningAsNode()) process_type_key.Set("node");
  else {
    std::string process_type = command_line.GetSwitchValueASCII(::switches::kProcessType);
    process_type_key.Set(process_type.empty() ? "browser" : process_type);
  }
}
void SetPlatformCrashKey() {
  // Note: this is redundant with the 'plat' key that
  // //components/crash already includes. Remove it.
  static crash_reporter::CrashKeyString<8> platform_key("platform");
  /* win32 / darwin / linux / unknown */
}

process_type 与 platform 是历史遗留,Chromium 已经有 ptype / plat。IsRunningAsNode() 又回到 20.2.1 那个 static bool 缓存——fuse 的结果在这里间接决定了崩溃报告里的进程类型字段。

20.11.1 renderer 侧只有三个方法,没有 start()

crash-reporter.ts:1-3 全文:

const { addExtraParameter, removeExtraParameter, getParameters } = process._linkedBinding(
  'electron_renderer_crash_reporter'
);
export default { addExtraParameter, removeExtraParameter, getParameters };

electron_api_crash_reporter_renderer.cc:35-44 的 Initialize 也只绑这三个(getParameters 与 browser 侧实现相同,都是 crash_keys::GetCrashKeys)。所以在这个版本里,渲染进程根本没有 crashReporter.start(),调用会得到 TypeError: ... is not a function。文档 crash-reporter.md 的历史记录里写着 "Deprecated calling this method in the renderer process",但当前状态是彻底移除;文末 "This method is only available in the main process" 才是准确的。

IS_MAS_BUILD() 时 renderer 侧把 addExtraParameter / removeExtraParameter 绑到两个空 stub,getParameters() 返回空 map——与 20.9.5 的表一致。

一个实践结论:想在所有进程里带上同一个自定义字段,不能只在主进程 start({extra: ...}),因为 extra 只进主进程的 crash keys(20.10.4)。正确做法是 start({globalExtra: ...});如果字段要动态更新,就得在每个进程里各自调 addExtraParameter,且 renderer 里要经 preload + contextBridge 暴露(文档开头那段 IMPORTANT 讲的正是这个)。

crashpad_support.cc:40 是另一个只在 Linux 有内容的绑定,导出 getCrashdumpSignalFD() 与 getCrashpadHandlerPID(),都从 crash_reporter::GetHandlerSocket() 取,失败返回 -1。非 Linux 平台上 electron_common_crashpad_support 导出的是空对象——与第 19 章讲的"非打印构建里 electron_browser_printing 导出空对象"是同一种条件编译降级。


20.12 查询已上报报告:一次同步磁盘读

electron_api_crash_reporter.cc:196-266 把两个查询 API 建在同一条链上:

scoped_refptr<UploadList> LoadCrashUploadList() {
  auto list = CreateCrashUploadList();
  electron::ScopedAllowBlockingForElectron allow_blocking;
  list->LoadSync();
  return list;
}
constexpr size_t kMaxUploadReportsToList = std::numeric_limits<size_t>::max();
v8::Local<v8::Object> ToReportObject(v8::Isolate* isolate,
                                     const UploadList::UploadInfo* upload) {
  return gin::DataObjectBuilder{isolate}
      .Set("date", upload->upload_time)
      .Set("id", upload->upload_id)
      .Build();
}

几个必须知道的事实:

  1. 这是同步 API,且真的阻塞主线程读文件。LoadSync() 前面显式包了 ScopedAllowBlockingForElectron,说明 Chromium 的线程限制原本会拦住它。上报告记录多的时候,getUploadedReports() 会让 UI 卡一下。源码里的开发者注记承认了这点:switch to using Load() instead of LoadSync() once the synchronous version of getUploadedReports is deprecated so we can remove our patch——现在还在等一个 patch 被移除。
  2. 返回对象只有 date 与 id 两个字段,没有文件路径、没有大小、没有上传状态。文档里写的 upload_time / upload_id 是 C++ 结构字段名,JS 侧拿到的是 date / id。
  3. kMaxUploadReportsToList = size_t::max 表示从不截断,历史记录全量读进内存再转 V8 数组。
  4. getLastCrashReport() 用 std::ranges::max_element(reports, {}, [](const auto* u){ return u->upload_time; }) 按时间取最大,不是取列表最后一项;空列表返回 v8::Null。

CreateCrashUploadList() 有平台分叉:

electron_api_crash_reporter.cc:207-214

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  return base::MakeRefCounted<CrashUploadListCrashpad>();
#else
  base::FilePath crash_dir_path;
  base::PathService::Get(electron::DIR_CRASH_DUMPS, &crash_dir_path);
  base::FilePath upload_log_path =
      crash_dir_path.AppendASCII(CrashUploadList::kReporterLogFilename);
  scoped_refptr<UploadList> result =
      base::MakeRefCounted<TextLogUploadList>(upload_log_path);
  // Crashpad keeps the records of C++ crashes (segfaults, etc) in its
  // internal database. The JavaScript error reporter writes JS error upload
  // records to the older text format. Combine the two to present a complete
  // list to the user.
  // Note: what is "The JavaScript error reporter", and do we care
  // about it?
  std::vector<scoped_refptr<UploadList>> uploaders = {
      base::MakeRefCounted<CrashUploadListCrashpad>(), std::move(result)};
  return base::MakeRefCounted<CombiningUploadList>(std::move(uploaders));
#endif

Linux 要把 Crashpad 内部数据库与旧的文本日志(CrashUploadList::kReporterLogFilename)合并(CombiningUploadList),macOS / Windows 只读 Crashpad 数据库。注释里那句 what is "The JavaScript error reporter" 表明连维护者都不确定第二个数据源现在还有没有生产者——但它仍被合并进结果。所以 Linux 上的 getUploadedReports() 可能包含另一套机制写进来的、格式不同的记录。

IS_MAS_BUILD() 下这两个函数被替换成返回空数组与 Null 的短版本(:192-200),连 UploadList 都不创建。


20.13 WER helper:Windows 上唯一在注册表里留痕的逻辑

electron_crash_reporter_client.cc:98-180 是本章唯一涉及 Windows 注册表的代码,目的是解决一类 Crashpad 抓不到的崩溃:__fastfail 终止(STATUS_STACK_BUFFER_OVERRUN,来自安全检查失败、CFG 违规、CRT 的 abort())。这类终止不经过进程内异常处理器,只能由 Windows Error Reporting 在进程外加载一个 helper DLL,让它去请 Crashpad handler 写 minidump。

命名规则写在注释里:

electron_crash_reporter_client.cc:115-116

// Copied from crashpad's crashpad_wer.dll by //electron:electron_wer and
// shipped in the assets directory (the executable's directory by default) as
// <exe name>_wer.dll, so an app that renames electron.exe to myapp.exe must
// rename the helper to myapp_wer.dll.
constexpr base::FilePath::CharType kWerHelperSuffix[] =
    FILE_PATH_LITERAL("_wer.dll");

GetWerHelperPath() 用 base::FILE_EXE 取可执行文件名、去掉扩展名、拼 _wer.dll,再和 base::DIR_ASSETS 组合。打包时把 electron.exe 改名,就必须同步把 electron_wer.dll 改成 <新名>_wer.dll,否则 helper 找不到,__fastfail 类崩溃没有 dump。文档把这条写在显眼位置,是因为它没有任何运行时报错。

RegisterWerHelperModuleForCurrentUser()(start() 时调用)做四件事:

electron_crash_reporter_client.cc:160-167

base::win::RegKey key;
if (key.Create(HKEY_CURRENT_USER, kWerHelperRegistryKey,
               KEY_QUERY_VALUE | KEY_SET_VALUE) != ERROR_SUCCESS) return;
const base::FilePath install_root = path.DirName().DirName();
std::vector<std::wstring> stale;
for (base::win::RegistryValueIterator it(HKEY_CURRENT_USER, kWerHelperRegistryKey);
     it.Valid(); ++it) {
  base::FilePath registered(it.Name());
  if (registered != path &&
      base::FilePath::CompareEqualIgnoreCase(registered.BaseName().value(), path.BaseName().value()) &&
      base::FilePath::CompareEqualIgnoreCase(registered.DirName().DirName().value(), install_root.value()) &&
      !base::PathExists(registered)) stale.emplace_back(it.Name());
}
for (const std::wstring& name : stale) key.DeleteValue(name.c_str());
if (!key.HasValue(path.value().c_str())) {
  // The value's data is ignored by WER; only the name matters.
  key.WriteValue(path.value().c_str(), DWORD{0});
}
  • 注册表键是 HKCU\Software\Microsoft\Windows\Windows Error Reporting\RuntimeExceptionHelperModules,WER 只加载以完整路径作为值名列出的 helper。
  • 值的数据完全不重要(写了个 DWORD{0}),只有值名(路径)有用。
  • 清理逻辑专门针对 Squirrel 的 app-x.y.z 版本目录:每次更新都会留一个新路径,所以遍历同 basename、同安装根、且文件已不存在的旧条目删掉。只删自己的(DirName().DirName() 比较),不动别的应用。
  • 文档补充:安装器若写 HKLM 也可以;不 ship 这个 DLL 就等于主动退出这套机制——RegisterWerHelperModuleForCurrentUser() 开头 if (path.empty() || !base::PathExists(path)) return; 直接返回。

GetWerRuntimeExceptionModule() 有一句容易忽略的注释:

electron_crash_reporter_client.cc:146-147

// Called once per process during crashpad initialization, including in
// sandboxed children, so do not touch the disk here; registering a path
// that does not exist is harmless (WER only loads listed, existing DLLs).
std::wstring ElectronCrashReporterClient::GetWerRuntimeExceptionModule() {
  return GetWerHelperPath().value();
}

它会在沙箱子进程里被调用,所以不能做文件存在性检查(沙箱没权限);宁可返回一个可能不存在的路径。真正检查与注册只在主进程 start() 那一次做。这与 20.9.1 里 SetErrorMode(... & ~SEM_NOGPFAULTERRORBOX) 是配套的两端:一端让 WER 愿意看,一端让 WER 能找到 helper。


20.14 全章对照与十个常见误解

20.14.1 三条边界的对照表

维度fusesautoUpdatercrashReporter
决策点打包时改二进制字节模块加载时按平台/包身份选实现进程启动时按时序装 handler
决定者@electron/fuses 或手工 patchprocess.platform + process.windowsStoreIsBrowserProcess() / IS_MAS_BUILD() / JS 调用 start()
保护机制操作系统代码签名无(只是分发)无(只是一次性标志)
运行时可探测吗9 个里只能查 1 个(features.isRunAsNodeEnabled)能,但从行为反推更可靠能,getUploadToServer() 等
静默失败典型关 grantFileProtocol... 后 file:// 白屏Linux quitAndInstall() 关窗不重启MAS 构建里所有方法存在但全空
与前面章节的接口17 章 asar / cookie、6 章 Node 集成18 章 WindowList、17 章 net.fetch16 章多进程、17 章网络上传

20.14.2 十个"不报错但就是没生效"的点

  1. features.isPrintingEnabled() 不是 fuse——它是 BUILDFLAG(ENABLE_PRINTING)。9 个 fuse 里只有 runAsNode 能从 JS 查,其余 8 个查不到不代表没开。
  2. 关掉 grantFileProtocolExtraPrivileges 会让用 file:// 加载 asar 资源的应用白屏——五处读取里最关键的是 protocol_registry.cc:34-57 用 AsarURLLoaderFactory 替换 file:// factory,fuse 关时这段整块不执行。先迁自定义协议再关 fuse。
  3. Linux 上 autoUpdater.setFeedURL() 静默成功、getFeedURL() 恒返回 ''——C++ 绑定无条件存在,四个平台方法在 !IS_MAC || IS_MAS_BUILD() 下编译成空函数。
  4. Linux 上 quitAndInstall() 会关掉所有窗口然后什么都不做——api::AutoUpdater::QuitAndInstall 会 CloseAllWindows(),而底层的平台方法是空的,也没有 app.quit()。
  5. macOS 的 update-downloaded 比 Windows 少一个参数——C++ Emit 第一个就是 releaseNotes,两个 Windows 实现第一个是 {}。按文档的 event 签名写在 mac 上整体错位一位。
  6. Squirrel.Windows 的 releaseDate 是 new Date()——源码注释 Date is not available on Windows, so fake it.,别拿它当发布日期展示。
  7. Squirrel.Windows 不发 before-quit-for-update——它的 quitAndInstall() 只有 processStart() + app.quit()。文档把这个事件写成通用行为,按它做退出前清理在该平台上永远不执行。
  8. crashReporter.start() 第二次调用会全部丢弃——g_crash_reporter_initialized 在参数解析之后、Start() 开头就 return;注意参数解析仍会跑,所以第二次调用仍可能抛类型错误或发弃用警告,只是什么都不改。
  9. globalExtra 里的 prod / ver 会被覆盖——GetExtraProcessAnnotations() 用 operator[] 强制写 ELECTRON_PRODUCT_NAME / ELECTRON_VERSION_STRING;_productName / _version 才是可以自定义的键,而且 try_emplace 保证用户值优先。
  10. getUploadedReports() 是阻塞主线程的同步磁盘读——LoadSync() 外加 ScopedAllowBlockingForElectron,Linux 还要合并两个数据源;记录多时会卡 UI,且返回对象只有 date / id。

20.14.3 排查顺序

遇到"设了没生效"按这个顺序查:① 这段代码在不在当前二进制里(IS_MAS_BUILD()、BUILDFLAG(...)、平台 #if);② 模块加载的是哪一份实现(process.platform、process.windowsStore);③ 调用落在哪个时序窗口(主进程等 JS、子进程开机即装、fuse 在 main() 之前);④ 最后才看参数(read lambda 的静默忽略、options.Get 失败保持默认、try_emplace 与 operator[] 的差别)。


20.15 小结:把决定提前到 JS 之外

这一章三块内容看起来毫不相干,实际上都在做同一件事——把一部分配置从"运行时传参"移到"运行时之前",理由各不相同:

  • fuses 提前到打包时,是为了让操作系统而不是应用代码来担保安全配置。整个机制的物理形态因此必须是"二进制里一串可被定位、可被翻转、但运行时只读的字节";volatile 保证翻转有效,代码签名保证翻不回去,fuses.json5 的位置寻址保证工具不会错改槽位。代价是 9 个 fuse 里 8 个在 JS 里查不到,出问题时只能靠打包流水线的记录回溯。
  • autoUpdater 提前到模块加载时,是因为四套后端的差异不是参数能抹平的:Squirrel.Mac 是 Objective-C 状态机、Squirrel.Windows 是 Update.exe 的 stdout 协议、MSIX 是 WinRT 异步部署 API、Linux 什么都没有。Electron 选择了"用同一个 API 名字包住四份实现,但不强行统一语义",于是留下了参数错位、事件缺失、日期伪造这些接缝。
  • crashReporter 提前(或推迟)到进程启动时,是因为崩溃捕获必须在崩溃之前装好,而上传配置又只有 JS 知道。这个矛盾的解法是主进程等 JS、子进程开机即装、Linux 再靠一个命令行开关把两者连起来;代价是 start() 有一个非常窄的有效窗口,错过之后新建的子进程不受监控。

把这条线和前面几章连起来看会更清楚:第 17 章的 NetworkContext 是"每个 session 一份身份",第 18 章的 Tray 是"对象自己决定何时销毁",第 19 章的 OSR 是"编译期开关换掉整条取帧路径"——而这一章是这些决定里最靠前的一层:有些代码根本没被加载,有些位根本不允许你读。

排查这类问题时,"我传的参数是否正确"往往是最后一个该问的问题。先问"这段代码在这个二进制、这个进程、这个时刻存在吗",答案通常就在 build.py 生成的那个数组、十行的模块分发器,或者 electron_main_delegate.cc 那句 if (!IsBrowserProcess()) 里。