《Electron 45.2.3 内核解剖》第 22 章 打包与分发:从 asar 到发布产物

0 阅读45分钟

《Electron 45.2.3 内核解剖》第 22 章 打包与分发:从 asar 到发布产物

22.0 五条边界,和一张产物全图

前 21 章讲的都是"一个正在运行的 Electron 进程里发生了什么"。这一章反过来:讲一个还没运行的 Electron 是怎么被组装出来的,以及组装出来的那些字节在运行时被谁、按什么格式、以什么信任级别读回去。

这件事在 Electron 里比在普通框架里更微妙,因为分发产物不只是"给用户的文件",它同时是运行时的数据源:app.asar 的 header 决定 require() 能不能找到模块,Info.plist 里的一个字符串决定进程是否 LOG(FATAL),PE 资源里的一段 JSON 决定整个应用能不能启动,config.gypi 决定第三方原生模块用哪套编译选项。打包期的错误不会在打包期报错,而是在用户机器上以"白屏""启动即退出"的形式出现。

先钉死五条边界,后面所有反直觉现象都能归到其中一条:

边界两侧关键判据
① 构建期 / 运行期GN target、@electron/asar vs asar::Archive、C++ 绑定同一个 .asar 文件,写的一方是 Node 脚本,读的一方是 Chromium C++
② 归档 / 真实文件系统app.asar vs app.asar.unpacked、sentinel fdfs 的每次调用先要回答"这个路径在不在归档里"
③ 可信 / 不可信字节header hash、per-block hash、fuse、OS 代码签名校验信息必须放在归档之外,否则等于没校验
④ 主产物 / 旁路产物dist.zip vs symbols.zip/dsym/pdb/debug符号与二进制靠 MODULE 头的 hash 配对,不靠文件名
⑤ 构建产物 / 发布资产dist.zip → electron-v45.2.3-*.zip同一份 zip 在上传前被改名、抹时间戳、算 checksum

按这五条边界,把 BUILD.gn、build/、script/ 里所有产物摊开(release-assets.json 是这个清单的权威版本,64 条模式):

产物生成处内容谁消费
dist.zipdist_zip("electron_dist_zip") BUILD.gn:1919可运行二进制 + 资源 + default_app.asar + 两个 LICENSE@electron/packager / 直接下载
symbols.zipscript/zip-symbols.py:22breakpad_symbols/ 全平台崩溃堆栈符号化
dsym.tar.xz / dsym-snapshot.zipzip-symbols.py:29-43macOS dSYM,snapshot 单独拆包Apple 崩溃日志 / lldb
pdb.zipzip-symbols.py:44-57Windows PDB,排除 electron_xcache.exe.pdbWinDbg / 符号服务器
debug.zipzip-symbols.py:58-64Linux debug/ 目录(剥离出的调试段)gdb
ffmpeg.zipdist_zip("electron_ffmpeg_zip") BUILD.gn:1948带专有编解码器的 libffmpeg需要 H.264/AAC 的应用
chromedriver.zipBUILD.gn:1965ChromeDriver 二进制WebDriver 自动化测试
mksnapshot.zipBUILD.gn:1985mksnapshot + v8_context_snapshot_generator自定义 V8 快照
hunspell_dictionaries.zipBUILD.gn:2012拼写检查词典session.setSpellCheckerDictionaryDownloadURL 的离线替代
xcache.zip / libcxx*_headers.zip / libcxx-objectsBUILD.gn:2020-2065编译工具链缓存与头文件原生模块编译
electron-api.json / electron.d.tspackage.json:67-69文档抽取出的 API 结构与类型IDE、TypeScript 用户
node-*.tar.gz / node.libupload-node-headers.pyNode 头文件 + 导入库node-gyp
toolchain profileupload.py:159-166windows_toolchain_profile.jsonPGO

这张表里有个容易被忽略的事实:release-assets.json 里的 xcache.zip 不在清单中(upload.py:130 会上传它,但 release-assets.json 没有对应模式)。清单是"发布时应当存在什么"的校验表,不是"上传脚本会产出什么"的完整描述——两者靠人工同步。

本章按五条边界的顺序展开:22.1–22.4 讲 asar 的格式与运行时读法(边界①②),22.5–22.7 讲完整性校验与 URL 侧接入(边界③),22.8–22.9 讲符号与二进制分离(边界④),22.10–22.13 讲发布、签名、体积与类型产物(边界⑤),22.14–22.16 收束成对照表和常见误解。


22.1 asar 的物理格式:一个 Pickle 加一段 JSON

22.1.1 前 8 字节不是 JSON 长度

大部分人以为 .asar 是"4 字节长度 + JSON 头 + 拼接的文件内容"。实际读法在 archive.cc:230-272,第一步读的是 8 字节:

buf.resize(8);
if (!file_.ReadAtCurrentPosAndCheck(buf)) { ... }

uint32_t size;
if (!base::PickleIterator(base::Pickle::WithData(buf)).ReadUInt32(&size)) {
  LOG(ERROR) << "Failed to parse header size from " << path_.value();
  return false;
}

base::Pickle 是 Chromium 的序列化容器,它自己的头部是 4 字节 payload 长度,后面跟 payload(这里是一个 uint32_t)。所以 8 字节的构成是:

偏移长度含义
0..34Pickle 声明的 payload 大小(小端,通常 = 4)
4..74size:后续 Pickle 块的长度

紧接着 buf.resize(size) 再读一块,又用 PickleIterator::ReadString(&header) 把 JSON 字符串解出来(:259-272)。也就是说 header 被包了两层 Pickle:外层是一个 uint32,内层是一个 string。这个结构解释了 header_size_ = 8 + size(:306)——size 是第二块的总字节数,不是 JSON 的字节数;JSON 前面还有 4 字节 Pickle 长度和 4 字节字符串长度。

@electron/asar 的 getRawHeader() 返回 { headerString, headerSize, header },script/gn-asar-hash.js:10 用的正是 headerString:

const { headerString } = asar.getRawHeader(archive);
fs.writeFileSync(hashFile, crypto.createHash('SHA256').update(headerString).digest('hex'));

哈希对象是解码后的 JSON 字符串,不含 Pickle 前缀、不含 padding。这一点在 22.5 里会变成关键:macOS 与 Windows 上嵌入二进制的 header hash 必须按同样的口径算,算错一个字节就是启动即 LOG(FATAL)。

22.1.2 header 的字段词典

Archive::FillFileInfoWithNode(archive.cc:107-179)是这份 JSON 格式的事实规范,它逐字段读取:

键类型读取处语义
sizeint:112文件字节数;缺失或负值直接返回 false
unpackedbool:117为真时立即 return,不再读 offset/integrity
offsetstring:124相对内容区起点的十进制字符串,不是数字
executablebool:139影响 CopyFileOut 出来的临时文件权限位
linkstring:359符号链接目标,按 header 内路径解析
filesdictGetFilesNode :52-68目录节点
integritydict:146-170algorithm / hash / blockSize / blocks

三个容易踩的点:

offset 是字符串。源码用 FindString + base::StringToUint64,不是 FindInt。原因在于 asar 支持超过 2³¹ 的偏移,而 JSON 数字在 base::Value 里是 int32/double,早期实现为了避开精度问题统一写成十进制字符串。手写 asar 生成工具时若写成数字,GetFileInfo 会静默返回 false,表现为"文件在归档里但读不到"。

unpacked 会短路一切。:117-122 一旦看到 unpacked: true 就返回,连 integrity 都不看。Archive::CopyFileOut(:458-461)对这种条目直接拼出 <archive>.unpacked/<path> 的真实路径,不做任何拷贝、不做任何校验。这就是 asarUnpack 的本质:它把文件从整套完整性保护里移了出去,安全性完全交给 OS 文件系统权限。文档 asar-archives.md:183-201 只讲了"为了原生模块和杀毒软件",没讲这层含义。

link 不是文件系统符号链接。它只是 header 里的一个字符串,GetNodeFromPath(:83-100)按路径分隔符逐段重走 header 树来解析。Readdir/Stat 会把它报成 UV_DIRENT_LINK,但内核里不存在这个链接对象。

22.1.3 路径解析:从最深向上找 .asar

asar_util.cc:141-201 的 GetAsarArchivePath 决定了"哪个 .asar 分量算归档"。算法是从路径最深的组件往上扫,遇到第一个 MatchesExtension(".asar") 且 IsDirectoryCached() 为假的分量就停:

const auto component = base::FilePath::StringViewType{value}.substr(
    start, component_end - start);
if (component.size() >= 5 &&
    component[component.size() - 5] == base::FilePath::kExtensionSeparator &&
    base::FilePath(component).MatchesExtension(kAsarExtension)) {
  base::FilePath candidate =
      leaf ? full_path : base::FilePath(value.substr(0, component_end));
  if (!IsDirectoryCached(candidate)) { ... }
}

三条推论:

  • .asar 目录优先于 .asar 文件。若 resources/app.asar 真的是个目录,IsDirectoryCached 返回 true,扫描继续往外层找(通常找不到),整条路径按普通文件系统处理。这是"把 asar 解开就能调试"能工作的原因。
  • 嵌套归档取最深的那个。foo.asar/bar.asar/baz.js 里,只要 foo.asar/bar.asar 不是目录,就以它为归档、baz.js 为内部路径。
  • allow_root 参数(:171)控制"路径本身就是归档文件"的情况:为 false 时 leaf && !allow_root 直接返回 false,因为 fs.stat(app.asar) 应该看到归档文件本身,而不是归档的根目录。

同一份逻辑在 FindArchivePrefixLength(:257-312)里被用字符串视图重写了一遍,供 JS 侧的 splitPath 调用。两遍实现必须严格一致,否则 fs 包装层与 C++ 读档层会对同一路径得出不同结论——asar_util.cc:237 那条注释专门说明了为什么 POSIX 上必须用 base::FilePath{prefix} 而不是 FromUTF8Unsafe():

Node mode never calls setlocale(), so it is always in the "C" locale.

在 "C" locale 下 FromUTF8Unsafe 遇到非 ASCII 字节会返回空路径,中文路径的 asar 就会整体失效。这是第 21 章 node-spec-runner.js 那类"环境变量决定解释器行为"的又一个实例,只不过这次影响的是路径编码。

22.1.4 构建期:为什么 gn-asar.js 要先复制到临时目录

build/asar.gni 定义的 asar() 模板(BUILD.gn:347 用于 default_app_asar)并不直接调 asar pack app/,而是走 script/gn-asar.js:39-44:

const tmpPath = fs.mkdtempSync(path.resolve(os.tmpdir(), 'electron-gn-asar-'));
for (const file of files) {
  const newLocation = path.resolve(tmpPath, path.relative(base[0], file));
  fs.mkdirSync(path.dirname(newLocation), { recursive: true });
  fs.writeFileSync(newLocation, fs.readFileSync(file));
}
asar.createPackageWithOptions(tmpPath, out[0], {});

注释写明了原因:// Copy all files to a tmp dir to avoid including scrap files in the ASAR。GN 的 sources 是显式文件列表,而不是目录树;如果直接对源目录打包,同目录下的 .ts 源文件、BUILD.gn、README 都会混进产物。先按 sources 重建一棵干净的树,能保证 default_app.asar 里只有编译后的 JS 和资源。

代价有两处。一是 fs.writeFileSync 不带 mode 参数,所有重建文件的权限位由 umask 决定,asar 里的 executable 标记因此不可靠(对 default_app 无影响,但说明这套模板不适合打原生模块)。二是 createPackageWithOptions 的 options 传的是空对象 {},没有 unpack、ordering、integrity 任何配置;default_app.asar 是不带 per-file integrity 的最小归档,它的保护只来自 22.5 讲的 header hash。

