Skip to content

fix(WeaselIPC, WeaselTSF): 防止 IPC 解析/反序列化异常逃逸出 TSF 回调导致 0xc000041d - #1983

Draft
takomitkm wants to merge 8 commits into
rime:masterfrom
takomitkm:fix/ipc-exception-hardening-0xc000041d
Draft

takomitkm wants to merge 8 commits into
rime:masterfrom
takomitkm:fix/ipc-exception-hardening-0xc000041d

Conversation

@takomitkm

@takomitkm takomitkm commented Nov 15, 2026 •

Copy link
Copy Markdown

PR:fix(WeaselIPC, WeaselTSF): 吞掉 IPC/TSF 边界上的 C++ 异常,避免 0xc000041d 拖死宿主

查重已完成(两轮):同仓库 issue/PR 已搜,含 #1304 / #1857 / #1952 / #815 / #1883 / #1914 / #1949 / #1962 / #1798 等。本 PR 是 #1304 的防御性补强,不是首次发现;与已开 #1914 互补不重复。


概述

weasel.dll(in-proc TSF)在焦点切换 / 输入法激活时把宿主程序(Firefox、SearchHost、explorer 等)拖崩,异常码 0xc000041d(STATUS_FATAL_USER_CALLBACK_EXCEPTION)或 0xc0000008。issue:#1857(OPEN,切换崩)、#1952(OPEN,0.17.4 候选窗 NPD)、#815(0xc000041d 先例,已关 not_planned)。

这是 #1304 的补强,不是另起炉灶

本 PR = 把 #1304 的收口做宽、做彻底,并去掉那个阻塞模态框(#1949 的回退源),再加一层最外层边界 catch(Ronifue/#1883 的做法)。

根因(源码闭合)

  1. WeaselIPC 不做版本校验:in-proc TSF 客户端 weasel.dll 与 out-of-proc WeaselServer.exe 走单命名管道,无构建号握手(IPCMetadata 无 version 字段)。
  2. 半安装 → 两套 half 不一致:正常升级若没停老 WeaselServer.exe(安装脚本 Upgrade 路径跳过 /quit),或 SetOverwrite try 静默跳过被锁文件,老服务端就会和新客户端同管。
  3. 响应是 boost 反序列化的文本,异常是 std::exception 而非 DWORD:ClientImpl::_SendMessage 只 catch (DWORD);include/PipeChannel.h 的 HandleResponseData(_TyHandler const& handler) 无 try/catch,直接 handler((LPWSTR)buffer, size) → ResponseParser::Parse → Deserializer::Store → WeaselIPCData.h 的 ar & data。布局/ schema 错配即抛 boost::archive::archive_exception(是 std::exception,不是 DWORD)。
  4. 异常逃逸出 TSF/COM 回调 = 致命用户回调异常:该异常一路逃出 WeaselTSF::DoEditSession,从宿主 UI 线程的 TSF 编辑会话回调里 unwind → 系统抛 STATUS_FATAL_USER_CALLBACK_EXCEPTION (0xc000041d),杀掉宿主进程。

运行时佐证:抓取到的 rime.weasel 服务端日志干干净净(无 pipe/connect/exception 错误串)——服务端一直正常,崩在客户端那条响应解析路径上,与上面的源码链一致。

为什么不是 #1914

#1914 让跑在宿主线程上的客户端 IPC 有界等待(fail-fast + 超时),解决的是「服务端卡住时宿主 UI 线程被 WaitNamedPipe/ReadFile 死等」的卡死。它不捕获「连上了但响应解析失败」的情况——而版本错配正是后者。两者正交、互补。本 PR 不重复 #1914 的工作。

改动(具体、可落地,5 处就地修改)

