Skip to content

fix(installer): stop server and verify binaries to prevent half-install - #1984

Draft
takomitkm wants to merge 8 commits into
rime:masterfrom
takomitkm:installer/anti-half-install
Draft

takomitkm wants to merge 8 commits into
rime:masterfrom
takomitkm:installer/anti-half-install

Conversation

@takomitkm

@takomitkm takomitkm commented Nov 16, 2026 •

Copy link
Copy Markdown

PR:fix(installer): 停服等待 + 复制后校验,杜绝「半安装」

问题:升级会静默产出「旧二进制 + 新版本号」

升级路径只 ExecWait 一次 WeaselServer.exe /quit(install.nsi 原 L164),不验证进程确已退出;Upgrade 时甚至跳过复制前的停服(原 L213-216)。server 仍在运行时,WeaselServer.exe / rime.dll / WinSparkle.dll 被锁,SetOverwrite try(原 L218)静默跳过这三个文件,随后注册表照写新 DisplayVersion——安装器自报成功、磁盘上仍是旧二进制。

本机实测(Windows 10.0.26200,0.17.4.98 nightly)

  • 10-31 与 11-14 两次安装后,安装目录 21 个文件里恰好只有 server 运行时加载的 3 个模块保持 2025 年版本(WeaselServer.exe 2025-06-04、rime.dll 2025-02-16、WinSparkle.dll 2025-06-04),其余 17 个全部更新;
  • 注册表 DisplayVersion 已写为 0.17.4.98,二进制仍是 0.17.4(2025-06-04);
  • 11-14 重装 13 分钟后,TSF 宿主 SearchHost.exe 连崩 4 次 0xc000041d(STATUS_FATAL_USER_CALLBACK_EXCEPTION,Application 日志 1000,%LOCALAPPDATA%\CrashDumps 有 4 个 dump);
  • 旧 server 配新 client DLL 正是 IPC 异常链的温床(见 fix(WeaselIPC, WeaselTSF): 防止 IPC 解析/反序列化异常逃逸出 TSF 回调导致 0xc000041d #1983 的机制分析与本机 WER 证据)。

修复

  1. StopWeaselServer(安装器与卸载器各一份):/quit 之后按镜像路径轮询进程是否真的消失(10s 优雅窗)→ 仍在则按路径强杀 → 再等 3s → 仍停不下来就中止安装(繁/简/英三语提示,静默模式同样中止)。见下方「为什么不用 rename 探测」。
  2. Upgrade 不再跳过停服:原 $0 != "Upgrade" 条件删除,每次安装前都执行停服。
  3. 每个关键二进制的 File 都当场检查错误标志:关键二进制区段用 SetOverwrite on,并由 !macro FileCritical 在每个 File 之后立即检查 ${Errors}——晚一步检查会被后续命令掩盖。六个文件:WeaselServer.exe、WeaselDeployer.exe、rime.dll、WinSparkle.dll、weasel.dll、weaselx64.dll(x64 时)。ARM64 专属的三个 DLL(weaselARM/ARM64/ARM64X)走 FileCriticalNonfatal:源文件缺席仍只是编译警告(非 ARM 构建正常现象),但打包了却写不进去同样记入失败清单。
  4. 写入成功即内容保证:File 成功 = 该文件字节确实来自本安装包,因此不再需要事后 rename-probe 或另行哈希比对;旧的 probe 只能证明「此刻没被占用」,证明不了内容,已移除。
  5. 关键文件缺失一律失败:VerifyCriticalBinaries 对缺失项也记入失败清单并中止;旧逻辑对缺失直接跳过,等于「文件根本没装上也算通过」。
  6. 系统目录 IME 副本同样校验:WeaselSetup 会把 weasel.dll 拷进 System32(x64 版)与 SysWOW64,这两份才是宿主进程真正加载的 DLL。新增 VerifySystemImeDlls 比较系统副本与 $INSTDIR 新装二进制的体积(32 位安装器经 Sysnative 访问真实 System32)。
  7. 不再丢弃 WeaselSetup.exe 退出码:注册/拷贝失败时直接中止安装(静默模式同样中止),避免「系统里 IME DLL 仍旧、注册表已是新版本」。
  8. 卸载器同样先停服再删文件。

设计取舍

  • 为什么不用 rename 探测进程:Windows 只禁止对运行中镜像写入与删除,改名是允许的(本机实测:进程存活时对其自身 exe 执行 Rename-Item 成功)。所以「rename 成功 = 进程已退出」这个前提不成立,用它会得到假阳性——服务器还在跑却判定已退出,优雅等待与强杀分支全成死代码,卸载路径也照旧删不掉被锁文件。现在改为按镜像路径查询进程存在性(Get-CimInstance Win32_Process 过滤 ExecutablePath),以 helper 的退出码为唯一判据。
  • 为什么不做哈希:File 成功后磁盘上的字节就是安装包里的字节(NSIS 自己写下去的),哈希只能重复验证刚写入的内容,无法覆盖真正的失败模式——被锁跳过。真正的判别信号是「写入是否成功」,所以把 SetOverwrite on + 逐条错误检查放在第一位。若维护者希望再加一层抗介质损坏的校验,可在构建期生成 SHA-256 清单并由运行时 powershell Get-FileHash 比对(需 CI 配合,属可选加固)。
  • 为什么系统目录副本只用体积比对:那两份由 WeaselSetup.exe(C++,copy_file)负责拷贝,NSIS 拿不到它的写入错误标志;可用信号是「退出码 + 目标文件是否存在 + 与源文件体积一致」。源文件刚刚经 File 成功写入,等价性由拷贝动作本身保证。同尺寸旧构建确实无法被体积区分,SHA-256 属可选加固(同上)。
  • 强杀作用域:taskkill /IM 会连另一个目录下的 Weasel 一起杀,改为按 ExecutablePath 过滤,只作用于本安装目录的实例。
  • 失败策略是显式中止而非带病继续:宁可安装失败让用户手动结束进程重试,也不产出半安装状态。
  • SetOverwrite on 与 try 的真实差异(更正早期说法):try 跳过被锁文件时同样会置错误标志(NSIS exec.c:overwriteflag==2 时 exec_error++),所以单就「能检测到失败」而言两者都够。on 的价值在于交互式安装会给用户 Retry 选项(关掉占用程序后当场继续),try 则静默跳过、只能事后统一报错中止。选 on 是体验取舍,不是正确性要求。

二轮 review 修正

review 指摘 处置
卸载段调用普通 Function 是编译期错误:NSIS 把安装器/卸载器编成两个独立程序,卸载段只能调用 un. 前缀函数;原版直接在 Section "Uninstall" 里 Call StopWeaselServer,makensis 报 Call must be used with function names starting with "un." in the uninstall section,安装包根本产不出来 改为 !macro StopWeaselServerDef UN 一个宏体、!insertmacro 两次生成 StopWeaselServer 与 un.StopWeaselServer;卸载段改 Call un.StopWeaselServer。负对照已验证:改回裸 Call 立即复现该编译错误
rename 探测是假阳性(见「设计取舍」第 1 条) 删除 rename-probe,改为按镜像路径的进程存在性轮询
测试断言方向反了:Phase 2 刚把三个文件替换成 7z.exe,紧接着却用要求「完全一致」的 Compare-BinaryState 去比对,必然在重装前抛异常;真正该断言的「必须不同」反而在不可达的下一行 改为断言三个伪造文件都必须与全新安装不同(覆盖全部三个文件,原来只有 WeaselServer.exe 有这项检查)
Phase 3 的 DisplayVersion 断言不可满足:升级路径会先跑旧版卸载器删掉注册表键,所以中止后 DisplayVersion 必然为空,「前后不变」永远不成立 改为「中止后不得写回任何 DisplayVersion」——这才是该阶段真正要保证的
FileCritical 注释称 try 不置错误标志 已按 NSIS 源码更正(见「设计取舍」末条)
ARM64 专属 DLL 在保护范围之外 纳入 FileCriticalNonfatal

验证

  • 编译(本机实跑):NSIS 3.13 makensis 全量编译 output/install.nsi → 成功产出安装包,仅 4 个预期内 /nonfatal 警告(ARM DLL ×3、data\*.gram,均由本构建环境未打包这些文件所致)。负对照:卸载段改回裸 Call 立刻复现 un. 编译错误。
  • 内嵌 helper 转义:makensis -V4 会回显每个 FileWrite 解析后的最终字符串,逐行核对与手工展开的脚本一致;$$ 在运行时字符串表中确实折叠为单个 $(用无压缩构建的 exe 直接读字符串表确认)。
  • 停服逻辑行为(干净机器实跑,4 个用例):
    1. 无匹配进程 → 立即 exit 0;
    2. 匹配进程在跑 → 走满 10s 优雅窗后强杀,实测 elapsed_ms≈10140,残留 0,exit 0;
    3. 另一个目录下的 WeaselServer.exe 在跑、目标路径无进程 → helper exit 0,别路径实例存活(路径隔离生效);
    4. 同 3 但目标路径指向别处 → 仍然只判自己的路径,exit 0,别路径实例不受影响。
  • 升级语义(CI,本 PR 新增):test/TestWeaselHalfInstall.ps1,接在既有 TestWeaselUpgrade.ps1 之后(ci.yml 新增 step,matrix.variant == 'msbuild'),在一次性 runner 上真实安装并断言:
    1. 陈旧二进制必须被换回:先全新安装并记录关键二进制的 PE TimeDateStamp + 体积,再用另一个 PE(7z.exe)覆盖 WeaselServer.exe/rime.dll/WinSparkle.dll(正是证据里的三个),先断言三者确实已不同,重装后必须回到记录的数值——静默跳过就会失败;
    2. 锁定关键文件必须中止:以 FileShare::None 独占打开 rime.dll,重装必须返回非零,且不得写回 DisplayVersion;释放后再装必须成功;
    3. 运行中的 server 必须先被停掉:记录 server 的 pid,重装后该 pid 必须已消失。
    • 安装器收尾会自己拉起 server,而 server 恰好握着被测文件,所以每个阶段先用镜像路径把它停掉。
  • 静态预检:改动的 .ps1 过 [Parser]::ParseFile + PSScriptAnalyzer -Severity Error,零命中。
  • 与 fix(WeaselIPC, WeaselTSF): 防止 IPC 解析/反序列化异常逃逸出 TSF 回调导致 0xc000041d #1983 的关系:fix(WeaselIPC, WeaselTSF): 防止 IPC 解析/反序列化异常逃逸出 TSF 回调导致 0xc000041d #1983 在宿主/IPC 边界兜底(崩了不拖死宿主);本 PR 消除半安装这一根因源头。两者正交,建议独立合入。

关于「关键二进制」范围(补充说明)

初版只校验 $INSTDIR 下 5 个文件,未覆盖 System32 / SysWOW64 的 IME 副本,这是本轮补上的缺口。两点实测事实支撑当前做法:

  • 这两份本机实测(2026-11-17)与 $INSTDIR 新装副本字节一致(System32\weasel.dll == weaselx64.dll,SysWOW64\weasel.dll == weasel.dll,SHA-256 完全一致),说明 WeaselSetup 的 copy_file() 有 MoveFileEx 改名兜底,加载中的 DLL 也能换掉——这正是 NSIS File/SetOverwrite try 缺失、导致 WeaselServer.exe 等 3 个文件变陈旧的差别所在;
  • 兜底若也失败,WeaselSetup 会返回非零,而旧代码 ExecWait 丢弃退出码——所以「退出码 + 系统副本体积」两道校验一起加。

实现形态说明

停服逻辑以 !macro StopWeaselServerDef UN 定义一次、展开两次,而不是写成两个手抄的 Function:NSIS 的 label 是函数内局部的,两份副本不会冲突;而安装器与卸载器是两个独立程序,卸载器只能调用 un. 前缀函数,因此必须真的有两份实现。宏保证两份实现逐字同步,改一处不会漏改另一处。

关联

Upgrades only ran one unverified `WeaselServer.exe /quit` and skipped it
entirely on the Upgrade path; with the server still alive, `SetOverwrite
try` silently skipped the locked binaries (WeaselServer.exe, rime.dll,
WinSparkle.dll) while the registry still claimed the new DisplayVersion.

Machine evidence (Windows 10.0.26200, 0.17.4.98 nightly install):
- install dir had 21 files, exactly the 3 modules loaded by the live
  server remained from 2025-06-04 after two installs (10-31, 11-14)
- 13 minutes after the 11-14 reinstall the TSF host SearchHost.exe
  crashed 4x with 0xc000041d (fatal user callback exception)

Changes:
- StopWeaselServer macro: /quit, bounded rename-probe polling (~10s),
  taskkill force kill, second bounded wait, abort with localized
  message if the server still cannot be stopped (silent mode included)
- the pre-copy stop now runs on every install, including Upgrade
- VerifyFreshBinaries after the File copies: rename-probe the five
  critical binaries; a failed probe means the copy was skipped, so the
  installer aborts with a localized stale-file list instead of writing
  a new DisplayVersion over stale binaries
- uninstaller uses the same stop logic before deleting files
… result

WeaselSetup copies weasel.dll into System32 and SysWOW64; those are the
copies every host process actually loads, so they are the IME surface where
a stale build hurts most. Two gaps remained:

- ExecWait discarded WeaselSetup.exe exit code, so a failure to register or
  copy the IME DLLs was ignored and the installer kept going and wrote the
  new DisplayVersion anyway
- nothing verified System32/SysWOW64 actually received the new build

Now the exit code aborts the install (silent mode included), and
VerifySystemImeDlls compares the size of System32\\weasel.dll against
$INSTDIR\\weaselx64.dll and SysWOW64\\weasel.dll against $INSTDIR\\weasel.dll
(a 32-bit installer reaches the real System32 through Sysnative).

Also converted the three helpers from macros to Functions: NSIS labels are
file-scoped, so the stop macro expanded three times would have collided on
its loop labels and failed to compile.
The rename probe uses a fixed ".weasel-lockprobe" suffix. A probe file left
behind by an interrupted run (crash, power loss) would make Rename fail with
"destination exists", which the probe cannot distinguish from "file still
locked" - the installer would then wait, force-kill, and abort on a healthy
installation. Delete the probe path first so the probe only ever reports the
lock state.
Review finding: the rename probe only proved "nothing holds the file right now",
never "the bytes on disk came from this package", so it could pass on a
half-installed tree. Reworked:

- set SetOverwrite on around the critical binaries: with "try" NSIS skips a
  locked destination silently and does NOT set the error flag, which is how
  the half-installs this PR fixes were produced
- check the error flag right after each critical File (via FileCritical),
  so a later command cannot mask an earlier failure; every failure is
  collected and listed at once
- a successful File writes this package bytes, so success is the provenance
  guarantee; the probe and its rename-side effects are gone
- missing critical binaries now fail the install instead of being skipped
- WinSparkle.dll added to the checked set: the PR own evidence names it as
  one of the three files that stayed stale, so it belongs on the list
- force-kill is path-scoped through a generated PowerShell script
  (Get-Process | Where Path -ieq exe | Stop-Process) instead of
  taskkill /IM, which would also kill a Weasel installed elsewhere
@takomitkm
takomitkm force-pushed the installer/anti-half-install branch from 942b429 to 4c4703c Compare November 17, 2026 07:33
… is stopped

The existing upgrade test installs, upgrades and uninstalls on a disposable
runner, but never asserts what this PR changes. Add a test that does:

- fresh install, then record the PE timestamp + size of every critical
  binary as the expected state
- overwrite WeaselServer.exe / rime.dll / WinSparkle.dll with a different
  PE binary (the three files the PR evidence names) and reinstall: the
  files must come back byte-wise identical, which fails if the installer
  silently skips them
- hold rime.dll open with FileShare::None and reinstall: the installer must
  exit non-zero and leave DisplayVersion untouched, then succeed again once
  the handle is released
- start WeaselServer and reinstall: the recorded pid must be gone afterwards

The installer starts a server when it finishes and that server holds the
files under test, so each phase stops it by image path first.
@takomitkm

Copy link
Copy Markdown
Author

建议合并后的测试入口是:
if (handshake_only) {
test_10();
test_11();
test_12();
test_13();
test_14();
} else {
test_1();
test_2();
test_3();
test_4();
test_5();
test_6();
test_7();
test_8();
test_9();
test_10();
test_11();
test_12();
test_13();
test_14();
}

否则可能出现测试文件已经包含了 #1983 的新用例,但全量执行入口没有调用它们的情况。

@takomitkm
takomitkm marked this pull request as draft November 22, 2026 16:23
…sertions

- StopWeaselServer: define one body via !macro StopWeaselServerDef for both
  the installer and the uninstaller (un. prefix). Calling a plain function
  from the uninstall section is a makensis compile error, so the previous
  single-function version never produced an installer at all (CI never ran:
  fork PR workflows need maintainer approval, all runs stayed action_required).

- Replace the rename lock-probe with process-existence polling by image
  path: Windows allows a running executable's file to be renamed (only
  writes and deletes are denied), so a successful Rename did not prove the
  process had exited. The embedded helper waits up to 10s for path-matched
  WeaselServer processes to exit, force-kills them, waits up to 3s more,
  and its exit code decides between continuing and aborting. Verified on a
  clean machine: no-process exit 0; running server killed after the
  graceful window with 0 left; a WeaselServer at a different path is never
  touched.