asar.gni:50 还顺带生成 *_header_hash target:gn-asar-hash.js:10 算出 header SHA256 写入 $target_gen_dir/asar_hashes/*.hash,再由 asar_hashed_info_plist() 通过 script/gn-plist-but-with-hashes.js:12-13 把 ${DEFAULT_APP_ASAR_HEADER_SHA} 替换进 shell/browser/resources/mac/Info.plist:59-66。后者只有 11 行,替换逻辑是朴素的 String.replace:

for (const key of Object.keys(keyPairs)) {
  plistContents = plistContents.replace(`$\{${key}}`, keyPairs[key]);
}

replace 只替换第一次出现。若同一 plist 里写了两次同一个替换标记,第二个会原样留在 Info.plist 里;keyPairs 的构造靠 keySet.length / 2 把参数数组劈成"键 + 哈希文件"两半,参数个数为奇数时会静默错位。这两个都是构建脚本层面的"错配不报错",只能在出包后检查 plist 才能发现。

22.1.5 两个 fuse 决定了这份格式有多少信任

fuses.json5 共 14 行、9 个 fuse(第 20 章逐个讲过读取点)。与 asar 直接相关的是两个,默认都是 0(关闭):

fuse默认开启后改变什么
embedded_asar_integrity_validation0header 与文件内容都做 SHA256 校验,失败 LOG(FATAL)
only_load_app_from_asar0LoadAppPackage 只认 app.asar,且必须能作为归档打开

asar-integrity.md 明确写了"通常两个一起开",理由是:只开完整性校验、不锁死加载路径时,攻击者可以放一个 resources/app/ 目录绕过校验——但 app_package.cc:95-98 的候选顺序是 app.asar → app → default_app.asar,app.asar 优先,所以严格说绕过需要删掉或改名 app.asar。文档把这条说成"应用代码搜索路径可被绕过",代码给出的具体条件更窄。

另有一个跨章节的联动:electron_main_delegate.cc:126-136 的 ValidateV8Snapshot 用的开关也是 IsEmbeddedAsarIntegrityValidationEnabled():

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

kChecksum 由 build/checksum_header.py:20 在构建期从 v8_context_snapshot.bin 算出,连同 kSize 与 96 字节 kHeaderPrefix 一起编进头文件。也就是说打开 asar 完整性 fuse 会顺带锁死 V8 启动快照,自定义 snapshot(第 20 章 loadBrowserProcessSpecificV8Snapshot)与这个 fuse 的组合需要重新编译,不是翻一个位就能共存。这一层耦合在 fuses.md:118-125 的 embeddedAsarIntegrityValidation 段落里完全没有提及。

22.1.6 blockSize 的实际取值与 header hash 的口径验证

asar-integrity.md 给的示例里 blockSize: 1024,很容易被当成规范值。仓库里能查到的实际取值来自 spec/asar-integrity.spec.ts:112-130:

// Layout of the archive used by fixtures/apps/asar-integrity-reads: a
// multi-block entry (with a recognisable marker at the start of every 4MB
// integrity block so tests can corrupt a specific block), an entry that is
// exactly one block, and a small one.  Keep in sync with the fixture.
const kIntegrityBlockSize = 4 * 1024 * 1024;
const kMultiSize = 2 * kIntegrityBlockSize + 1024 * 1024 + 5;
const blockMarker = (n: number) => `ASARBLOCK${n}MAGIC!`;

@electron/asar 的 createPackage 按块写出 blocks,测试注释把实际块大小记为 4 MiB 并要求与 fixture 保持同步,据此造了三个文件:跨 3 个块的大文件(每块开头写 ASARBLOCK<n>MAGIC! 标记,供 corruptBlock(n) 精确定位篡改)、恰好一个块的文件、1000 字节的小文件。docs 里的 1024 只是示意,照它去算块的边界会完全对不上。

这份 spec 还把 22.1.1 讲的 hash 口径写成了可执行断言(:140-141):

asar-integrity.spec.ts:139-140

const headerHash = (asarPath: string) =>
  nodeCrypto.createHash('sha256').update(getRawHeader(asarPath).headerString).digest('hex');

getRawHeader().headerString 而非整个文件、而非 header 对象——与 script/gn-asar-hash.js:10 逐字一致。测试用它同时写 Windows 的 resedit({ asarIntegrity: ... }) 和 macOS 的 Info.plist,因此这条链路事实上规定了两个平台信任锚的算法口径。任何自研打包工具都要复现这三行,否则 plist/PE 里填的 hash 与 Archive::Init 算出的 hash 永远对不上,表现为启动即 LOG(FATAL)。

afterEach(:103-110)里还有一条 Windows 特有的清理逻辑:崩溃测试后 DLL 会被系统短暂占用,所以最多重试 4 次删除临时目录,每次等待 500 * attempt 毫秒。这与第 21 章 L5 那套"真实安装包测试需要自己处理 OS 残留"是同一类问题。


22.2 Archive::Init:四道校验与一个偏移基准

22.2.1 第一道:文件必须能打开,且错误要分类

archive.cc:217-228:

bool Archive::Init() {
  CHECK(!initialized_);
  initialized_ = true;
  if (!file_.IsValid()) {
    if (file_.error_details() != base::File::FILE_ERROR_NOT_FOUND) {
      LOG(WARNING) << "Opening " << path_.value() << ": "
                   << base::File::ErrorToString(file_.error_details());
    }
    return false;
  }

CHECK(!initialized_) 把 Init() 限定为一次性操作——Archive 构造后 header 永不重读,这是后面所有缓存(node cache、external files、retained fd)成立的前提。FILE_ERROR_NOT_FOUND 被单独静音:模块解析会大量探测不存在的路径,全打日志会淹没输出。

Archive 的构造函数(:195-203)在持有 ScopedAllowBlockingForElectron 的前提下用 FLAG_OPEN | FLAG_READ 打开,Windows 上额外用 _open_osfhandle 造一个 fd 供 GetUnsafeFD() 返回;析构时(:205-215)要先 _close(fd_) 再 file_.TakePlatformFile() 交出句柄所有权,否则同一个 OS handle 会被关两次。这是第 17 章 ReconnectableURLLoaderFactory 那类"跨抽象层持有同一资源"问题的又一个样本。

22.2.2 第二道:长度必须自洽

:247-257:

archive.cc:250-255

file_length = file_.GetLength();
if (file_length < 0 || static_cast<uint64_t>(file_length) < buf.size() ||
    size > static_cast<uint64_t>(file_length) - buf.size()) {
  LOG(ERROR) << "Header size exceeds archive size in " << path_.value();
  return false;
}
file_size_ = static_cast<uint64_t>(file_length);

三个条件分别挡住:取长度失败、文件比 8 字节头还短、声明的 size 超出剩余字节。注意这里是 > 而不是 >=:允许 size 恰好等于剩余全部字节(一个没有内容的归档),随后 buf.resize(size) 会读走全部剩余内容。file_size_ 在这一步就被固定,之后无论磁盘上的文件是否被替换,所有偏移计算都以这个值为准。

22.2.3 第三道:header 必须是 dict

:299-308:

archive.cc:299-305

std::optional<base::Value> value =
    base::JSONReader::Read(header, base::JSON_PARSE_CHROMIUM_EXTENSIONS);
if (!value || !value->is_dict()) {
  LOG(ERROR) << "Failed to parse header";
  return false;
}
header_size_ = 8 + size;
header_ = std::move(*value).TakeDict();

JSON_PARSE_CHROMIUM_EXTENSIONS 允许尾随逗号等 Chromium 方言,但 JSONReader 本身对深度有限制。header_ 是 std::optional<base::DictValue>,后面所有 LookupNode 都返回指向这棵树内部节点的裸指针(const base::DictValue*)——这棵树在 Archive 生命周期内不移动、不修改,所以裸指针是安全的;node_cache_ 也因此能缓存这些指针而不持有引用。

22.2.4 第四道:完整性校验发生在 JSON 解析之前

:274-297 被 #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) 包住,位置在读出 header 字符串之后、JSONReader::Read 之前:

archive.cc:276-283

if (electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled() &&
    RelativePath().has_value()) {
  std::optional<IntegrityPayload> integrity = HeaderIntegrity();
  if (!integrity.has_value()) {
    LOG(FATAL) << "Failed to get integrity for validatable asar archive: "
               << RelativePath().value();
  }
  if (integrity->algorithm != HashAlgorithm::kNone) {
    ValidateIntegrityOrDie(base::as_byte_span(header), *integrity, "<header>");
  } else {
    LOG(FATAL) << "No eligible hash for validatable asar archive: "
               << RelativePath().value();
  }
  header_validated_ = true;
}

顺序不是随意的:先用不可信的 header 字节算哈希、确认与二进制里嵌入的可信值一致,然后才解析它。反过来(先解析再校验)意味着恶意构造的深层 JSON、超长字符串会在校验前就已经交给 JSONReader,攻击面更大。header_validated_ 一旦置位,22.5 里每个文件的 FillFileInfoWithNode 才会去强制要求 integrity 字段。

RelativePath().has_value() 是另一个硬门槛:只有归档位于应用包内部(mac 相对 Contents/,Windows 相对 DIR_ASSETS)才进入校验。放在用户目录、临时目录的任意 asar 即使开了 fuse 也不校验——这与 asar-integrity.md:9 里"validates the contents of your app's ASAR archives"的表述一致,但文档没说清判据是路径归属而不是文件名。

header_size_ = 8 + size 是最后落定的偏移基准。FillFileInfoWithNode:131-137 的注释点明了它依赖 Init() 的保证:

// Init() guarantees |file_size| >= |header_size|.
const uint64_t content_size = file_size_ - header_size_;
if (relative_offset > content_size ||
    info->size > content_size - relative_offset) {
  return false;
}
info->offset = header_size_ + relative_offset;

relative_offset 与 size 都来自 header,即不可信数据。这两个条件分别防止"起点越界"和"区间越过内容区尾部",写成了减法形式而非 a + b > c,是为了避免 uint64_t 加法溢出。手写打包工具若把 offset 写成绝对值(含 8+size),所有文件都会读失败且没有任何日志——GetFileInfo 只是返回 false,上层报 ENOENT。


22.3 查找、缓存与"文件被替换"这件大事

22.3.1 node_cache_:3.2 万条后整表清空

Archive::LookupNode(archive.cc:321-339)是每次 fs.stat / require() 都要走的热路径:

constexpr size_t kMaxNodeCacheEntries = 32 * 1024;

const base::DictValue* Archive::LookupNode(std::string_view path) const {
  DCHECK(header_);
  {
    base::AutoLock auto_lock(node_cache_lock_);
    auto it = node_cache_.find(path);
    if (it != node_cache_.end())
      return it->second;
  }
  const base::DictValue* node = GetNodeFromPath(path, *header_);
  base::AutoLock auto_lock(node_cache_lock_);
  if (node_cache_.size() >= kMaxNodeCacheEntries)
    node_cache_.clear();
  node_cache_.emplace(std::string(path), node);
  return node;
}

三个设计决定值得逐一看:

命中与未命中都缓存。GetNodeFromPath 返回 nullptr 时也会被 emplace 进表。Node 的模块解析会反复探测 node_modules/x/package.json、index.js、index.json 等不存在的路径,缓存"不存在"比缓存"存在"更省时间。

满了整表清,不做 LRU。注释(:321-322)给出的理由是"启动期探测的路径数量足够容纳,超过之后直接重来比逐条淘汰便宜"。absl::flat_hash_map::clear() 不释放桶数组,所以清空后只是重新填充,没有反复分配。副作用是极端大的应用(超过 3.2 万个不同探测路径)会进入"填满→清空→再填满"的循环,模块解析性能出现周期性抖动。

缓存的是裸指针。node_cache_ 类型是 flat_hash_map<std::string, const base::DictValue*>,指向 header_ 这棵 base::DictValue 树的内部节点。因为 header_ 在 Init() 之后永不修改,且 Archive 由 shared_ptr 持有到第 22.3.4 节讲的进程级缓存里,这些指针不会悬空。

22.3.2 link 链深度 40 是安全边界,不是性能优化

archive.cc:40-45:

// Upper bound on how many "link" entries may be chained while resolving a
// single path. Legitimate archives only ever produce short link chains (one
// hop per symlinked directory captured at pack time), so this generous limit
// never rejects a valid lookup, while stopping a header whose links form a
// cycle from recursing until the stack is exhausted.
constexpr int kMaxLinkDepth = 40;

深度在两处独立计数:GetFilesNode(:58-59)处理"目录本身是 link",GetFileInfo 的私有重载(:361-363)处理"文件本身是 link"。两处都是 depth >= kMaxLinkDepth 就返回 false。注释说得很直白:这是防止恶意 header 里的 link 环把栈打爆。链路超限时 fs 层拿到的是 NOT_FOUND 而不是一个明确的"链接过深"错误,排查时容易误判成文件没打进包。

GetNodeFromPath(:83-100)还有一条容易看漏的说明:. 和 .. 在这里被当成普通名字,不做规范化。注释写明"callers pass lexically normalized paths"——真正的规范化由 JS 侧 splitPath 负责(22.4.1)。C++ 侧只跳过空组件(前导、尾部、连续分隔符)。这是一处明确的分层契约:如果某个原生插件绕过 fs 包装层直接调 C++ 的 archive 接口,带 .. 的路径不会按预期解析。

22.3.3 CopyFileOut:临时文件、权限位与 Windows 的重启删除

Archive::CopyFileOut(:442-483)负责把归档内条目变成真实路径,供 child_process.execFile、process.dlopen、<video src> 这类必须拿到路径的调用使用。四条路径:

情况行为
external_files_ 已有直接返回缓存的临时路径
info.unpacked返回 <asar>.unpacked/<path>,不拷贝
其他新建 ScopedTemporaryFile,从 retained fd 读 info.size 字节写入,校验完整性后缓存

external_files_ 是 Archive 的成员 flat_hash_map,缓存与 Archive 同生命周期。也就是说同一个文件被 execFile 十次,只在第一次落盘;这也意味着运行期间改了磁盘上的 asar,已缓存的临时文件不会更新。

POSIX 上落盘后立刻改权限(:469-478):

archive.cc:475-476

base::SetPosixFilePermissions(temp_file->path(),
                              info.executable ? 0555 : 0444);

注释解释了原因:"cached, integrity-validated copy that may be handed out again for the lifetime of this process, so make it read-only to keep it from being modified out from under later consumers"。这是 TOCTOU 防护:如果临时文件可写,第一次校验通过后被别的线程改掉,第二次消费者拿到的就是未校验内容。注意这里没有 group/other 的写位,也没有 owner 写位——进程自己也不能改。

ScopedTemporaryFile(scoped_temporary_file.cc)的两个平台分歧:Windows 上 Init() 会保留原扩展名(path_.AddExtension(ext)),因为 .node、.dll 的加载器按扩展名判断;析构时 Windows 用 base::DeleteFileAfterReboot() 而非 DeleteFile(),注释写明"mostly used for Node native modules,deleting it now will halt the program"——DLL 被映射进进程后文件仍在用,只能登记重启删除。POSIX 上则直接 DeleteFile(),已打开的 fd 仍可用。

InitFromFile 把整个条目一次性读进内存(std::vector<uint8_t> buf(size)),再一次性写出。对一个 200 MB 的 .node 或视频文件,这意味着峰值内存多一份完整副本,且没有流式路径。这是 asarUnpack 在文档里被推荐用于"大文件"的另一个理由,但文档只提了启动开销。

22.3.4 进程级 DirectoryCache 与 ArchiveMap

asar_util.cc:32-46 定义两张进程级表,都是 base::NoDestructor(永不析构,与第 17 章 ContextMap() 同款):

using ArchiveMap = std::map<base::FilePath, std::shared_ptr<Archive>>;
struct DirectoryCache {
  std::map<base::FilePath, bool> is_directory;
  base::Lock lock;
};

GetOrCreateAsarArchive(:116-139)的语义比名字更重:

asar_util.cc:126-132

auto archive = std::make_shared<Archive>(path);
if (archive->Init()) {
  map.try_emplace(lower, path, archive);
  DirectoryCache& cache = GetDirectoryCache();
  base::AutoLock dir_lock(cache.lock);
  cache.is_directory.insert_or_assign(path, false);
  return archive;
}

成功打开一次归档,就把这个路径在 DirectoryCache 里永久钉成"不是目录"。注释(:129-130)点明意图:"a directory swapped in after the open must not be read in its place"。这是防目录替换攻击:攻击者若能在应用启动后把 app.asar 换成同名目录,未固定的实现会开始从目录里读未校验的 JS。

IsDirectoryCached(:72-102)只缓存存在的路径,注释说明原因:"a *.asar path probed before anything is created there (the win32 mkdir wrapper does exactly that) must not be pinned as 'not a directory' for the rest of the process"。这类"负结果不缓存"的规则,与 22.3.1 的"未命中也缓存"恰好相反——因为前者的事实会随磁盘变化,后者的 header 树是冻结的。

IsArchivePrefix(:219-253)又加了一层按字符串记忆的缓存,并特意说明了 POSIX 上必须用 base::FilePath{prefix} 直接构造而非 FromUTF8Unsafe(C locale 问题,22.1.3 已述)。它同样只缓存 exists && is_archive 的结果。

22.3.5 retained fd:应用运行中替换 app.asar 会发生什么

这是这一节最反直觉、也最能说明"分发产物即运行时状态"的一点。

Archive 构造时打开 file_ 并一直持有。archive.h:105-125 的两个方法把这个句柄暴露出去:

// Returns a duplicate of the archive's retained file handle, for consumers
// that need exclusive ownership of a base::File (e.g. concurrent streaming
// reads). The duplicate refers to the same underlying file as |file_|, so
// like ReadFileAt() it is unaffected by the on-disk file being replaced.
base::File DuplicateFile();

// Returns the file's fd.
// Using this fd will not validate the integrity of any files
// you read out of the ASAR manually.  Callers are responsible
// for integrity validation after this fd is handed over.
int GetUnsafeFD() const;

ReadFileToString(asar_util.cc:314-348)的注释把因果写全了:

Read through the archive's retained file handle rather than re-opening the archive by path: |info|'s offset and integrity hash come from the cached header, and the file on disk may have been replaced (e.g. by an app update) since that header was read. The retained handle always sees the bytes the header describes.

POSIX 上替换文件(rename / 原子更新)后,已打开的 fd 仍指向原 inode;Windows 上默认不允许替换被打开的文件,但更新器可以先改名再放新文件。于是结论是:运行中的 Electron 不会因为 asar 被替换就加载到新代码,也不会因为新旧混杂而崩——它继续从旧 inode 读,且 offset/hash 仍与旧 header 对得上。第 20 章讲的 Squirrel / MSIX 更新"必须重启才生效",底层依据就在这里。

spec/asar-integrity.spec.ts:339-386 有一组只在 macOS 跑的用例专门验证这个场景:先构造 app.asar,用 OnlyLoadAppFromAsar + integrity 两个 fuse 启动,再让应用把 app.asar 换成目录或换成另一个 asar,断言子进程不会加载替换后的 child.js(expect(res.out).not.toContain('child-loaded-replacement'))。这条测试把 IsRequiredAppArchive(22.6)与 retained fd 两处机制一起覆盖了。

代价是 GetUnsafeFD() 这个方法名里的 "Unsafe":注释明确说用这个 fd 手工读出来的字节不校验完整性,调用方自己负责。JS 侧的对应绑定叫 getFdAndValidateIntegrityLater(electron_api_asar.cc:99),名字把责任写进了 API——22.4.4 会看到 AsarEntryReader 如何兑现这个"later"。


22.4 asar-fs-wrapper.ts:76-83:2493 行的 fs 重写

22.4.1 splitPath 的两遍扫描与 UTF-16 换算

C++ 侧给了 FindArchivePrefixLength,JS 侧负责在它前后做规范化与切片(asar-fs-wrapper.ts:76-105):

const asarRe = /\.asar/i;
const kNeedsNormalization = -2;

const splitStringPath = (archivePath: string): SplitPathResult => {
  if (!asarRe.test(archivePath)) return NOT_ASAR;
  if (isWindows) archivePath = path.normalize(archivePath);
  let prefixLength = asar.splitPath(archivePath, !isWindows);
  if (prefixLength === kNeedsNormalization) {
    archivePath = path.normalize(archivePath);
    prefixLength = asar.splitPath(archivePath, false);
  }
  if (prefixLength < 0) return NOT_ASAR;
  ...
};

三条要点:

先用正则挡掉 99% 的路径。注释:"Cheap pre-check so the many paths that cannot involve an archive never leave JS"。/\.asar/i 不区分大小写,与 C++ 的 base::EndsWith(..., INSENSITIVE_ASCII) 对齐。

POSIX 与 Windows 的规范化策略相反。Windows 路径总是先 path.normalize()(盘符、混合分隔符),然后以 requireNormalized=false 调 C++;POSIX 只在 C++ 第一遍词法扫描报告 kNeedsNormalization 时才规范化。后者是 22.3.2 提到的 FindArchivePrefixLength 的 Pass 1 纯词法判断(:264-289):只有路径里同时出现 .asar 候选和 ./../空组件时才返回 kNeedsNormalization,避免让常见路径付出 path.normalize() 的代价。

返回值要换算成 UTF-16 长度。electron_api_asar.cc:362-380 的 SplitPath 里:

result = asar::FindArchivePrefixLength(path, require_normalized);
// The caller slices a JS string with this, so report UTF-16 code units.
if (result > 0 && !is_ascii)
  result = Utf16LengthOfUtf8Prefix(path, result);

C++ 的偏移量按 UTF-8 字节算,但 JS 的 String.slice() 按 UTF-16 码元算。含中文的路径里,一个汉字在 UTF-8 是 3 字节、在 UTF-16 是 1 码元,直接拿去切会切错位置。Utf16LengthOfUtf8Prefix(:57-65)遍历前缀,跳过 continuation byte,并把 4 字节序列(emoji / 增补平面)算成 2 个码元(代理对)。这是这一整条链路上最容易被忽略、也最容易在中文路径上出错的一处转换。

WithUtf8Path(:32-55)还做了个零拷贝优化:ASCII 路径直接用 v8::String::ValueView 的 one-byte 视图构造 string_view,不分配;注释说"this sits under every fs call on a packed path"。非 ASCII 才回退到 gin::ConvertFromV8 生成 std::string。

22.4.2 三个 internal binding 与 original-fs 的隔离

文件开头(:20-34)拿的不是公开的 fs,而是 Node 内部对象:

const { internalBinding } = require('internal/bootstrap/realm');
const binding = internalBinding('fs');
const dirBinding = internalBinding('fs_dir');
const uvBinding = internalBinding('uv');
const { kUsePromises } = binding;

uvBinding 的存在只为一件事:createError(:261-323)造出的错误要带 libuv 的 errno,不是 POSIX errno。注释举例:"UV_EACCES is -4092 there, not -13",Node 会按 libuv 的表解码 errno,填错值会显示成莫名其妙的错误码。

cloneBinding(:350-366)解决的是 original-fs:

asar-fs-wrapper.ts:362-365

if (!Object.prototype.hasOwnProperty.call(binding, '_electronOriginalBindings')) {
  Object.defineProperty(binding, '_electronOriginalBindings', {
    value: Object.freeze({ fs: cloneBinding(binding), fs_dir: cloneBinding(dirBinding) }),
    enumerable: false, configurable: false, writable: false
  });
}

original-fs 由 generate_original_fs.py 从与 fs 相同的源码生成,因此默认会共享同一批 binding 对象——下面所有 override 一旦装上,original-fs 也会跟着变成 asar-aware,那它就不"original"了。解决办法是在装 override 之前用 Reflect.ownKeys + getOwnPropertyDescriptor 深克隆一份,挂在不可枚举、不可写、不可配置的属性上,让生成后的模块改从这里取绑定。script/node/ 里的生成器把 internalBinding('fs') 替换成读 _electronOriginalBindings.fs,所以这份快照必须冻结在"任何补丁之前"。

spec/asar.spec.ts:4194-4241 里 original-fs module 那组用例就是在守这条边界:treats .asar as file(itremote)、is available in forked scripts、has the same APIs as fs。

22.4.3 sentinel fd:给原生代码一个必然失败的句柄

openAsarEntry(:845-880)在归档内条目上打开时,返回的 fd 不是归档的 fd:

asar-fs-wrapper.ts:873-878

const archiveFd = archive.getFdAndValidateIntegrityLater();
if (!(archiveFd >= 0)) throw createError(AsarError.INVALID_ARCHIVE, { asarPath, syscall });
if (!withSentinel) return { reader: new AsarEntryReader(-1, archiveFd, info) };
const fd = asar.createSentinelFd();
if (!(fd >= 0)) throw createError(AsarError.TOO_MANY_OPEN, { asarPath, filePath, syscall });
return { reader: new AsarEntryReader(fd, archiveFd, info) };

createSentinelFd(electron_api_asar.cc:303-333)造的是 /dev/null 的只写副本(POSIX O_WRONLY | O_CLOEXEC + F_DUPFD_CLOEXEC;Windows CreateFileW(L"NUL", GENERIC_WRITE, ...) + DuplicateHandle + _open_osfhandle)。注释把设计意图写得非常完整:

The fs wrapper hands one of these out for every open() of a packed entry and keeps the mapping from it to the entry on the JavaScript side, so the descriptor a caller sees is only meaningful through Node's fs module. Code that reads the raw descriptor itself (a native addon, a child's stdio, a socket, ...) fails with EBADF instead of being handed bytes of the archive at the wrong offset, and no handle to the archive itself ever escapes.

换句话说:fd 只是 openAsarFiles 这张 Map 的 key,真正的数据来自 AsarEntryReader 持有的 archiveFd(即 C++ 的 GetUnsafeFD())。把 fd 交给 child_process 的 stdio 或 net.Socket({ fd }),读到的不是归档内容而是 EBADF——这是"响亮地失败"而不是"悄悄给错字节"。

asar-archives.md:133-151 把这条写成了用户可见的限制,但没解释 fd 具体是什么。源码里 O_CLOEXEC / bInheritHandle=FALSE 两处还额外保证了子进程不会继承这个 sentinel,避免编号被误用。

22.4.4 AsarEntryReader、fd 复用与 stale 清理

openAsarFiles(:750-770)的类型定义本身就是一份防御清单:

asar-fs-wrapper.ts:749-752

interface OpenAsarFile {
  reader: AsarEntryReader;
  handle?: WeakRef<{ fd: number }>;
}
const openAsarFiles = new Map<number, OpenAsarFile>();

handle 是 WeakRef,因为 FileHandle 由 Node 的 C++ 对象持有、GC 时才关闭。lookupAsarFd 每次都要 deref() 并同时校验 handle.fd === fd——fd 编号会被操作系统复用,一个陈旧的 Map 条目可能捕获到"后来占用了同一编号的无关文件"的读取,把它的字节当成归档内容返回。

为此有三道清理:

机制位置触发时机
lookupAsarFd 惰性删除:755-768读之前发现 handle 已回收或编号变了
passThroughOpen:789-808任何原生 open 产生新 fd 时,先 forgetStaleAsarFd
sweepStaleAsarFds:811-817全表扫描,处理没有经过 passThroughOpen 的关闭路径

passThroughOpen 还要兼容 Node binding 的三种调用形态:同步(直接返回 fd)、kUsePromises(Promise,.then 里清理)、回调式(劫持 req.oncomplete)。注释解释了为什么加 if (openAsarFiles.size === 0) 短路:"the common case stays a plain pass-through"——没有 asar 句柄时零额外开销。

完整性校验的"later"也在这里兑现。AsarEntryReader 上方那段长注释(:545-565)说明:位置被换算成归档偏移并 clamp 到条目范围,字节只在所属 block 的哈希刚验证通过之后才交出去;reader 保留最近验证过的一个 block,让顺序读(流)每个 block 只付一次读 + 一次哈希,且绝不"从磁盘重读一个 block 却不重新验证"。kMaxRetainedBlocks = 32 是所有 live reader 共享的上限,防止并发打开大量句柄把内存钉死;超过上限仍逐块校验,只是不再保留。

integrityViolation(:486-496)用 v8Util.exitImmediately(1) 而非 process.exit(1),注释给了两条理由:主进程里 process.exit() 被映射成异步优雅退出 app.exit(),JS 会继续跑并消费已被篡改的字节;而 libc 的 exit() 会在 Chromium 线程仍存活时跑静态析构,Windows 上间歇性 0xC0000005。消息用 fs.writeSync(2, ...) 阻塞写,确保退出前不丢。spec/asar-integrity.spec.ts:284 断言的正是输出里含 ASAR Integrity Violation: got a hash mismatch。

22.4.5 18 个字段的假 Stats

asarStatsToFsStats(:160-248)不是自己造一个 fs.Stats 对象,而是伪造 Node binding 会返回的原始数组,再交给 Node 自己的 getStatsFromBinding():

asar-fs-wrapper.ts:200-207

const kStatFields = 18;
const statScratch = new Float64Array(kStatFields);
const bigintStatScratch = new BigInt64Array(kStatFields);
statScratch[0] = 1; // dev
statScratch[2] = 1; // nlink
statScratch[3] = uid;
statScratch[4] = gid;
statScratch[6] = 4096; // blksize
for (let i = 10; i < kStatFields; i += 2) {
  statScratch[i] = fakeTimeSec;
  statScratch[i + 1] = fakeTimeNsec;
}

模块级共享 scratch 数组的技巧是跟 Node 自己的 statValues 学的;fillStatArray 只写 4 个变化字段(mode / ino / size / blocks),返回共享数组,必须被同步消费(getStatsFromBinding 会拷贝出来)。异步路径用 makeStatArray 返回 .slice() 私有副本,因为结果要经 request 对象稍后送达。

伪造值的语义:

字段值后果
dev / nlink恒 1所有归档内文件看起来在同一设备、硬链接数为 1
时间戳fakeTime = new Date() 模块加载时刻整个进程内所有文件的 mtime/ctime/birthtime 完全一致,且等于启动时间
ino++nextInode,每次 stat 递增同一文件 stat 两次得到不同 inode
mode文件 0644 / 可执行 0755 / 目录 0755 / link 0777用字面量而非 fs.constants.S_I*,因为 Windows 没定义 group/other 与执行位常量
blocksMath.ceil(size / 512)按 512 字节单位

asar-archives.md:165-170 只说"不要相信 Stats,除了 size 和文件类型",源码补充了具体哪里假:ino 每次都变意味着任何基于 inode 去重的构建工具(增量编译、缓存、文件监听)在 asar 内文件上会失效;时间戳恒为启动时间意味着 If-Modified-Since 之类的缓存判断每次重启都会变。

22.4.6 overrideAPI 的三条分派路径

overrideAPI / overrideAPISync(:400-473)是所有被包装 API 的模板,它要同时覆盖 Node 的四套调用形态:

asar-fs-wrapper.ts:432-439

module[name] = function (this: any, ...args: any[]) {
  const pathInfo = splitPath(args[pathArgumentIndex]);
  if (!pathInfo.isAsar) return old.apply(this, args);
  const callback = args[args.length - 1];
  if (typeof callback !== 'function') {
    return overrideAPISync(module, name, pathArgumentIndex!, true)!.apply(this, args);
  }
  ...
};
if (old[util.promisify.custom]) {
  module[name][util.promisify.custom] = assignFunctionName(
    name, makePromiseFunction(old[util.promisify.custom], pathArgumentIndex));
}
if (module.promises && module.promises[name]) {
  module.promises[name] = makePromiseFunction(module.promises[name], pathArgumentIndex);
}

三条路径分别是:回调式(拿到 copyFileOut 的路径后 nextTick 调用 old)、同步式(无回调时内联走 overrideAPISync(..., fromAsync=true) 的函数,注意它不写回 module[name])、Promise 式(util.promisify.custom 与 module.promises[name] 各包一次)。

overrideAPISync 的通用策略是把路径参数替换成 archive.copyFileOut() 返回的临时路径,再调原函数。makePromiseFunction 里若 getOrCreateArchive 失败返回 Promise.reject(...) 而不是抛异常,保持 Promise 语义。

这套"替换路径"的策略与 22.4.3 的 AsarEntryReader 是并行的两套机制:fs.readFile(path) 走前者(复制到临时文件),fs.open(path) + fs.read(fd) 走后者(直接从 retained fd 读并逐块校验)。asar-archives.md:152-163 列出的"需要额外解包"的 API(child_process.execFile*、process.dlopen)属于前者;:133-151 列出的 fs.read / createReadStream / FileHandle 属于后者。

最后一条环境开关(:16-17):

asar-fs-wrapper.ts:16-17

const envNoAsar = process.env.ELECTRON_NO_ASAR && process.type !== 'browser' && process.type !== 'renderer';
const isAsarDisabled = () => process.noAsar || envNoAsar;

ELECTRON_NO_ASAR 只在 process.type 既不是 browser 也不是 renderer 时生效——也就是 utility process、child_process(Node 模式)这类。主进程与渲染进程设了这个环境变量不会禁用 asar。文档 asar-archives.md:93-113 讲 process.noAsar 与 ELECTRON_NO_ASAR 时没写这个限定,这是在 CI 或子进程里配置时最容易踩的一条。

22.4.7 override 清单、访问日志与递归 readdir 的 link 环

wrapFsWithAsar(:882)从 lstatSync 开始,把 fs 的公开 API 逐个重写。有意思的是 overrideAPI / overrideAPISync 这两个通用模板在文件末尾只被调用四次(:2451-2468):

asar-fs-wrapper.ts:2451-2454

// Native modules and child processes need a real file on disk, so these
// are the only remaining consumers of Archive::CopyFileOut.
overrideAPISync(process, 'dlopen', 1);
overrideAPISync(Module._extensions, '.node', 1);
overrideAPI(childProcess, 'execFile');
overrideAPISync(childProcess, 'execFileSync');

源码注释点明了原因:只有原生模块加载与 execFile* 还需要真实磁盘文件,fs 主路径早已改走 AsarEntryReader(22.4.4)。旁边的 overrideChildProcess(:2454-2470)把 exec / execSync 用 invokeWithNoAsar(...) 包起来而不是套模板,因为命令字符串里若含 asar 路径,execFile 的内部调用会把整条命令当成一个归档路径;注释还说明不能用 Module._load 懒加载,那样会拖累每次 require() 且永远走不到 import ... from 'node:child_process'。

也就是说 fs.stat、fs.readFile、fs.open、fs.copyFile、fs.createReadStream、fs.promises.* 这些全部是手写的,每个都要单独处理参数位置、回调形态、throwIfNoEntry、BigInt stat、encoding 等细节。这正是这个文件长达 2493 行的原因:通用模板只适合"把路径换成临时文件路径再调原函数"这一类,而 fs 的绝大多数 API 需要更精细的行为。

shouldThrowStatError(:897-903)是其中一个典型:Node 的 fs.statSync(path, { throwIfNoEntry: false }) 在找不到时应返回 undefined,包装层必须复刻这个语义,否则 fs.existsSync()(内部就用这个选项)会把 asar 内不存在的文件判成崩溃。

statTypeForReaddir(:912-922)的注释值得单独抄下来:

Unlike internalModuleStat itself, symbolic links inside archives are not followed: recursive readdir descends into whatever this reports as a directory, and archives may legitimately contain link cycles (a real filesystem walk would only be stopped by ENAMETOOLONG).

真实文件系统里符号链接环最终会被 ENAMETOOLONG(路径长度上限)拦住,但 asar 的 link 只是 JSON 字符串,路径长度不会增长,递归 readdir 会无限下降。所以包装层的递归版本明确不跟随归档内 link。这与 22.3.2 的 kMaxLinkDepth = 40 是两处独立的防环机制,分别管 C++ 查找与 JS 递归遍历。

最后是一个几乎没人用的诊断开关(:883-896):

asar-fs-wrapper.ts:887-894

// Read once at startup (set it in the environment that launches the app):
// process.env goes through node's env interceptor and this is consulted on
// every read of a packed file.
const logAsarReads = Boolean(process.env.ELECTRON_LOG_ASAR_READS);
const logASARAccess = (asarPath, filePath, offset) => {
  if (!logAsarReads) return;
  if (!logFDs.has(asarPath)) {
    const logFilename = `${path.basename(asarPath, '.asar')}-access-log.txt`;
    const logPath = path.join((require('os') as typeof os).tmpdir(), logFilename);
    logFDs.set(asarPath, fs.openSync(logPath, 'a'));
  }
  fs.writeSync(logFDs.get(asarPath), `${offset}: ${filePath}\n`);
};

设 ELECTRON_LOG_ASAR_READS=1 后,每次读取归档内文件都会往 os.tmpdir()/<asar名>-access-log.txt 追加一行 <offset>: <path>;调用点只有两处(:1316、:1379)。注释强调"read once at startup",因为 process.env 在 Electron 里走 Node 的 env interceptor,每次读都有额外成本,而这个判断位于每次归档读的热路径上。

这份日志的实际用途是排查启动性能:把应用启动阶段实际读到的 asar 条目按 offset 排序,就能看出 @electron/asar 的 ordering 参数该怎么写(把启动期文件排到归档前部以减少随机 IO)。文档 asar-archives.md 没提这个环境变量,仓库里也只有这五处引用。


22.5 ASAR Integrity:信任锚必须放在归档之外

22.5.1 为什么校验信息不能只写在 asar 里

asar-integrity.md:40-43 给出的 header 结构是:

{
  "algorithm": "SHA256",
  "hash": "...",
  "blockSize": 1024,
  "blocks": ["...", "..."]
}

hash 是整个文件内容的 SHA256,blocks 是每 blockSize 字节一块的 SHA256 数组。两者都在 header 里,而 header 又是 asar 文件的一部分。如果只靠这两项,改文件的人可以同步改 header——自校验等于没有校验。

所以真正的信任锚必须来自归档之外、且被 OS 签名覆盖的地方:

平台信任锚由谁保护
macOSInfo.plist 的 ElectronAsarIntegrity 字典,值是 header 字符串的 SHA256bundle 代码签名
WindowsPE 资源 Integrity / ElectronAsar,值是 JSON 数组、含 header SHA256Authenticode 签名

也就是说:OS 签名保护 plist/资源 → 其中的 header hash 保护 header → header 里的 per-file hash 保护内容。三级链。第 20 章讲 const volatile kFuseWire 时说过"fuse 的保护实际来自 OS 代码签名",这里是同一个结论的第二次出现,只不过被保护对象换成了 plist 与 PE 资源。

asar-integrity.md 明确要求 @electron/asar >= 3.1.0(后迁到 @electron/asar)才会写出 integrity 字段,并指出 @electron/packager >= 18.3.1 / @electron/forge >= 7.4.0 会自动完成这套配置。换句话说,Electron 本体不负责生成应用的 app.asar,也不负责写这两个信任锚——它只负责在运行时读。仓库里唯一的 asar 构建目标是 default_app_asar(22.1.4),那是为了让未打包的 Electron 有个可运行的默认页面。

22.5.2 macOS:Info.plist 与一个 fail-open 的 digest slot

archive_mac.mm:42-49 的 HeaderIntegrity() 从主 bundle 读:

NSDictionary* integrity = [electron::MainApplicationBundle()
    objectForInfoDictionaryKey:@"ElectronAsarIntegrity"];
if (!IsIntegrityDictionaryValid(integrity))
  return std::nullopt;
if (!integrity)
  return std::nullopt;
NSString* ns_relative_path =
    base::apple::FilePathToNSString(relative_path.value());
NSDictionary* integrity_payload = [integrity objectForKey:ns_relative_path];
if (!integrity_payload)
  return std::nullopt;

两个细节:

MainApplicationBundle() 而不是 MainBundlePath()。RelativePath() 的注释写明"in a helper process that is the helper's own bundle, which holds no archives"——helper 进程(renderer、GPU、utility)的主 bundle 是 helper 自己的 .app,里面没有 asar。必须用外层应用 bundle 的 Contents/ 作为基准,才能算出 Resources/app.asar 这个 key。

缺 key 就返回 nullopt,进而在 Init() 里 LOG(FATAL)。archive.cc:278-282 把 HeaderIntegrity() 返回空值判成 "Failed to get integrity for validatable asar archive"。所以开了 fuse 却没在 plist 里登记某个 asar,那个 asar 一被打开进程就退出——包括 default_app.asar。BUILD.gn:1572-1575 的 asar_hashed_info_plist("electron_app_plist") 就是为官方构建预置这个 key:shell/browser/resources/mac/Info.plist:59-66 里有 Resources/default_app.asar 的 SHA256 + ${DEFAULT_APP_ASAR_HEADER_SHA} 替换标记。

IsIntegrityDictionaryValid(integrity_digest.mm:23-27,2025 年新增)是第二个信任锚,机制与第 20 章的 fuse wire 几乎一样:

constexpr char kIntegrityDictionaryDigestSentinel[] =
    "AGbevlPCksUGKNL8TSn7wGmJEuJsXb2A";

__attribute__((section("__DATA_CONST,__asar_integrity"), used))
const volatile IntegrityDictionaryDigestSlot kIntegrityDictionaryDigest =
    MakeDigestSlot(kIntegrityDictionaryDigestSentinel);

slot 布局是 32 字节 sentinel + used + version + 32 字节 digest,落在 Mach-O 的 __DATA_CONST,__asar_integrity 段,打包期由 @electron/packager 之类的工具定位并翻转。校验逻辑(:56-82):

integrity_digest.mm:48-51

if (kIntegrityDictionaryDigest.used == false)
  return true;  // No digest to validate against, fail open
if (kIntegrityDictionaryDigest.version != 1)
  return false;  // Unknown version, fail closed

used == false 时 fail open(返回 true),version != 1 时 fail closed。这是与 fuse 机制相反的默认策略:没启用就完全不拦;一旦启用但版本不认识,宁可拒绝。哈希的计算方式是把 plist 字典的 key 按 NSLiteralSearch 排序,然后依次把 relative_path_key、algorithm、hash 三段 UTF-8 喂进 SHA256——不含 blockSize / blocks,因为这两个字段在 plist 的 header 级配置里本来就不存在(文档给的 plist 示例只有 algorithm 与 hash)。

used/version 由 MakeDigestSlot 在编译期设为 false / 0,注释写着 "to be set at package-time"。这是第 20 章 fuse wire 的 Mach-O 版本:同样是 const volatile 防止常量折叠,同样是靠固定 sentinel 在二进制里定位。区别是 fuse 的 wire 由 build.py 在 Electron 自己的构建里生成,而这个 slot 由应用打包工具在分发前填充。

22.5.3 Windows:PE 资源与一条全是 FATAL 的解析链

archive_win.cc:25-26 把信任锚放在 PE 资源里:

const wchar_t kIntegrityCheckResourceType[] = L"Integrity";
const wchar_t kIntegrityCheckResourceItem[] = L"ElectronAsar";

RelativePath() 用 base::DIR_ASSETS 算相对路径(通常得到 resources\app.asar)。LoadIntegrityConfig() 从 GetModuleHandle(nullptr)(当前 exe)里 FindResource / LoadResource / LockResource 取出资源字节,按 JSON 解析。文档给的格式是:

[
  { "file": "resources\\app.asar", "alg": "sha256", "value": "9d1f..." }
]

与 mac 的差异有四处:

维度macOSWindows
容器Info.plist 字典PE 资源 Integrity/ElectronAsar
结构字典,key 是正斜杠相对路径数组,每项含 file 字段
算法字段algorithmalg(大小写不敏感)
hash 字段hashvalue
key 归一化精确匹配 Resources/app.asarbase::ToLowerASCII 后匹配

解析链里几乎每一步都是 LOG(FATAL):FindResource 失败、LoadResource 失败、LockResource 返回空、res_size == 0、JSON 不是合法值、根不是 list——这六种情况直接终止进程。只有数组内单项格式不合法时才降级为 LOG(WARNING) + continue(跳过该项),这会让对应的 asar 在后续 HeaderIntegrity() 里查不到,再触发一次 FATAL。

HeaderIntegrity() 末尾也有一句 LOG(FATAL) << "Failed to find file integrity info for " << key;(不是返回 nullopt),与 mac 的返回 nullopt 形成对照——两边最终都在 Archive::Init 里被判成失败,但 Windows 的报错信息更直接。

GetIntegrityConfigCache() 用 base::NoDestructor 包住一次性解析结果:LoadIntegrityConfig() 只在第一次打开 asar 时执行,之后所有归档共用这份 map。这解释了 spec/asar-integrity.spec.ts:160-172 为什么用 resedit(appPath, { asarIntegrity: ... }) 在启动前写入资源,且注释强调 "This has to happen before the fuses are flipped, which re-signs the app"——改 PE 资源会破坏 Authenticode 签名,必须在重签之前做。

22.5.4 per-file integrity:字段缺失也是 FATAL

header_validated_ 置位后,FillFileInfoWithNode(archive.cc:143-176)对每个文件条目强制执行:

if (load_integrity &&
    electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled()) {
  if (const base::DictValue* integrity = node->FindDict("integrity")) {
    const std::string* algorithm = integrity->FindString("algorithm");
    const std::string* hash = integrity->FindString("hash");
    std::optional<int> block_size = integrity->FindInt("blockSize");
    const base::ListValue* blocks = integrity->FindList("blocks");
    if (algorithm && hash && block_size && block_size > 0 && blocks) {
      ...
      for (auto& value : *blocks) {
        if (const std::string* block = value.GetIfString()) {
          integrity_payload.blocks.push_back(*block);
        } else {
          LOG(FATAL) << "Invalid block integrity value for file in ASAR archive";
        }
      }
      if (*algorithm == "SHA256") {
        integrity_payload.algorithm = HashAlgorithm::kSHA256;
        info->integrity = std::move(integrity_payload);
      }
    }
  }
  if (!info->integrity.has_value()) {
    LOG(FATAL) << "Failed to read integrity for file in ASAR archive";
  }
}

四个必须同时满足的条件:algorithm、hash、blockSize > 0、blocks 是数组。任何一项不满足,最后那个 if (!info->integrity.has_value()) 都会 FATAL。特别注意 algorithm 只认字面量 "SHA256":写成小写 sha256 或 "SHA-256" 时,前面的字段都读到了,但 info->integrity 始终没被赋值,依然 FATAL。这是"静默失败"最隐蔽的一种——错误信息是 "Failed to read integrity",看起来像缺字段,实际是算法名不匹配。

block_size 用 FindInt(int32),超过 2³¹ 的块大小会被拒绝;blocks 里只要有一个元素不是字符串就 FATAL。HashAlgorithm 枚举只有 kSHA256 与 kNone 两个值,kNone 只在未启用校验时使用。

还有一条短路值得回头看:info->unpacked 为真时 :117-122 直接 return true,这段 integrity 检查根本不会执行。所以 asarUnpack 出来的文件在开了 fuse 的应用里是完全不受校验的,这与 22.1.2 的结论一致,但这里的影响更严重:不是"读不到 hash",而是"连 header 都不要求有 hash"。

22.5.5 ValidateIntegrityOrDie 的四个调用点

asar_util.cc:350-364 是唯一的全量校验函数:

void ValidateIntegrityOrDie(base::span<const uint8_t> input,
                            const IntegrityPayload& integrity,
                            std::string_view what) {
  if (integrity.algorithm == HashAlgorithm::kSHA256) {
    const std::string hex_hash =
        base::ToLowerASCII(base::HexEncode(crypto::hash::Sha256(input)));
    if (integrity.hash != hex_hash) {
      LOG(FATAL) << "Integrity check failed for asar archive entry '" << what
                 << "' (" << integrity.hash << " vs " << hex_hash << ", "
                 << input.size() << " bytes)";
    }
  } else {
    LOG(FATAL) << "Unsupported hashing algorithm in ValidateIntegrityOrDie";
  }
}
调用点输入校验对象
Archive::Init :288header 字符串字节与 plist/PE 里的 header hash 比对
ReadFileToString :344整文件内容info.integrity.hash(全文件哈希)
ScopedTemporaryFile::InitFromFile :57拷出的字节<copied-out entry>,用同一个 info.integrity
JS 层 validateBufferIntegrity asar-fs-wrapper.ts:507fs.readFile 的 Bufferintegrity.hash,失败走 exitImmediately(1)

后三个用的是 integrity.hash(整个文件的哈希),不是 blocks。分块哈希只在流式路径里用(22.5.6)。也就是说 fs.readFileSync 读一个 100 MB 的归档内文件,会先整块读进内存、再整块算一次 SHA256 才返回;而 createReadStream 是逐块校验、边校验边给字节。同一份数据两种校验粒度,行为差异在 22.5.7 的测试里被明确覆盖。

crypto 模块在 JS 层是延迟加载的(:476-479 的 getCrypto()),注释写明 "Delay load crypto to improve app boot performance when integrity protection is not enabled"。异步路径用 webcrypto.subtle.digest 把哈希挪出 JS 线程(:501-504),同步路径只能用 createHash。

22.5.6 流式分块校验与"被跳过的字节"

AsarFileValidator(asar_file_validator.cc:97-104,146 行)挂在 file:// / asar URL 加载路径上,处理 Range 请求和流。OnRead 把每次读到的字节按 block_size 切块喂给 hasher,块满即 FinishBlock() 与 integrity_.blocks[current_block_] 比对,不符则 LOG(FATAL)。

最难的一段是 FinishBlock() 里对跳过的区间补读(:104-124):

asar_file_validator.cc:97-104

// If the file reader is done we need to make sure we've either read up to the
// end of the file (the check below) or up to the end of a block_size byte
// boundary. If the below check fails we compute the next block boundary, how
// many bytes are needed to get there and then we manually read those bytes
// from our own file handle ensuring the data producer is unaware but we can
// validate the hash still.
if (done_reading_ &&
    total_hash_byte_count_ - extra_read_ != read_max_ - read_start_) {
  uint64_t bytes_needed = std::min(
      integrity_.block_size - current_hash_byte_count_,
      read_max_ - read_start_ - total_hash_byte_count_ + extra_read_);
  uint64_t offset = read_start_ + total_hash_byte_count_ - extra_read_;
  std::vector<uint8_t> abandoned_buffer(bytes_needed);
  if (!file_.ReadAndCheck(offset, abandoned_buffer)) {
    LOG(FATAL) << "Failed to read required portion of streamed ASAR archive";
  }
  current_hash_->Update(abandoned_buffer);
}

原因:HTTP Range 请求只发送文件的一段,但每个 block 的哈希覆盖完整 blockSize 字节。要验证"已发送的字节所在块"未被篡改,就必须把该块里客户端没要的其余字节也读出来喂进哈希——否则攻击者改一个块中未被请求的部分,哈希对不上但无法区分是"没读到"还是"被改了"。abandoned_buffer 这个名字就是"读了就扔"的意思;extra_read_、read_start_、read_max_ 由 SetRange() 从 URL loader 传入,SetCurrentBlock() 处理从中间块开始的 Range。

asar_url_loader.cc:280-312 展示了它如何被装配:

// Each request needs its own |base::File| as multiple requests may be
// streaming at the same time, but for packed files it must be a duplicate
// of the |Archive|'s retained handle rather than a fresh open by path:
// |info|'s offset and block hashes come from the cached header, and the
// archive on disk may have been replaced (e.g. by an app update) since
// that header was read.
base::File file = info.unpacked
                      ? base::File(real_path, ...)
                      : archive->DuplicateFile();
base::File validator_file;
if (info.integrity.has_value())
  validator_file = file.Duplicate();
...
readable_data_source = std::make_unique<mojo::FilteredDataSource>(
    std::move(file_data_source), std::move(asar_validator));

每个请求一个独立的 base::File(DuplicateFile(),与 retained handle 指向同一底层文件),validator 再复制一份,因为它要读"被跳过的字节",与 data source 的读位置互不干扰。mojo::FilteredDataSource 把 validator 的 OnRead 插在数据源与 data pipe 之间,因此字节在写进 pipe 之前就已经校验过了——测试里 "no byte from the corrupted block was ever delivered" 就是靠这个顺序保证的。

22.5.7 测试覆盖矩阵比文档更精确

spec/asar-integrity.spec.ts 412 行,只在 (win32 && arch !== 'arm64') || darwin 上跑(:142),每个 beforeEach 超时 120 秒(要复制并重新签名一个完整的 app bundle)。describe('when enabled') 下的用例把 22.5 的所有分支都覆盖到了:

用例验证的机制
opens normally when unmodified全链路放行
fatals if the integrity header does not matchArchive::Init 的 header 校验
fatals if a loaded main process JS file does not matchReadFileToString
fatals if a renderer content file does not matchAsarURLLoader 路径
serves unmodified files through fs.open-style APIsAsarEntryReader
fatals if a file read through fs.open-style APIs does not matchJS 层 validateBufferIntegrity
terminates a stream when it reaches corrupted block N流式分块,且前面块已送达
still serves ranges that only touch intact blocks when a later block is corruptedabandoned_buffer 补读的正确性边界
fatals whole-file reads of an entry with a corrupted block全量 hash 与分块 hash 的差别
detects a block that is corrupted in place after it was already read oncereader 不缓存已校验 block 的旧字节
does not load a child process from a directory / from a modified archiveOnlyLoadAppFromAsar + retained fd(仅 darwin)
when disabled / does nothing if the integrity header does not matchfuse 关闭时完全跳过

"仍然可以只取未损坏块"这条尤其反直觉:一个文件被篡改了,某些 Range 请求仍然成功。这不是漏洞——被返回的字节确实通过了该块的哈希;但排查问题时如果只看到"页面能加载",不能据此推断文件完好。


22.6 OnlyLoadAppFromAsar:不看磁盘的判定

app_package.cc:88-100:

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")};
}
for (const auto& candidate : candidates) {
  base::FilePath path = resources.Append(candidate);
  if (only_asar && !asar::GetOrCreateAsarArchive(path))
    continue;
  std::string json;
  if (!asar::ReadFileToString(path.Append(FILE_PATH_LITERAL("package.json")),
                              &json)) {
    continue;
  }

fuse 开启后候选列表只剩一个名字,且多了一道 GetOrCreateAsarArchive(path) 检查——目录冒名 app.asar 也过不了(打不开成归档)。

但真正精巧的是 asar_util.cc:48-66 的 IsRequiredAppArchive:

// 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([] {
        const base::FilePath resources = electron::GetResourcesPath();
        const base::FilePath name(FILE_PATH_LITERAL("app.asar"));
        return std::make_pair(
            resources.Append(name),
            base::MakeAbsoluteFilePath(resources).Append(name));
      }());
  return path == s_paths->first || path == s_paths->second;
}

"Decided without looking at the disk, so that every process agrees"是核心。这个函数在 IsDirectoryCached 里被先于 GetFileInfo 调用(:84-88):只要路径等于 resources/app.asar(两种拼写:原样与绝对化后的),就无条件返回"不是目录",并且不写缓存。于是:

  • 主进程、renderer、utility、子进程对同一个路径得出相同结论,不受各自启动时磁盘状态影响;
  • 攻击者在应用启动后把 app.asar 换成同名目录,GetAsarArchivePath 仍把它当归档,走 Archive::Init 打开文件失败,而不是回退成读目录里的明文 JS;
  • spec/asar-integrity.spec.ts:374-386 的两个用例验证的正是这一点。

这一层与 22.3.4 的 DirectoryCache 钉死、22.3.5 的 retained fd 构成三道互补防线:IsRequiredAppArchive 防"路径语义被换",DirectoryCache 防"已打开的归档被目录顶替",retained fd 防"文件被原子替换后新旧字节混读"。

fuses.md:96-106 列出了开启该 fuse 时 Electron 只搜索 app.asar(并顺带提到 default_app.asar),与代码一致;但没有说明"不看磁盘"这条实现策略,也没说明它和 integrity fuse 的组合会同时挡住"替换成目录"与"替换成篡改过的归档"。


22.7 URL 侧:替换 file:// 工厂与 IO 线程

22.7.1 一处替换,两条入口

第 17 章讲过 ProtocolRegistry::RegisterURLLoaderFactories 会用 asar 工厂替换 Chromium 的 file:// 工厂,这里从打包侧补上完整条件(protocol_registry.cc:26-46):

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 开启(默认 1)、Chromium 是否已经给了 file 工厂、以及 allow_file_access。grant_file_protocol_extra_privileges 关掉,asar 内的 <img src>、<script src>、<video src> 全部失效——这正是第 20 章说的"关掉会白屏"。

注释里还有一条对上游的防御说明:Chromium 可能在这之后 emplace 默认 file 工厂,"it won't override our asar factory",但要求未来 asar 支持出问题时先检查 Chromium 是否改了这个调用。这是把上游行为当外部契约来守。

导航走的是另一条入口 CreateNonNetworkNavigationURLLoaderFactory(scheme)(:50-60),file:// 且 fuse 开启时同样返回 asar 工厂。两条入口分别对应子资源与导航,缺一条就会出现"页面能打开但资源全挂"或反过来。

22.7.2 AsarURLLoaderFactory 的生命周期与 pipe 尺寸

asar_url_loader_factory.cc:28-35 只有 57 行,两个要点:

// static
mojo::PendingRemote<network::mojom::URLLoaderFactory>
AsarURLLoaderFactory::Create() {
  mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
  content::GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&BindOnIOThread,
                     pending_remote.InitWithNewPipeAndPassReceiver()));
  return pending_remote;
}

工厂绑定在 IO 线程而非创建它的 UI 线程,注释理由是"all it does is post loaders to the thread pool"。base::MakeSelfDeleting 让它随最后一个 receiver 断开而析构,代码尾部那行 // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) 是给静态分析器看的——自删对象在扫描器眼里就是泄漏。

CreateLoaderAndStart 无条件传 new net::HttpResponseHeaders("") 作为额外响应头,即空头,具体 MIME、Content-Length、Content-Range 全由 AsarURLLoader::CreateAndStart 自己填。

ResponsePipeSize(asar_url_loader.cc:60-69):

uint32_t ResponsePipeSize(uint64_t body_size) {
  return base::saturated_cast<uint32_t>(std::clamp<uint64_t>(
      body_size, net::kMaxBytesToSniff,
      network::GetDataPipeDefaultAllocationSize(
          network::DataPipeAllocationSize::kLargerSizeIfPossible)));
}

下界是 MIME 嗅探缓冲(初始读要一次写进 pipe),上界是 Chromium 的大尺寸默认 pipe,中间取 body 自身大小。注释说明动机:"small files do not pay for a 2 MB shared buffer and large ones are not fed through in 64 KB slices"。

IsUnder(:56-58)在三个位置被调用(:166、:185、:194),检查解析出的真实路径是否仍在允许的 root 之下——防的是 file:///app.asar/../../etc/passwd 这类路径穿越。这与第 17 章 registerSource 的 real_root confinement 是同一类防护,只不过这里在 URL loader 里手工做。

HEAD 请求走 RespondWithoutBody(:260-269),不创建 data pipe、不读文件,但仍会填 Content-Length 与 Content-Type。这意味着开了 integrity fuse 时,对一个损坏的归档内文件发 HEAD 请求不会触发校验——校验发生在 OnRead,没有读就没有校验。排查"文件坏了但某些请求正常"时要记住这条。

22.7.3 AsarURLLoader::Start 的完整状态机

asar_url_loader.cc:130-455 是这一章里最长的一段单一函数,把它按分支拆开,能看清 asar 在 URL 侧到底替 Chromium 做了多少事。

入口三分路(:130-150):

asar_url_loader.cc:131-138

base::FilePath path;
if (!net::FileURLToFilePath(request.url, &path)) {
  ... OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
  MaybeDeleteSelf();
  return;
}
const bool in_archive = GetAsarArchivePath(path, &asar_path, &relative_path);
if (!in_archive && root.empty()) {
  content::CreateFileURLLoaderBypassingSecurityChecks(
      request, std::move(loader), std::move(client), nullptr, false,
      extra_response_headers);
  MaybeDeleteSelf();
  return;
}

root 为空表示"这是普通 file:// 请求",不在归档就直接交回 Chromium 原生 file loader,自己销毁。root 非空时(例如 protocol.registerSource 复用了 asar loader,见第 17 章)必须自行处理,因为要做 confinement。这解释了为什么 grant_file_protocol_extra_privileges 打开后普通文件访问性能几乎不变——绝大多数请求走的是原生实现,asar loader 只在路径里有 .asar 时才真正工作。

路径穿越的三道 IsUnder(:162-200):

asar_url_loader.cc:164-167

if (!root.empty() &&
    (!base::NormalizeFilePath(asar_path, &real_archive) ||
     !IsUnder(real_archive.Append(relative_path), root))) {
  OnClientComplete(net::ERR_FILE_NOT_FOUND); return;
}

NormalizeFilePath 会解析符号链接拿到真实路径,防止用软链接绕过 root。unpacked 条目更绕:CopyFileOut() 给出临时/真实文件路径后,还要用 real_archive.AddExtension("unpacked").AppendRelativePath(real_path, &logical) 把真实路径反算成归档内的逻辑路径,再判 IsUnder(logical, root)。因为临时文件在 os.tmpdir()(22.4.7 可配日志目录,但 CopyFileOut 用的是 CreateTemporaryFile),直接判真实路径必然不在 root 下。

非归档的普通文件分支(:187-199)同样要 NormalizeFilePath + IsUnder + GetFileInfo,并显式拒绝 file_info.is_directory 和负 size。

Range 只支持单区间(:204-250):

asar_url_loader.cc:215-220

if (net::HttpUtil::ParseRangeHeader(range_header.value(), &ranges) &&
    ranges.size() == 1) {
  byte_range = ranges[0];
  if (!byte_range.ComputeBounds(file_size)) fail = true;
} else {
  fail = true;
}

Range: bytes=0-99,200-299 这类多区间请求直接 416,没有 multipart/byteranges 支持。失败时若已有 head->headers(正常路径)就 ReplaceStatusLine("HTTP/1.1 416 Range Not Satisfiable") + Content-Range: bytes */<size> + RespondWithoutBody,否则回 ERR_REQUEST_RANGE_NOT_SATISFIABLE。成功则改成 206 并填 Content-Range: bytes <first>-<last>/<size>。

MIME 的两级判定(:364-375):先 net::GetMimeTypeFromFile(path, ...) 按扩展名查;失败才用首次读入的 kMaxBytesToSniff 字节调 net::SniffMimeType,且传 ForceSniffFileUrlsForHtml::kDisabled(不因为文件 URL 就强制嗅探成 HTML)。注意 path 是归档内逻辑路径,扩展名来自它——第 17 章提过 GetMimeTypeFromFile 对 .asar 内路径不可靠,这里正是补上嗅探兜底的原因。

两次"读了就扔"的补读。第一处(:345-362)处理 Range 起点越过首块的情况:

asar_url_loader.cc:348-354

} else if (is_verifying_file &&
           first_byte_to_send >= static_cast<uint64_t>(block_size)) {
  // ... we need to read the next 4MB-1KB to validate that block.
  uint64_t bytes_to_drop = block_size - net::kMaxBytesToSniff;
  total_bytes_dropped_from_head += bytes_to_drop;
  std::vector<char> abandoned_buffer(bytes_to_drop);
  auto abandon_read_result = readable_data_source.get()->Read(
      info.offset + net::kMaxBytesToSniff, base::span<char>(abandoned_buffer));

注释里的 "4MB" 与 22.1.6 从 spec 里读到的 kIntegrityBlockSize = 4 * 1024 * 1024 对得上。第二处(:389-425)按 start_block = first_byte_to_send / block_size 分两种情况:start_block == 0 时补 first_byte_to_send - kMaxBytesToSniff(嗅探已读过的部分到 Range 起点之间),否则补 first_byte_to_send - (start_block * block_size)(目标块内起点之前的字节)。两者都通过 SetCurrentBlock(start_block) 让 validator 从正确的块号开始比对。

最后两个 SetRange 的参数含义不同(:432-441):

asar_url_loader.cc:435-441

file_data_source_raw->SetRange(
    first_byte_to_send + info.offset,
    first_byte_to_send + info.offset + total_bytes_to_send);
if (file_validator_raw)
  file_validator_raw->SetRange(info.offset + first_byte_to_send,
                               total_bytes_dropped_from_head,
                               info.offset + file_size);

数据源拿到的是 [起点, 终点) 的绝对归档偏移;validator 拿到的是 (read_start_, extra_read_, read_max_),其中第二参是所有被丢弃字节的累计值——22.5.6 的 FinishBlock() 里 total_hash_byte_count_ - extra_read_ != read_max_ - read_start_ 这个判据,就是靠这三个数还原"实际应该哈希到哪"的。total_bytes_to_send == 0 的提前返回分支(:378-387)也照样调 SetRange,注释写明是为了"validate the tiny amount of data we did send"。

把这一节与 22.5.6 合起来看,AsarFileValidator 那些看似冗余的 abandoned_buffer 逻辑并不是防御性编程,而是Range 请求 + 分块哈希 + MIME 嗅探三者共用一个读缓冲必然产生的记账问题:嗅探读了块首、Range 跳到了块中、data source 只读请求区间,validator 必须自己把缺口补齐才能算出一个完整块的哈希。


22.8 dist.zip:从 GN 依赖闭包到可下载压缩包

22.8.1 dist_zip 模板的两个 target 与一条注释

BUILD.gn:1859-1895 的 dist_zip 模板生成两个 GN target:

template("dist_zip") {
  _runtime_deps_target = "${target_name}__deps"
  _runtime_deps_file =
      "$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" +
      get_label_info(target_name, "name") + ".runtime_deps"

  group(_runtime_deps_target) {
    forward_variables_from(invoker, ["deps", "data_deps", "data", "testonly"])
    write_runtime_deps = _runtime_deps_file
  }

  action(target_name) {
    script = "//electron/build/zip.py"
    deps = [ ":$_runtime_deps_target" ]
    ...
    args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [
             target_cpu, target_os, "$flatten", "$flatten_relative_to",
           ];
  }
}

第一个 group 什么都不构建,唯一职责是让 GN 把依赖闭包写进 .runtime_deps 文件;第二个 action 拿这份清单调 build/zip.py。分成两个 target 是为了让 write_runtime_deps 的输出成为 action 的显式输入,GN 才能正确排序。

electron_dist_zip 的 data_deps(:1919-1945)包含 electron_app、electron_version_file、licenses,Linux 官方构建额外加五个 strip target 与 chrome_sandbox。最后那段注释把一处易错点写得很明白:

if (electron_use_resource_allowlist) {
  # Build-order dep only (not data_deps): the check must pass before the
  # dist zip is created, but its stamp output must not be packed into the
  # zip's runtime deps.
  deps += [ ":electron_resource_allowlist_check" ];
}

resource_allowlist_check 的 stamp 文件如果进了 data_deps,就会被 GN 写进 runtime_deps、被 Python 打进 zip。用 deps 而非 data_deps 是 GN 里区分"构建顺序依赖"与"运行时数据依赖"的标准手法,第 21 章的 deps/data_deps 在测试里也出现过,但这里第一次直接关系到用户下载到的文件内容。

顺带一提 electron_use_resource_allowlist 本身(:1120):只在 enable_resource_allowlist_generation && (is_linux || is_mac) 时开,它从链接输入里抽 ui::AllowlistedResource<id> 标记,只为实际被引用到的字符串重打包 .pak。注释里写着 "on Windows this should extract from electron.exe.pdb instead of the inputs pseudo-link",与 22.9 的 PDB 提取是同一条线索。

22.8.2 runtime_deps 是闭包,不是手写清单

zip.py:98-103:

dist_zip, runtime_deps, target_cpu, _, flatten_val, flatten_relative_to = argv
dist_files = set()
with open(runtime_deps) as f:
  for dep in f.readlines():
    dep = dep.strip()
    if not skip_path(dep, dist_zip, target_cpu):
      dist_files.add(dep)

set 去重很关键:多个 target 会声明同一个共享库或 .pak。GN 的 write_runtime_deps 输出的是相对构建目录的路径列表,包括二进制、resources/、locale pak、swiftshader、crashpad handler 等所有被标记成运行时数据的东西。所以 dist.zip 的内容不是谁手写的一份文件表——加一个 data_deps 就会自动多一个文件,删一个 data 就可能静默少一个文件。

这也解释了为什么第 21 章的 L5 测试要拿真实构建产物去跑:只有产物本身能回答"该带的带了没有"。

22.8.3 EXTENSIONS_TO_SKIP 与 PATHS_TO_SKIP 逐项

zip.py:8-50 的两张排除表是多年积累的产物,每一项都对应一个具体原因:

排除项原因(源码注释)
.pdb符号单独打 pdb.zip
.mojom.js / .mojom-lite.jsMojo 生成的 JS,运行时不需要
.info / .m.js构建中间产物
dbgcore.dll / dbghelp.dll / msdia140.dll只给 Chromium 测试用;不 ship dbghelp 就不需要 msdia140(它是 dbghelp 动态加载来符号化堆栈的)
angledata//ui/gl 的输出,不需要
./crashpad_wer.dllelectron_wer 会以 <exe名>_wer.dll 另发(第 20 章 WER helper)
./libEGL / ./libGLESv2ANGLE 静态链接,这两个是给 Chromium bot 基础设施的空壳
./libVkICD_mock_ / ./VkICD_mock_不需要的输出
Electron.dSYMcreate_bundle 的输出,符号另有压缩包
gen/angle/angle_commit.h上游遗留(注释给了 crbug 链接)
pyprotochrome/browser:resources 的传递依赖
resources/inspector + 四个 gen/third_party/...DevTools 前端、协议类型、bidi、webui 生成物
debugscript/zip-symbols.py:67 单独打(22.9.5)

skip_path()(:52-79)还有三条条件式排除:

  • arm + mksnapshot.zip + snapshot_blob.bin:arm/arm64 的 mksnapshot 在 x64 机器上构建,不生成这个 blob,消费者自己用 mksnapshot 生成;
  • xcache.zip + snapshot_blob.bin:electron_xcache 虽链接 V8,但总是被喂 target 的 blob;
  • 以 clang_ 开头且含 / 的路径:次级工具链的产物落在 $root_out_dir/<toolchain>/,要同时用原路径和去掉工具链前缀的路径去匹配 PATHS_TO_SKIP(注释解释了 startswith 的匹配方式)。

ELECTRON_DEBUG_ZIP_SKIP=1 会把每次跳过的路径打印出来(os.environ.get(...)),排查"某个文件怎么没进包"时这是唯一的内置开关。

22.8.4 Linux 的 .stripped 双份与 chrome-sandbox 改名

zip.py:104-108:

# On Linux, filter out any files which have a .stripped companion
if sys.platform == 'linux':
  dist_files = {
    dep for dep in dist_files if f"{dep.removeprefix('./')}.stripped" not in dist_files
  }

strip_binary.gni 的 strip_binary 模板产出两个文件:<binary>.debug(剥离出的调试段)与 <binary>.stripped(瘦身后的可运行二进制)。两个都会进 runtime_deps,所以先按"存在 .stripped 伴生文件"把原始未 strip 版本过滤掉,再在写入时把 .stripped 后缀去掉:

zip.py:135-136

if sys.platform == 'linux':
  name_to_write = name_to_write.removesuffix('.stripped')

还有一处特例(:127-133):

zip.py:128-131

arcname = (
  os.path.join(dirname, 'chrome-sandbox')
  if basename.removesuffix('.stripped') == 'chrome_sandbox'
  else dep
)

文件名在打包时从 chrome_sandbox(下划线)改成 chrome-sandbox(连字符),因为 Linux 上 setuid sandbox helper 的既有名字是后者。这类"构建名 ≠ 分发名"的映射在 zip.py:113-116 里只有这一处,很容易被漏看。

22.8.5 macOS 用系统 zip -y,其余平台用 Python zipfile

zip.py:110-113:

if sys.platform == 'darwin' and not should_flatten:
  execute(['zip', '-r', '-y', dist_zip] + list(dist_files))
else:
  with zipfile.ZipFile(dist_zip, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as z:
    ...

-y 是 store symbolic links as links。macOS 的 .app/.framework 内部大量使用符号链接(Versions/Current、Frameworks 下的引用),Python zipfile 默认会跟随链接把内容复制进去,解包后 framework 结构就毁了。所以非 flatten 的 macOS 产物必须走系统 zip。

代价是两条路径的产物不完全一致:系统 zip 会写入 macOS 扩展属性/资源分叉相关字段、文件时间取自磁盘,Python 路径则是手工 z.write(dep, name_to_write)。upload.py:337-342 的 zero_zip_date_time() 正是为了抹掉这些差异(22.10.4)。

util.py:70-87 的 make_zip 也做了同样的平台分叉,用于 symbols.zip 等发布包,压缩级别统一为 ZIP_COMPRESSION_LEVEL = 6。注释给了数字依据:"Deflate level 6 is ~1.7x faster than level 9 on the multi-GB debug info archives ... and the output is only ~0.4% larger"。

22.8.6 flatten 与跨工具链产物

dist_zip 模板接受 flatten 与 flatten_relative_to。BUILD.gn:1985-2004 的 mksnapshot.zip 用到它,注释说明原因:

$root_out_dir/<toolchain>/; flatten so mksnapshot.zip keeps the layout

arm64 的 mksnapshot 是在 x64 主机上交叉编译的,二进制落在 clang_x64_v8_arm64/ 这类次级工具链目录里。不 flatten 的话,用户下载到的 zip 里会多一层工具链目录,脚本找不到可执行文件。zip.py:139-149 的处理是:若 name_to_write 不以 flatten_relative_to 开头,就退化成 os.path.basename(arcname);并且用 written set 保证"flatten 把多个 dep 映射到同一名字时只保留第一个"——注释举例 "the same file built by two toolchains"。

这条"保留第一个"在 dist_files 是 set(无序)的前提下有点微妙:哪个工具链的文件进包取决于 Python 集合的迭代顺序。对 mksnapshot 来说两份同名文件内容应当等价,但这仍是发布脚本里一处未被显式约束的行为。

BUILD.gn:2040-2065 的 libcxx_headers.zip / libcxxabi_headers.zip 也用 flatten,把 gen/ 下的头文件铺平。

22.8.7 LICENSE、version 与 resource allowlist

electron_dist_zip 的 data_deps 里有 :licenses(:1901-1917),它由两个 copy target 组成:LICENSE → 根目录同名文件,about_credits.html → LICENSES.chromium.html。electron_version_file 提供 version 纯文本。这三个文件在 zip-symbols.py:19 的 licenses 列表里又被复用一次——符号包里也带 LICENSE 与 version,因为符号文件是可独立分发的资产。

check_resource_allowlist.py + build/resource_allowlist_check_suppressions.txt 是打包前的最后一道静态检查:验证 .pak 里没有多余字符串。它只在 Linux/mac 生效,且只在 enable_resource_allowlist_generation 为真时挂到 dist_zip 的 deps 上。

22.8.8 zip_manifests/:终于有一道机器校验

22.10.2 会说 release-assets.json 靠人工维护。但在构建侧,Electron 确实用机器守住了两个最关键 zip 的文件清单,这一节先把证据摊开。

script/zip_manifests/ 下有 16 个 .manifest 文件,命名规则是 <zip名>.<平台>.<架构>.manifest:

前缀平台值数量
dist_zip.linux / mac / mac_mas / win × x64 / arm648
chromedriver_zip.同上8

dist_zip.linux.x64.manifest 的开头是:

LICENSE
LICENSES.chromium.html
chrome-sandbox
chrome_100_percent.pak
chrome_200_percent.pak
chrome_crashpad_handler
electron
icudtl.dat
libffmpeg.so
libvk_swiftshader.so
libvulkan.so.1
locales/af.pak
...

第三行 chrome-sandbox 正好把 22.8.4 那个 chrome_sandbox → chrome-sandbox 的改名固化成了契约——如果哪天 zip.py:129 里那段特例被删掉,这份 manifest 会立刻让 CI 变红。

生成脚本 script/generate-zip-manifest.py:6-10 只有 14 行:

def main(zip_path, manifest_out):
  with open(manifest_out, 'w', encoding='utf-8') as manifest, \
      zipfile.ZipFile(zip_path, 'r', allowZip64=True) as z:
    for name in sorted(z.namelist()):
      manifest.write(name + '\n')

校验脚本 check-zip-manifest.py:23-26 做的是双向差集:

check-zip-manifest.py:23-26

files_in_zip = set(z.namelist())
files_in_manifest = {line.strip() for line in manifest.readlines() if line.strip()}
added_files = files_in_zip - files_in_manifest
removed_files = files_in_manifest - files_in_zip

两个差集都为空才返回 0;否则分别打印 + / - 列表,并给出 "ACTION REQUIRED" 的两条建议("Add the new files to the manifest, or Remove them from the zip")。用 set 意味着它只校验文件名集合:不校验顺序、文件大小、内容哈希、压缩方法、时间戳,也不校验目录项与符号链接是否被正确保留。一份字节被篡改但名字没变的 zip 照样通过——完整性靠 22.10.5 的 checksum,不靠 manifest。

CI 调用点在 .github/actions/build-electron/action.yml:233 与 :307:

target_os=${{ inputs.target-platform == 'macos' && 'mac' || inputs.target-platform }}
if [ "${{ inputs.artifact-platform }}" = "mas" ]; then
  target_os="${target_os}_mas"
fi
electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ inputs.target-arch }}.manifest

外壳还有一层 if [ "${{ inputs.is-asan }}" != "true" ] && [ "${{ inputs.is-ubsan }}" != "true" ]——ASan / UBSan 构建跳过清单校验,因为 sanitizer 会往输出目录里多塞运行时库,manifest 对不上。路径 out/Default/dist.zip 是硬编码的,与 ELECTRON_OUT_DIR(22.10.3)不联动。

所以准确的说法是:dist.zip 与 chromedriver.zip 的文件名集合有机器校验,且按平台/架构/MAS 分了 16 份;ffmpeg.zip、mksnapshot.zip、symbols.zip、dsym*.zip、pdb.zip、debug.zip、xcache.zip 以及所有非 zip 资产都没有对应 manifest。release-assets.json:32-35 那 64 条模式与这 16 份 manifest 是两套独立的清单,各自覆盖一部分产物,彼此没有生成关系。


22.9 符号表:二进制与调试信息的四套分离方案

22.9.1 四个平台的产物矩阵

平台主要符号格式辅助产物生成方式
macOSbreakpad_symbols/(Breakpad .sym)dsym.tar.xz、 dsym-snapshot.zipextract_symbols 从 dSYM 抽
Windowsbreakpad_symbols/pdb.zip从 electron.exe.pdb 抽,PDB 另存
Linuxbreakpad_symbols/debug.zipstrip_binary 剥离出的 .debug 段
全部symbols.zip(含 LICENSE/version)—zip-symbols.py:20

BUILD.gn:1608-1660 是 macOS 的符号 target 群:electron_framework_syms、electron_helper_syms_${_helper_target}(每个 helper 一个)、electron_app_syms、crashpad_handler_syms,全部输出到 $root_out_dir/breakpad_symbols,最后用 group("electron_symbols") 汇总。每个都传 dsym_file 指向对应的 .dSYM/Contents/Resources/DWARF/<name>。

Windows 段(:1847-1856)只有一个 electron_app_symbols。BUILD.gn:1132 那条注释解释了为什么 Windows 的 resource allowlist 还没做:"on Windows this should extract from electron.exe.pdb instead of the inputs pseudo-link (and the executable must then stop depending on :packed_resources to avoid a dependency cycle)"。

22.9.2 dump_syms.py:MODULE 头决定落盘路径

build/dump_syms.py:10-17 只有 53 行,核心是把 dump_syms 的输出按它自己的第一行归档:

BINARY_INFO = collections.namedtuple('BINARY_INFO',
                                     ['platform', 'arch', 'hash', 'name'])

def get_module_info(header_info):
  # header info is of the form "MODULE $PLATFORM $ARCH $HASH $BINARY"
  info_split = header_info.strip().split(' ', 4)
  if len(info_split) != 5 or info_split[0] != 'MODULE':
    return None
  return BINARY_INFO(*info_split[1:])

def get_symbol_path(symbol_data):
  module_info = get_module_info(symbol_data[:symbol_data.index('\n')])
  exe_name = module_info.name.replace('.pdb', '')
  return os.path.join(module_info.name, module_info.hash, exe_name + ".sym")

Breakpad 符号文件的第一行是 MODULE <platform> <arch> <hash> <binary>,其中 <hash> 是二进制的构建 ID / PDB GUID+age。落盘路径形如 Electron Framework/<hash>/Electron Framework.sym。这套 <name>/<id>/<name>.sym 布局是 Breakpad/Crashpad 符号服务器的约定,崩溃报告只带模块 id,服务器据此定位文件——不靠 zip 里的文件名对应。

subprocess.check_output(args).decode(sys.stdout.encoding) 把整个符号文件读进 Python 内存再一次写出。一个 Electron Framework 的 .sym 可达数百 MB,这一步是发布流程里少数几次"整文件过内存"的地方。

22.9.3 extract_symbols.gni:27-30 用 host toolchain

dump_syms_label =
    "//third_party/breakpad:dump_syms($host_system_allocator_toolchain)"
dump_syms_binary = get_label_info(dump_syms_label, "root_out_dir") +
                   "/dump_syms$_host_executable_suffix"

dump_syms 必须跑在构建主机上,所以显式指定 $host_system_allocator_toolchain;交叉编译 arm64 目标时它不是 arm64 二进制。_host_executable_suffix 只在 host_os == "win" 时加 .exe。args 里若有 dsym_file 就追加到末尾,dump_syms.py:36-39 收到第五个参数时拼出 ["-g", dsym_file]。

outputs 只有一个 stamp 文件(不声明 .sym 本身),因为符号路径要等运行 dump_syms 之后才知道 hash——GN 无法在配置期表达这个输出名。这是"输出名依赖输入内容"时 GN 的常见妥协,代价是增量构建只认 stamp,二进制变了但 stamp 没失效就可能漏重新抽符号(inputs 里列了 invoker.binary,所以通常没问题)。

22.9.4 zip-symbols.py 的三条平台分支与一个 2 GiB 上限

script/zip-symbols.py:24-31(75 行):

with scoped_cwd(args.build_dir):
  dirs = ['breakpad_symbols']
  make_zip(zip_file, licenses, dirs)

if PLATFORM == 'darwin':
  dsyms = glob.glob('*.dSYM')
  snapshot_dsyms = ['v8_context_snapshot_generator.dSYM']
  for dsym in snapshot_dsyms:
    if (dsym in dsyms): dsyms.remove(dsym)
  make_tar_xz(dsym_tar_file, licenses, dsyms)
  make_zip(dsym_snapshot_zip_file, licenses, snapshot_dsyms)
  if len(dsyms) > 0 and 'DELETE_DSYMS_AFTER_ZIP' in os.environ:
    execute(['rm', '-rf'] + dsyms)
elif PLATFORM == 'win32':
  pdbs = glob.glob('*.pdb')
  excluded_pdbs = ['electron_xcache.exe.pdb']
  ...
elif PLATFORM == 'linux':
  make_zip(debug_zip_file, licenses, ['debug'])

三条值得单独记的:

v8_context_snapshot_generator.dSYM 单独打包。它是构建期工具(生成 V8 快照),不属于运行时二进制,但调自定义 snapshot 的用户需要它。单独出 dsym-snapshot.zip 让运行时用户不必下载。

electron_xcache.exe.pdb 被排除,注释写明原因:"its V8-sized PDB pushes pdb.zip over GitHub's 2 GiB release asset limit"。这是发布资产体积反过来影响构建脚本的一个具体例子——不是性能考量,是平台硬限制。

DELETE_DSYMS_AFTER_ZIP 是可选清理。dSYM 总量约 7 GB(util.py:90-92 的注释给出这个数),CI 磁盘紧张时才删。make_tar_xz 用 XZ_PRESET = '-3',注释给了实测数据:"The default preset (-6) is ~5x slower than -3 for ~12% smaller output on DWARF; on the 5-core macOS CI runners that is the difference between a ~6 minute and a ~30 minute 'Zip Symbols' step",并且用多线程 xz 拆分输入,因为单线程 xz 处理 7 GB 要 30 分钟以上。

22.9.5 upload-symbols.py:符号服务器的三道规矩

upload-symbols.py:79-86 只在新 tag(upload.py:150 的 if not tag_exists and not args.upload_to_storage)时执行,Windows 上还会顺带跑 upload-node-headers.py。

def run_symstore(pdb, dest, product):
  for attempt in range(2):
    try:
      execute(['symstore', 'add', '/r', '/f', pdb, '/s', dest, '/t', product])
      break
    except Exception as e:
      print(f"An error occurred while adding '{pdb}' to SymStore: {str(e)}")
      if attempt == 0:
        print("Retrying...")

PDB_LIST 由 electron.exe.pdb 加 glob('*.dll.pdb') 组成,symstore add /r /f ... /s ... /t <product> 把 PDB 按符号服务器布局放进 breakpad_symbols。第二次失败被静默吞掉(循环结束没有 raise),所以符号上传不完整时流水线仍然绿。

之后每个 .sym 都跑一次 sentry-cli difutil bundle-sources,生成 .src.zip(源码包),再把 *.pdb/*.sym/*.src.zip 一起上传。

最后一段是路径大小写:

upload-symbols.py:10-17

def is_fs_case_sensitive():
  with tempfile.NamedTemporaryFile(prefix='TmP') as tmp_file:
    return(not os.path.exists(tmp_file.name.lower()))
...
# The symbol server needs lowercase paths, it will fail otherwise
if is_fs_case_sensitive():
  for f in files:
    lower_f = f.lower()
    if lower_f != f:
      if os.path.exists(lower_f): shutil.rmtree(lower_f)
      ...
      shutil.copy2(f, lower_f)
files = [f.lower() for f in files]
for f in files:
  assert os.path.exists(f)

判据很巧:用 NamedTemporaryFile(prefix='TmP') 造一个大小写混合的临时文件,再检查 tmp_file.name.lower() 是否存在——存在说明文件系统大小写不敏感(同一个文件两种写法都能访问),不需要复制;不存在说明大小写敏感,必须生成全小写副本。注释直接写明"The symbol server needs lowercase paths, it will fail otherwise"。

store_artifact(SYMBOLS_DIR, 'symbols', files) 把相对路径原样作为对象 key,于是 Breakpad 的 <name>/<hash>/<name>.sym 结构直接映射到对象存储。util.py:198-206 的 azput 是底层实现(node script/lib/azput.js --prefix ... --key_prefix ...)。

22.9.6 符号与二进制靠什么配对

把 22.9 整节收束成一条因果链,能解释很多"崩溃堆栈显示成地址"的排查:

  1. 构建期 dump_syms 从二进制(或 dSYM/PDB)读出模块 id,写进 .sym 第一行与目录名;
  2. 运行时 Crashpad 生成 minidump,里面只带模块名 + id(第 20 章 ElectronCrashReporterClient);
  3. 符号化服务按 <name>/<id>/<name>.sym 查对象存储;
  4. 找不到就只有地址,找不到且 id 对得上但内容不匹配就会给出错误的行号。

第 4 种情况是自定义构建最容易踩的:修改了源码重新编译但没重新上传符号,或用了不同 BRANDING.json:2(BRANDING.json:2 里的 project_name / product_name / mac_bundle_id)导致模块名变了。upload.py:55-59 那句 Tag (...) should match build (...) 校验的正是发布版本与构建版本的一致性,是这条链上唯一一道自动检查。


22.10 发布链路:改名、抹时间戳、算校验和

22.10.1 先校验 tag,再动任何文件

upload.py:48-70:

build_version = get_electron_build_version()
if not ELECTRON_VERSION.startswith(build_version):
  errmsg = f"Tag ({ELECTRON_VERSION}) should match build ({build_version})\n"
  return 1

tag_exists = False
release = get_release(args.version)
if not release['draft']:
  tag_exists = True

if not args.upload_to_storage:
  assert release['exists'], \
        'Release does not exist; cannot upload to GitHub!'
  assert tag_exists == args.overwrite, \
        'You have to pass --overwrite to overwrite a published release'

ELECTRON_VERSION = 'v' + get_electron_version(),get_electron_version()(util.py:184-192)是 node -p 'require("./script/lib/get-version").getElectronVersion()' 的输出,缓存到模块级变量。get_electron_build_version() 在 --version 未指定时直接返回它(:196-201),所以默认路径下这条校验恒成立——它真正防的是用 -v 显式传了另一个版本的情况。

assert tag_exists == args.overwrite 是个很紧的约束:已发布的 release 必须带 --overwrite 才能上传,草稿 release 带了 --overwrite 反而会失败。get_release() 调用 find-github-release.mts,并特意设 NODE_NO_WARNINGS=1 后用 json.loads() 解析 stdout —— 注释写明"Strip warnings from stdout to ensure the only output is the desired object",因为 Node 的任何警告都会让 JSON 解析失败。

22.10.2 release-assets.json 是校验表,不是产出表

release-assets.json:2 只有 64 条 patterns,形式如 electron-${version}-darwin-x64.zip。它列的是一个完整发布应当具备的资产名集合。与 upload.py 实际上传的内容对一下,能发现几处差异:

现象说明
xcache.zip 被上传(upload.py:130)清单里无对应模式
libcxx-objects-* 只在 Linux 上传清单里有 linux-x64 / linux-arm64 两条
electron-api.json / electron.d.ts 只在 darwin && x64 上传清单里是两条无平台前缀的名字
hunspell_dictionaries.zip 只在 linux && x64 上传清单里一条
*-toolchain-profile.zip 只在 Windows 上传清单里有 win32-x64 / win32-arm64 两条
mksnapshot-*-linux-arm64-x64.zip名字里带 -x64,来自 22.8.6 的交叉构建约定

"只在某个 job 上传"是刻意的去重:同一份平台无关资产不该被 8 个构建矩阵各传一次。electron-api.json 与 electron.d.ts 选 darwin && x64 只是约定,若那个 job 失败,其余七个 job 全绿也补不上这两个文件。清单本身不做生成,靠人工维护——这是发布流程里典型的"检查表与执行脚本双份真相"。不过要区分清楚:构建侧另有 16 份 zip_manifests/*.manifest 用机器校验 dist.zip 与 chromedriver.zip 的文件名集合(22.8.8),两套清单覆盖的产物不同、彼此没有生成关系;release-assets.json 管的是"Release 页面该有哪 64 个资产",manifest 管的是"这两个 zip 里该有哪些文件"。

22.10.3 上传顺序与平台条件矩阵

upload.py:72-166 的顺序是固定的:

  1. 复制 dist.zip → electron-${version}-<platform>-<arch>.zip,上传;
  2. 复制 symbols.zip → 同名带 -symbols,上传;
  3. macOS:electron-api.json、electron.d.ts(仅 x64)、dsym.tar.xz、dsym-snapshot.zip;
  4. Windows:pdb.zip;
  5. Linux:debug.zip、libcxx_objects.zip、libcxx_headers.zip / libcxxabi_headers.zip(仅 x64);
  6. 全平台:ffmpeg(从 src/out/ffmpeg/ffmpeg.zip 复制到 OUT_DIR)、xcache(MAS 跳过)、chromedriver、mksnapshot、hunspell(仅 linux-x64);
  7. 仅新 tag:upload-symbols.py,Windows 再加 upload-node-headers.py;
  8. Windows 收尾:把 windows_toolchain_profile.json 现打包成 zip 再上传。

三步容易看漏的细节:

ffmpeg.zip 的源在另一个输出目录。SRC_DIR/out/ffmpeg/ffmpeg.zip 不在 OUT_DIR,因为 ffmpeg 是独立 GN 构建(专有编解码器授权原因)。其余所有产物都在 get_out_dir()(util.py:208-213,默认 src/out/Default,可由 ELECTRON_OUT_DIR 覆盖)。

arm64 的 mksnapshot 上传的是 x64 二进制但用 x64 名字(:139-147):if get_target_arch() == 'arm64' and PLATFORM != 'darwin' 时把目标名改成 ...-x64.zip,而 mksnapshot.zip 的内容不变。这与 22.8.6 的 snapshot_blob.bin 排除条件互为表里。

符号上传与 node headers 只在首次发布时做(:149-153)。重跑一次发布(比如覆盖某个 zip)不会重复往符号服务器推同一批符号,也不会重复上传 headers。assert tag_exists == args.overwrite 保证了重跑必须带 --overwrite,此时 tag_exists=True,条件 not tag_exists 为假,正好跳过。

22.10.4 zero_zip_date_time:上传前抹掉非确定性

upload_electron() 的第一件事(upload.py:337-343):

filename = os.path.basename(file_path)
try:
  zero_zip_date_time(file_path)
except NonZipFileError:
  pass

_zero_zip_date_time(:218-335)用 mmap 遍历 zip 的中央目录与本地文件头,把 DOS 日期/时间字段清零,并处理三类 extra field:STRIPZIP_OPTION_HEADER (0xFFFF)、EXTENDED_TIME_DATA (0x5455)、UNIX_EXTRA_DATA (0x7875)、ZIP64_EXTRA_HEADER (0x0001)。其中 ZIP64 的 8 字节长度会覆盖规范 zip 头里的 4 字节长度,必须单独按 Struct("<HHQQ") 解析。

为什么需要这一步?22.8.5 说过 macOS 用系统 zip -r -y、其他平台用 Python zipfile,前者把 mtime 写进每条记录,后者也默认取文件 mtime。同一份源码、同一次构建,在不同时间打出的 zip 字节会不同;对可复现构建和 SHA256 校验和来说这是噪音。抹掉时间后,dist.zip 的内容只由输入文件字节决定。

NonZipFileError 被静默吞掉(except: pass),因为上传列表里还有 electron-api.json、electron.d.ts、dsym.tar.xz 这些非 zip 文件。这是"对所有产物统一调一次、失败即跳过"的写法,副作用是一个损坏的 zip 也会因为解析失败而被当成非 zip 直接上传,且后续的 checksum 会照算不误。

22.10.5 checksum 的两条存储路径

upload.py:386-393

def upload_sha256_checksum(version, file_path, key_prefix=None):
  checksum_path = f'{file_path}.sha256sum'
  if key_prefix is None:
    key_prefix = f'checksums-scratchpad/{version}'
  sha256 = hashlib.sha256()
  with open(file_path, 'rb') as f:
    sha256.update(f.read())
  with open(checksum_path, 'w', encoding='utf-8') as checksum:
    checksum.write(f'{sha256.hexdigest()} *{filename}')
  store_artifact(os.path.dirname(checksum_path), key_prefix, [checksum_path])

格式是 GNU coreutils 的 <hex> *<filename>(* 表示二进制模式)。注意校验和在 zero_zip_date_time 之后计算(upload_electron 先抹时间再上传再算 checksum),所以 checksum 对应的是用户实际下载到的字节。

--upload-to-storage 模式下 key_prefix 变成 release-builds/{version}_{YYYYMMDD}(:52-56 用 datetime.utcnow()),checksum 与 zip 存到同一前缀;GitHub 模式下 checksum 只进 checksums-scratchpad/{version},不上传为 release asset。release-assets.json 里确实没有任何 .sha256sum 模式——用户从 GitHub Release 页面看不到校验和文件,它只在对象存储里。

store_artifact → azput → node script/lib/azput.js 是唯一的存储出口,注释只有一行 # Azure Storage。

22.10.6 GitHub 上传的四次重试与"先删后传"

upload-to-github.mts:48-55(125 行):

const uploadUrl = `https://uploads.github.com/repos/electron/${targetRepo}/releases/${releaseId}/assets{?name,label}`;
let retry = 0;
...
.catch((err) => {
  if (retry < 4) {
    retry++;
    // Reset octokit in case it cached an auth error somehow
    octokit = new Octokit({ authStrategy: createGitHubTokenStrategy(targetRepo), log: console });
    octokit.repos.listReleaseAssets({ owner, repo, release_id: releaseId, per_page: 100 })
      .then((assets) => {
        const existingAssets = assets.data.filter((asset) => asset.name === fileName);
        if (existingAssets.length > 0) {
          octokit.repos.deleteReleaseAsset({ ..., asset_id: existingAssets[0].id })
            .catch((deleteErr) => { console.log(...); })
            .then(uploadToGitHub);
        } else {
          uploadToGitHub();
        }
      })

四个设计点:

每次重试都重建 Octokit,注释说是防"cached an auth error"——GitHub App 的 installation token 有效期短,长时间上传后原实例可能持有过期凭据;createGitHubTokenStrategy(targetRepo) 会在新建时重新取 token。

先列出资产、删掉同名项,再重传。GitHub Release 不允许同名资产,上传中断后服务端可能已留下一个不完整的资产;不删就永远传不上去。per_page: 100 是硬编码上限,一个 release 的资产超过 100 个时分页缺失会让删除逻辑找不到目标——release-assets.json 有 64 条模式,还没到这个界。

删失败仍然继续上传(.catch(...).then(uploadToGitHub)),日志只打一行,不终止。

retry < 4 意味着最多 5 次尝试(初次 + 4 次重试),失败后只设 process.exitCode = 1,不 process.exit()。upload_io_to_github 用 subprocess.Popen(..., stdout=PIPE) 等它退出并检查 returncode,非零就 sys.exit(rc),所以整条流水线会在第一个真正失败的资产处停下。

getHeaders 的 content-type 映射只有 5 项(json/zip/txt/ts 与缺省 undefined),.tar.xz、.sha256sum 不在表里——扩展名不在表中时 content-type 是 undefined,Octokit 会自己决定。注释没解释,但 throw new Error('Failed to get headers for extensionless file') 表明无扩展名文件是明确禁止的。

22.10.7 nightly 判定:indexOf('nightly') > 0

function getRepo(): ElectronReleaseRepo {
  return releaseVersion.indexOf('nightly') > 0 ? NIGHTLY_REPO : ELECTRON_REPO;
}

用的是 > 0 而不是 >= 0 或 includes()。版本号形如 v45.0.0-nightly.20260101,nightly 出现在索引大于 0 处,判据成立;一个恰好以 nightly 开头的版本串会被判成正式 repo。考虑到 upload.py 里 ELECTRON_VERSION = 'v' + ...,实际不会以 n 开头,所以这是个无害但脆弱的写法。

createGitHubTokenStrategy(targetRepo) 按 repo 取不同的 GitHub App 凭据,说明 nightly 与正式发布用的是两套权限。types.mts:1 定义 ELECTRON_ORG / ELECTRON_REPO / NIGHTLY_REPO,find-github-release.mts:4-24(49 行)按版本找 draft/published release 并返回 { id, exists, draft }。


22.11 签名与公证:运行时消费的是签名,不是脚本

22.11.1 仓库里没有发布签名脚本

先把边界说清楚:这个仓库不包含给分发产物签名的脚本。code-signing.md:111-116 把 macOS 的 @electron/osx-sign / @electron/notarize、Windows 的 Azure Artifact Signing / jsign / 传统证书 / WiX MSI / electron-builder 都列为外部工具链;script/codesign/ 下只有四个测试辅助脚本:

文件行数用途
generate-identity.sh35生成自签名测试证书
get-trusted-identity.sh13取可信 identity 供 spec 使用
cleanup-identity.sh21清理测试证书
codesign.cnf18OpenSSL 配置

codesign-helpers.ts:11 的门控是 process.platform === 'darwin' && !process.mas && !features.isComponentBuild()——组件构建与 MAS 构建都不跑签名测试。这几份脚本的作用是让第 21 章 L5 那类真实安装包测试能有一张可用的证书,不是 Electron 官方二进制的签名流程(那在 CI 的私有配置里)。

这个边界很重要:22.5 讲的 plist / PE 资源信任锚,其安全性依赖"改了二进制就得重签",但重签这一步 Electron 本体既不做也不校验——它只假设 OS 已经验过。

22.11.2 运行时唯一读签名的地方:codesign_util.cc

codesign_util.cc:69-75(2023 Microsoft 版权,改编自 Chromium)提供两个函数:

std::optional<audit_token_t> GetParentProcessAuditToken() {
  pid_t parent_pid = getppid();
  task_name_t parent_task;
  kern_return_t kr =
      task_name_for_pid(mach_task_self(), parent_pid, &parent_task);
  ...
  kr = task_info(parent_task, TASK_AUDIT_TOKEN,
                 reinterpret_cast<task_info_t>(&token), &size);
  ...
}

注释解释了为什么用 task_name_for_pid 而不是别的 API:"yields a name port (not a control port), so it does not require any special entitlement"。头文件补了另一条:"Callers should invoke this as early in process startup as possible"——父进程可能很快退出,晚取就拿不到 audit token。

ProcessSignatureIsSameWithCurrentApp 用 SecCodeCopySelf 拿自己的签名、SecCodeCopyDesignatedRequirement 取 designated requirement,再用 SecCodeCopyGuestWithAttributes 按 audit token(而非 pid)查目标进程,最后 SecCodeCheckValidity 判断其是否满足同一 requirement。源码注释把选择 audit token 的理由写全了:

kSecGuestAttributeAudit is preferred over kSecGuestAttributePid because the audit token is bound to a single process instance and cannot be spoofed by PID reuse or by the target exec()ing into a different image after the lookup.

这是防 TOCTOU:用 pid 的话,攻击者可以在查询与校验之间让目标 exec() 成另一个映像,或等 pid 被复用。第 21 章 openAsarFiles 用 WeakRef + handle.fd === fd 防 fd 复用,是同一类问题的 JS 版本。

这套检查服务于"子进程是不是自己人"的判断,与 22.5 的 asar 完整性、第 20 章的 fuse 一起构成运行时信任链,但它检查的是进程身份,不是文件字节。

22.11.3 未签名时 fail-open,以及一个具体的 Node 后果

IsUnsignedOrAdHocSigned 读 kSecCodeInfoFlags,flags & kSecCodeSignatureAdhoc 或 flags 缺失都算"未签名/临时签名"。ProcessSignatureIsSameWithCurrentApp 随后:

if (not_signed.value()) {
  // Current app is not signed.
  return true;
}

头文件注释把这条看似矛盾的设计解释得很具体:

This API returns true if current app is not signed or ad-hoc signed, because checking code signature is meaningless in this case, and failing the signature check would break some features with unsigned binary (for example, process.send stops working in processes created by child_process.fork, due to the NODE_CHANNEL_ID env getting removed).

也就是说开发期未签名的 Electron 必须让所有子进程通过身份检查,否则 child_process.fork() 的 IPC 通道环境变量会被剥掉,process.send 直接失效。这是一个"为了不破坏默认行为而放宽安全检查"的明确取舍,也是 code-signing.md:79-98 那句"unsigned or ad-hoc signed app may behave inconsistently"背后的实现。

文档列出的四个需要签名的 API 里,safeStorage、cookieEncryption fuse、autoUpdater 都依赖 OS 层 Keychain / Squirrel.Mac 对"同一个 app"的识别;app.setLoginItemSettings() 则要求"not packaged, code signed, and notarized"三者齐备。这些都不是 Electron 自己能检测的,所以文档只能给现象清单。

22.11.4 改 fuse 与改资源都必须发生在签名之前

把第 20 章与本章拼起来,一次正确的打包顺序是:

  1. 用 @electron/asar 生成 app.asar(带 integrity 字段);
  2. 算 header hash;
  3. 写进 Info.plist 的 ElectronAsarIntegrity(mac)或 PE 的 Integrity/ElectronAsar 资源(Win);
  4. 填 Mach-O __DATA_CONST,__asar_integrity slot(mac,可选);
  5. 用 @electron/fuses 翻转 fuse wire(const volatile 数组里的字节);
  6. 最后整体签名,macOS 再公证、staple。

spec/asar-integrity.spec.ts:158-159 的注释直接印证了第 3 步与第 5 步的顺序:"This has to happen before the fuses are flipped, which re-signs the app"——@electron/fuses 的 flipFuses 在 macOS 上会做 ad-hoc 重签(resetAdhocDarwinSignature 选项),如果先翻 fuse 再改 plist,plist 的改动又会让签名失效。

@electron/fuses 工具侧还给了一个保护:把 fuse 位设成 'r'(removed)后不允许再改回 '1'。第 20 章已经指出这不是运行时状态——getter 只判 == '1',真正的防护是签名;这里可以再补一句:一旦重签被跳过,手工把 'r' 改回 '1' 就能重新启用被移除的 fuse。所以"翻转 + 重签"必须作为一个原子动作看待。


22.12 体积:被 strip、压缩级别和 2 GiB 上限共同塑形

22.12.1 三套 strip

平台机制产物
Linuxstrip_binary.gni:29-54 调 llvm-strip + llvm-objcopy.debug + .stripped,可选 --compress-debug-sections
macOSbuild/strip_framework.py:17 cp -a 后删 Headers/ 与 Versions/Current/Headers/瘦身后的 Squirrel/Mantle/ReactiveObjC framework
Windows不做二进制 strip,PDB 天生分离.pdb

BUILD.gn:1467-1508 的 stripped_framework 模板只用于三个第三方 framework(Mantle、ReactiveObjC、Squirrel),strip_framework.py:14 的全部工作是删头文件——注释 "Strip headers, we do not need to ship them"。真正的调试符号在 dSYM 里,由 22.9.4 单独打包。

Linux 的 strip_binary 只在 is_official_build 时挂到 dist_zip(BUILD.gn:1926-1933):测试构建保留完整符号表。这正是第 21 章 codesign-helpers.ts:140 要 strip -x 的原因——testing build 带全符号表,codesign/zip/ditto 都会按体积放大处理时间。

22.12.2 压缩级别的两组实测数字

util.py:65-68:

Deflate level 6 is ~1.7x faster than level 9 on the multi-GB debug info archives this is used for (pdb.zip, dsym-snapshot.zip, debug.zip), and the output is only ~0.4% larger.

util.py:90-93:

xz preset -3:The default preset (-6) is ~5x slower than -3 for ~12% smaller output on DWARF; on the 5-core macOS CI runners that is the difference between a ~6 minute and a ~30 minute "Zip Symbols" step.

两处都是用时间换 0.4% / 12% 体积时不换的判断,且给了实测平台(5 核 macOS CI)。make_tar_xz 还启用多线程 xz,因为单线程处理约 7 GB dSYM 要 30 分钟以上。

22.12.3 平台硬限制反向约束构建

electron_xcache.exe.pdb 被排除出 pdb.zip 的原因不是"没用",而是 GitHub Release 单个资产 2 GiB 上限(22.9.4)。类似的体积约束还体现在:

  • zip.py:52 排除 resources/inspector 与四个 gen/third_party/... 目录,这些是 DevTools 前端与生成物,体积大且运行时不需要;
  • angledata、pyproto、libEGL/libGLESv2 空壳被排除;
  • debug/ 不进 dist.zip,走 debug.zip;
  • dSYM 单独 dsym.tar.xz,并允许 DELETE_DSYMS_AFTER_ZIP 在打包后清理。

换句话说 dist.zip 的体积不是"所有构建输出减去没用的",而是"所有构建输出减去被明确列出的、且往往是因为体积或平台限制才列出的"。每次上游 Chromium 新增一个生成目录,都要靠人去 PATHS_TO_SKIP 补一行——ELECTRON_DEBUG_ZIP_SKIP=1 就是给这件事用的诊断开关。


22.13 类型、头文件与 config.gypi:给第三方开发者产物

22.13.1 文档是类型的唯一真源

package.json:67-69:

"create-api-json": "node script/create-api-json.mjs",
"create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js",
"gn-typescript-definitions": "npm run create-typescript-definitions && node script/cp.mjs electron.d.ts"

链路是 docs/api/*.md → electron-api.json → electron.d.ts → ts-smoke。第 21 章从 CI 角度讲过 lint:docs 会校验 api-history schema 与文档内 JS 代码块的类型;这里从产物角度看:electron.d.ts 不在 dist.zip 里,它是独立的 release asset,由 darwin && x64 那一个 job 上传(upload.py:83-89)。改一个文档的 JSDoc 描述,会改变一个被成千上万项目下载的 1 MB 文件。

22.13.2 Node 头文件的四个兼容名字

upload-node-headers.py:19-24:

HEADER_TAR_NAMES = [
  'node-{0}.tar.gz',
  'node-{0}-headers.tar.gz',
  'iojs-{0}.tar.gz',
  'iojs-{0}-headers.tar.gz'
]

同一份 node_headers.tar.gz 被复制成四个名字上传,覆盖历史上 node-gyp 用过的各种 URL 约定(iojs 是 2015 年 io.js 与 Node 合并前的名字)。Windows 上还把 electron.lib 复制成 node.lib、iojs.lib、win-x64/node.lib 等路径(:55-80),供链接原生模块时按不同工具链的查找规则命中。

这些别名只在 upload-node-headers.py 里,而 release-assets.json 里一个都没有——校验表完全不管 headers 资产,因为它们进的是对象存储 headers/dist/{version} 而非 GitHub Release。

22.13.3 config.gypi:用 JSON 写 gyp 条件的三个理由

script/generate-config-gypi.py:60-67 生成随 headers 分发的 config.gypi。它先跑 third_party/electron_node/configure.py,用 ast.literal_eval 读回结果,再读 all.gn:5 里的 node_module_version,最后做几处改写:

v['built_with_electron'] = 1
v['node_module_version'] = int(args['node_module_version'])
v['build_v8_with_gn'] = 'false'   # Used by certain versions of node-gyp.
v.pop('clang', None)
v.setdefault('conditions', []).append(['OS=="mac"', {'clang%': 1}])
config.setdefault('target_defaults', {}).setdefault(
    'target_conditions', []).append(
        ['OS=="mac"', {'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '13.0'}}])

三条注释解释了各自的必要性:

  • "One config.gypi ships in the headers for every platform, so per-OS values for native module builds are expressed as gyp conditions rather than baked" —— 只有一份文件,不能在生成期把当前平台的 clang 值写死,必须留成条件表达式让 node-gyp 在用户机器上求值。
  • target_conditions 放在 common.gypi 自己的条件之后,所以能覆盖它;目的写得很具体:"keeps native modules loadable on macOS 13.0 - 13.4, which Chromium still supports"。
  • 输出用 json.dumps(indent=2, sort_keys=True) 而不是 pprint,因为 "node-gyp reads this file by swapping quote characters, which only round-trips the condition strings in this form"。

还有一步容易被忽略:run_node_configure() 生成 config.gypi 后,main() 随即 os.remove() 删掉它,理由是"to make the parallel/test-process-config test pass"。也就是说这个脚本把 Node 源码树里的生成物当临时文件用,最终产物只写到 target_file。

把 22.13 与 22.10 合起来看,Electron 的"发布"实际有两类受众:下载 dist.zip 的最终应用打包者,和下载 headers/lib/d.ts 的原生模块与 TypeScript 开发者。两类产物的生成链路、上传条件、校验表覆盖程度完全不同——release-assets.json 主要服务前者。


22.14 对照:把全章的判据摊到一张表上

22.14.1 五条边界 × 关键文件 × 运行时读点

边界打包期写什么落在哪个字节运行时谁读读错会怎样
① 构建/运行gn-asar.js:1 重建目录树后调 @electron/asarPickle 头 + JSON headerArchive::Init() archive.cc:217LOG(ERROR) 后返回 false,上层报 ENOENT
② 归档/文件系统unpacked 标记 + .unpacked/ 目录header 里的 boolCopyFileOut :458静默走真实路径,跳完整性校验
③ 可信/不可信header hash 进 plist / PE 资源Info.plist / Integrity 资源HeaderIntegrity() mac/winLOG(FATAL),进程退出
④ 主产物/符号MODULE <platform> <arch> <hash> <name>.sym 第一行符号服务器按 id 查堆栈只有地址
⑤ 构建/发布改名 + 抹时间戳 + checksumzip 中央目录时间字段下载方校验 checksum可复现构建失效

这张表的共同点是:每一行的"运行时谁读"都在 C++ 或 Node 启动极早期,晚于 JS 业务代码。所以打包期的问题不会以 API 报错的形式出现,只会是"启动即退出"或"某个资源加载不出来"。

22.14.2 同一个 asar 文件,五种读取路径的校验粒度

读取方式数据来源校验对象校验时机失败表现
fs.readFileSync(path)retained fd 整块读入integrity.hash(全文件 SHA256)读完后、返回前JS 层 exitImmediately(1)
fs.open() + fs.read(fd)AsarEntryReader 逐块integrity.blocks[n]每块交给调用方之前exitImmediately(1),前面块已送达
createReadStream / FileHandle同上,保留最近一个已验证块分块流式到达损坏块时终止流
file:// 子资源 + RangeDuplicateFile() + FilteredDataSource分块 + abandoned_buffer 补读写入 data pipe 之前LOG(FATAL)
file:// HEAD 请求只读 header 信息不校验无损坏文件仍返回 200
child_process.execFile / process.dlopenCopyFileOut 临时文件全文件 SHA256落盘时LOG(FATAL)

spec/asar-integrity.spec.ts:315-318 的 still serves ranges that only touch intact blocks when a later block is corrupted 正是这张表的直接证据:"文件被篡改"与"某次读取失败"不是一回事。同样,"页面能打开"也不能推出 asar 完好——HEAD 请求和未触及损坏块的 Range 都不会触发校验。

22.14.3 四个平台的差异汇总

维度macOSWindowsLinux
asar 完整性Info.plist 字典 + Mach-O digest slotPE 资源 Integrity/ElectronAsar不校验(archive.cc:311-319 返回 nullopt)
header hash 键Resources/app.asar(正斜杠,精确匹配)resources\app.asar(小写化后匹配)—
算法字段algorithm = SHA256alg = sha256(大小写不敏感)—
缺信任锚返回 nullopt → Init FATAL直接 LOG(FATAL)—
主压缩包系统 zip -r -y(保留符号链接)Python zipfilePython zipfile
二进制瘦身framework 删 Headers + dSYM 分离PDB 天然分离llvm-strip 产出 .stripped
符号副产物dsym.tar.xz + dsym-snapshot.zippdb.zip(排除 xcache PDB)debug.zip
更新/签名代码签名 + 公证 + Squirrel.MacAuthenticode + Squirrel / MSIX无系统级签名

Linux 上 embedded_asar_integrity_validation 编译期就被摘掉:#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) 包住 Archive::Init 的校验块,而非 mac/win 的实现文件里 HeaderIntegrity() 与 RelativePath() 直接 return std::nullopt(:311-319)。asar-integrity.md:11 的 "Version support" 段只列了 macOS 与 Windows,与代码一致,但没有说明这是编译期分支而非运行时判断。

only_load_app_from_asar 则三个平台都生效(app_package.cc 无平台 #if),所以 Linux 应用可以只锁加载路径、不做内容校验。

22.14.4 一次正确打包的顺序清单

把 22.5、22.11、22.10 的因果合成可执行的顺序,越靠前越不能挪到后面:

  1. 编译 JS/资源,用 @electron/asar >= 3.1.0 生成带 integrity 的 app.asar;把必须真实存在的文件用 asarUnpack 移出(并接受它们不受校验)。
  2. 用 getRawHeader().headerString 算 header SHA256——不是整个文件、不是含 Pickle 前缀的字节。
  3. 写入 Info.plist(mac)或 PE 资源(Win),可选填 __DATA_CONST,__asar_integrity slot。
  4. flipFuses 翻转 EnableEmbeddedAsarIntegrityValidation 与 OnlyLoadAppFromAsar;若用自定义 V8 snapshot,注意 ValidateV8Snapshot 会一并启用(22.1.5)。
  5. 整体代码签名;macOS 再公证、staple。此后任何字节改动都会让第 3、4 步的信任链失效。
  6. 压缩、抹时间戳、算 checksum、上传;符号单独走 22.9 的链路,且只在新 tag 时推符号服务器。

22.14.5 排查顺序

遇到"设了没生效"或"打包后行为变了",按本章的判据从外往里查比逐个试参数快:

  1. 确认平台编译期分支:asar 完整性在 Linux 完全不存在;IS_MAS_BUILD()、BUILDFLAG(...) 决定很多 API 是否在二进制里(第 19、20 章同款)。
  2. 确认 fuse 位与签名:electron::fuses 的 getter 只判 == '1';'r' 是工具侧策略不是运行时状态;改过二进制没重签,OS 层就可能拒绝加载。
  3. 确认信任锚的键名与大小写:mac 用正斜杠精确匹配,Win 用小写化路径;algorithm vs alg、hash vs value。
  4. 确认路径归属:只有相对 Contents/(mac)或 DIR_ASSETS(Win)的归档才校验;放在 userData 的 asar 永远不校验。
  5. 确认读取路径:整文件、分块、Range、HEAD、unpacked 五种路径的校验粒度不同(22.14.2)。
  6. 最后才看字段名与类型:offset 必须是字符串、blockSize 必须是正数 int、algorithm 必须是字面量 "SHA256"。

22.15 十五个常见误解

这一章的误解有个共同特点:全都不报错。它们表现为白屏、启动即退出、数据看起来正常但其实是伪造的、或者某个 CI job 静默少传了一个文件。

误解 1:.asar 是"4 字节长度 + JSON 头 + 内容"。 实际是 8 字节的两层 Pickle:前 4 字节是 Pickle 的 payload 长度,后 4 字节是第二块的长度 size,第二块里再用 ReadString 解出 JSON。header_size_ = 8 + size(archive.cc:306)。按 4 字节解析会整体错位。

误解 2:header 里的 offset 是数字。 FillFileInfoWithNode:124-129 用 FindString + StringToUint64 读。写成 JSON 数字会返回 false,最终报 ENOENT,看起来像"文件没打进包"。

误解 3:asarUnpack 只是为了避免额外解包的开销。 unpacked: true 在 :117-122 直接 return,连 integrity 字段都不读。开了完整性 fuse 的应用里,这些文件完全没有校验。文档 asar-archives.md:183-201 只讲了性能与杀毒软件。

误解 4:fs.stat() 拿到的 inode 和时间戳可以用来做缓存键。 asar-fs-wrapper.ts:160-248 里 ino 是每次调用 ++nextInode(同一文件两次 stat 结果不同),四个时间戳恒等于模块加载时刻,整个进程内一致。文档只说"不要相信 Stats,除了 size 和类型"。

误解 5:ELECTRON_NO_ASAR=1 在任何进程都能关掉 asar 支持。 asar-fs-wrapper.ts:16 的条件是 process.env.ELECTRON_NO_ASAR && process.type !== 'browser' && process.type !== 'renderer'。主进程与渲染进程设了它无效,只有 utility / Node 子进程受影响。

误解 6:开了 integrity fuse,应用里所有 .asar 都受保护。 Archive::Init:276-277 要求 RelativePath().has_value(),即归档必须在应用包的 Contents/(mac)或 DIR_ASSETS(Win)之内。放在 userData、临时目录、外挂资源的 asar 不校验。

误解 7:完整性校验是一个开关、一处代码。 至少五处独立实现:C++ 的 ValidateIntegrityOrDie(header / ReadFileToString / ScopedTemporaryFile)、JS 的 validateBufferIntegrity / validateBufferIntegrityAsync、AsarFileValidator 的流式分块。全量哈希与分块哈希覆盖范围不同,HEAD 请求完全不校验。

误解 8:integrity.algorithm 写成小写也能用。 archive.cc:165 只认 *algorithm == "SHA256"。写成 sha256 时前面字段都读到了,但 info->integrity 没被赋值,最后 LOG(FATAL) << "Failed to read integrity for file in ASAR archive" —— 错误信息像是缺字段,实际是字符串不匹配。

误解 9:运行中替换 app.asar 会立刻加载新代码(或导致新旧字节混读而崩)。 Archive 持有 retained fd,ReadFileToString 明确不按路径重开;POSIX 上替换后旧 fd 仍指向原 inode,offset 与 hash 仍与缓存的旧 header 对得上。应用继续跑旧代码,必须重启。spec/asar-integrity.spec.ts:339-386 有专门用例。

误解 10:OnlyLoadAppFromAsar 只是把候选列表缩短成一项。 IsRequiredAppArchive(asar_util.cc:48-66)完全不看磁盘,把 resources/app.asar 两种拼写无条件判成"非目录",且不写缓存。它防的是"启动后把归档换成同名目录"这类路径语义攻击。

误解 11:asar integrity fuse 与自定义 V8 快照互不影响。 electron_main_delegate.cc:126-136 的 ValidateV8Snapshot 用的开关也是 IsEmbeddedAsarIntegrityValidationEnabled(),会 CHECK 快照的 SHA256 是否等于构建期编进 snapshot_checksum.h 的值。开启 fuse 后换自定义 snapshot 必须重新编译。

误解 12:符号表是 dist.zip 的一部分。 zip.py 明确排除 .pdb 与 debug/,zip-symbols.py:20 单独产出 symbols.zip / dsym.tar.xz / pdb.zip / debug.zip。符号与二进制靠 Breakpad MODULE 头里的 hash 配对,不靠 zip 内文件名。

误解 13:release-assets.json 是上传脚本自动生成并检查的清单。 它是人工维护的 64 条模式,upload.py:131 并不读它。xcache.zip 被上传却不在清单里;electron.d.ts 与 electron-api.json 只在 darwin && x64 一个 job 上传,那个 job 失败时其余 job 补不上。构建侧确有无误的机器校验,但只覆盖 dist.zip 与 chromedriver.zip 的文件名集合(16 份 zip_manifests/*.manifest,见 22.8.8),而且不校验内容字节。

误解 14:发布时的 SHA256 校验和等于构建产物 dist.zip 的哈希。 upload_electron() 先就地调 zero_zip_date_time() 抹掉 zip 时间字段与 extra field,再算 checksum。校验和对应的是用户下载到的字节,与构建目录里那份 dist.zip 不同。

误解 15:这个仓库里有给官方二进制签名的脚本,electron.d.ts 也在 dist.zip 里。 script/codesign/ 下四个文件只服务测试证书;签名/公证由 @electron/osx-sign、@electron/notarize、Azure Artifact Signing 等外部工具完成。electron.d.ts 与 electron-api.json 是独立 release asset,由 docs/api/*.md 生成,不进 dist.zip。

再补一条不算误解但极易踩的:ELECTRON_OUT_DIR 能改 OUT_DIR(默认 src/out/Default),但 upload.py:124 的 ffmpeg 路径写死 SRC_DIR/out/ffmpeg/ffmpeg.zip。改了输出目录后,dist.zip 等产物跟着变,ffmpeg 却仍去固定位置找。


22.16 小结:分发产物是运行时状态的另一种写法

把这一章收束成三句话。

第一句:asar 不是压缩包,是一份被包装成文件系统的只读索引。 它没有压缩、没有校验和字段(除非另开 fuse)、offset 是字符串、link 只是 JSON 里的一个键、fs.stat 返回的 18 个字段有 14 个是编出来的。 Electron 为它写了 2493 行 JS 包装层、509 行 C++ 读档器、146 行流式校验器、两个平台各一份信任锚读取器,以及 4000 多行的 spec/asar.spec.ts。这些代码存在的唯一理由是让 require('./foo') 在归档内外表现一致——一致的代价是伪造。

第二句:完整性不是"给文件算个哈希",而是一条跨三层的信任链。 OS 签名保护 Info.plist / PE 资源(以及可选的 Mach-O digest slot),其中的 header hash 保护 JSON header,header 里的 per-file hash 再保护内容。链条上任何一环缺失都是 LOG(FATAL) 而不是降级;链条之外的东西(Linux、unpacked 文件、包外 asar、HEAD 请求)则完全不校验。理解"哪里不校验"与理解"哪里校验"同样重要。spec/asar-integrity.spec.ts 用 412 行把这条链的每个断点都测了一遍,包括"被篡改的文件某些 Range 仍能正常返回"这种反直觉情形。

第三句:发布脚本是构建系统的第二份规格说明。 dist.zip 的内容由 GN runtime_deps 闭包决定,被 zip.py:100-103 的两张排除表裁剪,再被 upload.py:74-76 改名、抹时间戳、算 checksum;符号走另一条按 MODULE hash 索引的路;类型定义、headers、config.gypi 服务的是另一类受众。这三条链路里,release-assets.json 只是人工维护的校验表,只有 dist.zip 与 chromedriver.zip 另有 16 份 manifest 做文件名集合的机器校验,PATHS_TO_SKIP 靠人跟上上游变化,upload-symbols.py 的第二次失败被静默吞掉。"发布成功"与"产物齐全"不是同一件事,第 21 章 L4/L5 之所以必须用真实构建产物测试,原因就在这里。

从第 17 章的工厂链、第 19 章的取像素路径,到这一章的打包产物,Electron 身上反复出现同一个模式:它没有自己的一套东西,而是在 Chromium / Node / 各平台既有机制之间插入薄薄一层,然后把这层的边界条件写进源码注释里。读 Electron 源码最有效的办法,往往就是先找那句解释"为什么必须这么绕"的注释——本章里 volatile 防常量折叠、retained fd 防更新期替换、audit token 防 pid 复用、abandoned_buffer 补读被跳过的块,全都是这样找到的。