1. WeaselIPC/Deserializer.h — TryDeserialize(补 #1304 的缝)

  • 把 catch (const boost::archive::archive_exception& e) → catch (...),吞掉一切反序列化失败。
  • 删除 catch 里的 MessageBoxA(NULL, msg.c_str(), "IPC exception", MB_OK | MB_ICONERROR)(出现IPC Exception弹窗 #1949 的回退源;阻塞模态框跑在宿主 UI 线程上绝对不能要)。
  • 注释说明:版本/ABI 错配时让异常在宿主 UI/TSF 回调之外被吞掉,不要弹框。

2. WeaselIPC/ContextUpdater.cpp — _StoreCand(补 #1304 没兜住的构造异常)

3. WeaselIPC/Styler.cpp — Styler::Store(同上)

  • 同样把 ss/ia 构造 + TryDeserialize(ia, sty) 包进 try { ... } catch (...) { return; },错配时保留样式不变。

4. include/PipeChannel.h — HandleResponseData(补 #1304 没覆盖的解析入口)

  • 把 handler((LPWSTR)buffer, size) 调用包进 try { return handler(...); } catch (...) { return false; }。
  • 这里 handler 就是 ResponseParser,版本/ABI 错配时它内部会抛,绝不外泄到调用方(宿主 UI 线程)。

5. WeaselTSF/EditSession.cpp — DoEditSession(最外层边界 catch,Ronifue/#1883)

  • 把整个 DoEditSession(TfEditCookie ec) 函数体包进 try { ... } catch (...) { return TRUE; }。
  • 编辑会话回调里抛异常会被 TSF 管理器(msctf)当作致命用户回调异常,直接 0xc000041d 崩宿主;这里兜住后,畸形 IPC 响应最多让当次更新失效,不会再拖死 app。

刻意不改(及原因)

  • PipeChannel::Transact / _ReceiveResponse:已有 ClientImpl::_SendMessage 的 catch(DWORD) 与第 4 项的 HandleResponseData try/catch 兜底,不在崩点上,按最小改动原则不动。
  • WeaselTSF.cpp 里 ActivateEx 等其余 TSF 回调:本 PR 只包最具体的崩点 DoEditSession(小狼毫使得有一部分游戏(Helldivers 2)和应用(网易 UU 加速器)闪退崩溃,分析得是 weasel.dll 在部分应用中触发 C++ 异常崩溃导致 #1883 的 WinDbg 栈指向它)。更宽的「所有 TSF 入口包 try」是可选后续,fxliang 也提过「ipc 异常直接关输入法可能更好」——这涉及 svc 生命周期语义,留给单独讨论,保持本 PR 纯防御、可独立合入。
  • 版本握手 / 安装器半安装修复:是根因的源头,但属更大的 server+client 协同改动与 installer 逻辑,列为后续 hardening,不混进本防御性 PR。
  • DoEditSession 的 catch 不做回滚(已知限制):异常发生时,try 块内已经执行的 TSF 副作用(组合已开始/结束、文本已插入、语言栏与候选窗已更新)都保持原样,本地状态可能与刚提交的文本不一致,要等下一个 edit session 重新同步。这是有意取舍——宿主存活优先于 IME 状态自洽。按阶段验证异常恢复行为属后续工作:需要真实 ITfContext / TSF mock 才能在「某一步之后」注入异常,当前轻量测试工程(TestResponseParser)不具备该能力,因此本 PR 只保证异常不逃出 TSF 回调边界,不保证异常后状态自洽。
    • 半安装实锤(本机验证,2026-11-17):output/install.nsi 升级路径只 ExecWait 一次 WeaselServer.exe /quit(L164),不验证进程确已退出;Upgrade 时甚至跳过复制前的第二次 /quit(L213-216);随后 SetOverwrite try(L218)对被锁文件静默跳过。本机 10-31 与 11-14 两次安装后,安装目录 21 个文件里恰好只有 server 运行时加载的 3 个模块(WeaselServer.exe 2025-06-04、rime.dll 2025-02-16、WinSparkle.dll 2025-06-04)未被覆盖,而注册表 DisplayVersion 已写为 0.17.4.98——安装器自报成功、二进制未换;11-14 重装 13 分钟后宿主 SearchHost.exe 连崩 4 次 0xc000041d。
    • 处置:安装器修复属独立改动,将在单独 PR 提交(要点:kill 等待/重试直到进程退出 + 复制后校验关键二进制时间戳 + 失败时显式报错),本 PR 保持纯防御边界不动。

验证

  • CI(已跑):临时探针 run 43762059489 在 windows-2022 上以 Debug x64 构建 TestResponseParser 并执行全部 9 个用例,结果 No errors detected.(exit 0)。
    • review 补充 test_10(现名 truncated_candidate_transaction_commits_nothing)后,run 44038443693 复跑全部 10 个用例:构建 0 Error(s),运行 No errors detected.(exit 0)。
    • 覆盖:畸形 ctx.cand 保留旧 cinfo、畸形 style 保留旧样式、HandleResponseData 吞掉 handler 异常、ctx.cand 走真实序列化 CandidateInfo 协议。
    • 说明:本 PR 在 rime/weasel 的 CI 因首次贡献者需维护者批准而处于 action_required;探针分支执行的是与 .github/workflows/ci.yml 新增步骤相同的命令。
  • 安装包(已构建):run 43757573434 成功产出 weasel-0.17.4.103.36727e2-installer.exe(SHA-256 E05BBF1DDA9B6D21B2574A138413296EE14C4052A01ADF59E2DED3211CE0B84C)。
  • 真机(待校机用户执行):安装上述构建后,故意把老 WeaselServer.exe + 新 weasel.dll(或反之)混装:
    • 改前:任意程序焦点切换 / TSF 激活 → 宿主 0xc000041d 崩。
    • 改后:输入法仅「无响应 / 不显示」,宿主存活,且不会弹 MessageBoxA 阻塞框。
  • 单测(已落地):HandleResponseData 喂会抛异常的 handler,断言返回 false 且不抛;_StoreCand/Styler::Store 喂畸形 payload,断言保留旧状态。
    • TryDeserialize 本身不是事务:它直接对调用方对象执行 ia >> t,中途失败时该对象可能已被部分写入。事务性由调用端的「临时对象 + 成功才提交」保证——ContextUpdater::_StoreCand / Styler::Store 都是先解析到副本、成功才赋值。
    • test_10(现名 truncated_candidate_transaction_commits_nothing)专门验证这一点:把一份真实序列化的 CandidateInfo(6 个候选)在候选列表中段截断(切点已过归档头,前缀成员已读入),再走 ctx.cand= 真实分发路径,断言 cinfo 与调用前完全一致——若没有临时对象提交,这些已读成员会先污染 cinfo。
  • 真机 WER 证据(本机,Windows 10.0.26200,Weasel 0.17.4.0,ReportArchive 元数据;无 dump):
    • 2026-05-07 APPCRASH:故障模块 amdxx64.dll(AMD 显卡驱动 32.0.31007.1017),异常 c0000005,偏移 0xd0c62。
    • 2026-05-18 APPCRASH:amdxx64.dll(同驱动缺版本资源),异常 c0000005,偏移 0xd0c62 —— 与上次同一偏移,稳定复现的驱动崩溃点;宿主侧表现为 0xc000041d(STATUS_FATAL_USER_CALLBACK_EXCEPTION:user32/win32k 回调内异常直接判死宿主)。
    • 2026-07-13 APPCRASH:故障模块 rime.dll 1.13.1.0,异常 c0000005,偏移 0xb70e4 —— 服务进程崩死,宿主 TSF 端收到截断的管道数据,落入本 PR 加固的 text_wiarchive 异常链。
    • 2026-08-14 BEX64:rime.dll 1.13.1.0,异常 c0000409(fail-fast,任何 try/catch 不可拦截)—— 只杀服务进程(输入临时失效),不拖死宿主;与本 PR「临时 IME 失败可接受」的边界一致。
    • 结论:驱动侧崩溃不在 IME 代码可修范围;rime.dll 侧崩溃导致的服务死亡正是宿主侧 IPC 解析异常链的实测来源,支持本 PR 的防御点。
    • 时间线说明:上述 WER 记录均为 2026-10-31 重装前的存档(此后本机 WER 无新的 WeaselServer 记录)。触发本 PR 的宿主崩溃报告(BuildID 2026-11-04,AMD 驱动 32.0.32015.7029)为宿主应用自身的 crash reporter 格式,不经 WER 的 AppCrash_WeaselServer.exe 归档,故不在上表内;本表作用是证实「服务侧 rime.dll 崩溃 → 截断管道数据 → 宿主侧 IPC 解析异常链」这一机制在本机成立过,而非复现 11-04 那次事件本身。

关联

给受影响用户的话

今天最稳的解法是干净重装同一个一致构建(System32 的 weasel.dll 与 Program Files 的 WeaselServer.exe+rime.dll 都换、先停老服务)——见 weasel-recover-checklist.md。本 PR 让即便发生错配也只降级为「无响应」而非崩宿主。

takomitkm and others added 3 commits November 15, 2026 14:43
Follow-up to rime#1304. Serialization/deserialization exceptions can still
escape into a Windows callback and take down the host process
(0xc000041d, an unhandled C++ EH exception delivered to msctf), and
rime#1304's own MessageBoxA can block the host thread (rime#1949). Wrap the
remaining deserialization sites so a version/ABI mismatch between
WeaselServer.exe and weasel.dll is handled gracefully instead of
crashing or blocking the caller:

- WeaselIPC/Deserializer.h: use a silent catch(...) in TryDeserialize
  instead of a modal MessageBoxA.
- WeaselIPC/ContextUpdater.cpp (_StoreCand): on exception, leave the
  candidate list unchanged and return.
- WeaselTSF/WeaselIPC/Styler.cpp (Store): on exception, leave the style
  unchanged and return.
- include/PipeChannel.h (HandleResponseData): return false on exception.
- WeaselTSF/EditSession.cpp (DoEditSession): swallow any exception and
  return TRUE, since an exception out of an edit-session callback
  crashes the host process with 0xc000041d.
…lure

TryDeserialize previously swallowed every exception and returned void, so its
callers could not distinguish a failed parse from a successful one. When
`ia >> t` threw mid-flight, the target was left half-updated and the caller's
outer catch never fired, so partial CandidateInfo/UIStyle data was published
into the TSF callback.

- TryDeserialize now returns bool (true on success, false on any throw) instead
  of silently swallowing the failure.
- _StoreCand and Styler::Store deserialize into a temporary and commit it to
  the real target only on full success, leaving the previous state untouched on
  failure.

This replaces the earlier "swallow-and-hope" behaviour and is the transactional
fix requested during review of rime#1983 (follow-up to rime#1304).
Add narrow, non-modal OutputDebugStringW traces at the five catch boundaries
so a version/ABI mismatch is observable without the host-thread MessageBoxA
that caused issue rime#1949. Add five regression tests to TestResponseParser:

- TryDeserialize reports failure without mutating its target;
- a malformed ctx.cand payload is rejected without publishing partial state;
- a malformed style payload leaves UIStyle unchanged;
- a well-formed archive is still published;
- a throwing HandleResponseData returns false instead of propagating.

No production control flow changes: catch boundaries, return values and the
pre-existing DoEditSession return convention are left untouched.
@takomitkm
takomitkm marked this pull request as ready for review November 15, 2026 15:49
@takomitkm

takomitkm commented Nov 15, 2026 •

Copy link
Copy Markdown
Author

it makes me use en now hah, i wanna keep my env before fix all i met
给我炸飞了weasel一启动所有窗口都打不开,设置都只剩个框

- explicitly build TestResponseParser (Debug x64) in the msbuild matrix
- run it non-interactively by feeding a keystroke to system("pause")
- clang-format touched C++ files so the lint job stays green
test_4 fed ctx.cand.length/.0/.1, which ContextUpdater has not read since CandidateInfo moved to a single serialized ctx.cand value. The test therefore asserted candidates that were never parsed and would fail as soon as it was actually executed. Serialize a CandidateInfo and feed it through ctx.cand, keeping the preedit/cursor assertions.
takomitkm added a commit to takomitkm/weasel-0.17.4fix-AIGC that referenced this pull request Nov 17, 2026
…t mismatch

A half-finished installer run can leave an old WeaselServer.exe next to a
freshly updated weasel.dll (locked binaries skipped under `SetOverwrite try`
while the registry still records the new DisplayVersion). The pair then
disagrees about the line-based text protocol, and whichever response shape
the older peer cannot parse turns into an archive exception on the client
side -- which, reaching a TSF callback, crashes the host (0xc000041d).

Make the pairing observable instead of silent:

- `WEASEL_IPC_PROTOCOL_VERSION` (1) names the text protocol revision and is
  the single place to bump when the `action=` keys or their value encodings
  change incompatibly.
- The server prepends `protocol.version=<n>` to every response header and
  also publishes the value to `HKCU\Software\Rime\Weasel\IpcProtocolVersion`
  at startup, so a mixed installation can be diagnosed without a debugger.
- `ResponseParser` tracks the line inline -- before any action deserializer
  is required -- parses it strictly, and reports a mismatch or an absent
  line through `OutputDebugStringW` / `DebugStream` only. It never shows a
  modal dialog (that regression is rime#1949) and never throws into the host UI
  thread.

Backward compatible in both directions: an old server sends no version line,
which the client reports as `(old server?)` and otherwise ignores; an old
client ignores the unknown `protocol.` action key.

Tests test_10..test_14 cover the tracked, verbatim, absent, malformed (x2)
and full `operator()` paths. They are numbered from 10 because rime#1983 already
occupies 5..9 in the same file; the two patches then stay trivially mergeable.
Review follow-up on two accuracy issues.

`TryDeserialize` is not transactional: it runs `ia >> t` on the caller's
object, so a body that fails part-way through can leave that object
half-updated. The atomicity comes from the call sites, which deserialize into
a temporary and commit only on success.

- test_5: state what it actually proves (this body is rejected on the first
  extraction) instead of attributing rollback to TryDeserialize.
- test_10: truncate a real serialized CandidateInfo inside the candidate list
  (past the archive header, trimmed back to a token boundary so the failure is
  a plain input-stream error) and assert _StoreCand leaves cinfo untouched.
  Without the temporary + commit-on-success those already-read members would
  have overwritten cinfo first.
- WeaselTSF/EditSession.cpp: document that the catch is deliberately not a
  rollback. TSF side effects already performed in the try block stay as they
  are, so local state can be inconsistent until the next edit session
  resynchronises it; host liveness is preferred over that consistency.
  Per-stage recovery behaviour needs a real ITfContext, which the lightweight
  TestResponseParser project cannot provide, so it stays follow-up work.
@takomitkm

Copy link
Copy Markdown
Author

Cross-PR note: #1985 added another test_10() in the same test file (protocol-version parsing vs. this PR's truncated-candidate transaction), so the two branches had a content conflict at that file. I renamed the cases added here to behaviour-based names (truncated_candidate_transaction_commits_nothing, etc.) and pushed them to this PR's head a76a864; the #1985 side was renamed too. A scratch merge of the updated tips now resolves cleanly with all cases registered. No functional change to the hardening itself.

@takomitkm

Copy link
Copy Markdown
Author

Integration check: a temporary probe merging both updated heads built TestResponseParser (Debug x64) and ran all 16 cases clean — No errors detected. (exit 0), run 45086048706. The probe branch has been deleted; both PR heads are unchanged.

@takomitkm
takomitkm marked this pull request as draft November 23, 2026 03:47
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