- FileCritical comment: try mode does set the error flag when it skips a
  locked file (nsis exec.c does exec_error++ for overwriteflag==2); the
  real difference of on is the interactive Retry dialog. Reworded.

- ARM64-only DLLs (weaselARM/ARM64/ARM64X) now go through
  FileCriticalNonfatal so a write failure is recorded instead of being
  silently skipped on ARM64 machines.

- TestWeaselHalfInstall.ps1: stale fixtures are now asserted to DIFFER
  from the fresh install (the old code compared for equality right after
  replacing the files, so it threw before reinstalling); the equality
  check covers all three sabotaged files. Phase 3 no longer asserts
  DisplayVersion equality across the upgrade uninstall, which clears the
  registry key; it asserts nothing was written back instead.
@takomitkm

Copy link
Copy Markdown
Author

二轮修正已推送(0d50651)

review 指出的三个问题全部修复,另外补了两处:

  1. un. 作用域:StopWeaselServer 现由 !macro StopWeaselServerDef UN 定义一次、展开两次(StopWeaselServer + un.StopWeaselServer),卸载段改 Call un.StopWeaselServer。此前版本在卸载段裸调普通函数是 makensis 编译期错误,安装包根本产不出来。
  2. 探测机制替换:rename-probe 删除——Windows 允许改名运行中的可执行文件(只禁写入/删除),「rename 成功 = 进程退出」不成立。改为按镜像路径轮询进程存在性(Get-CimInstance Win32_Process 过滤 ExecutablePath),10s 优雅等待 → 按路径强杀 → 再等 3s,退出码裁决。
  3. 测试断言方向:Phase 2 改为断言三个伪造文件必须与全新安装不同(原版刚替换完就要求「完全一致」,必炸);Phase 3 的 DisplayVersion 前后相等断言不可满足(升级路径先删注册表键),改为断言中止后没有写回任何版本号。
  4. ARM64 专属 DLL 纳入 FileCriticalNonfatal,写入失败不再被静默跳过。
  5. FileCritical 注释更正:try 跳过时其实也置错误标志(NSIS exec.c 对 overwriteflag==2 做 exec_error++),on 的真实差异是交互式安装提供 Retry。

验证记录

  • makensis 3.13 全量编译通过,产出安装包(仅 4 个预期内 /nonfatal 警告);负对照:卸载段改回裸 Call 立即复现 Call must be used with function names starting with "un." 编译错误。
  • 停服逻辑在干净机器上跑了 4 个行为用例:无进程立即 exit 0;运行中实例走满优雅窗后被强杀、残留 0;另一目录的 WeaselServer 全程存活(路径隔离正确)。
  • 内嵌 helper 的 NSIS 转义经 -V4 编译回显逐行核对,$$ 运行时折叠为 $ 已用无压缩构建实测确认。
  • 改动的 .ps1 过 [Parser]::ParseFile + PSScriptAnalyzer(Error 级零命中)。

一点请求:这个 PR 来自 fork,CI workflow 一直停在 action_required(需要仓库成员手动批准),所以之前的编译错误没机会被 CI 抓到。如果 @rime/weasel 的维护者方便的话,请在 Actions 页对这个 PR 的 workflow run 点一次 Approve and run,让新测试(TestWeaselHalfInstall.ps1)和 makensis 编译真正跑起来。

正文已就地更新,修正是逐项列在「二轮 review 修正」表里。

WeaselServer.exe /quit is a synchronous named-pipe client: PipeChannel's
_Connect() waits in WaitNamedPipe() with no overall deadline, and
ShutdownServer() blocks on a response with no timeout. With ExecWait the
installer hung behind that child before the PowerShell helper could reach
its force-kill, so the whole anti-half-install guard was bypassable.

- Launch /quit with Exec (fire-and-forget); the helper now owns the full
  10s graceful + kill + 3s recheck budget.
- Add test Phase 5: a WeaselServer.exe stub that sleeps forever on both
  no-args and /quit, proving the installer kills it and finishes within
  45s instead of waiting on the stuck client forever.
nsExec has no default wait timeout. If PowerShell or its WMI query hangs before the helper reaches its own deadlines, the installer would wait forever. /TIMEOUT=20000 kills the process and returns the literal 'timeout', which the existing non-zero check already treats as a failure and abort.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant