# 补丁编写与新版本适配指南 / Patch Authoring & Adaptation Guide 简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn) 这篇手册面向需要修改客户端(Quirrel 界面脚本、`aces.exe` 二进制指令、或 `wto_ws.dll` 局内 `LocalMP` 原生裁判模块)以及协助适配游戏新版本的开发者。 > **动手前的第一道自检**:请先阅读 [开发规范第 1 节](development-rules.md#architecture-zh),确认问题**确实无法**通过修改 `apps/server` 协议响应或下发原版任务/配置 BLK 字段解决。只有原版客户端真正缺失对应通路时,才编写客户端补丁。 --- ## 1. 第 0 步:只读拆包、查看二进制 BLK、反汇编定位与选型 请将原版客户端目录视为只读,不要直接修改其中的文件。利用仓库自带的 `@wto/vromfs`、`@wto/blk` 和 Python 静态分析工具 `tools/re/cli.py`,你可以在内存中直接查看原版脚本、配置与反汇编代码。 ### 1.1 一行命令读取原版 `.vromfs.bin` 中的 `.nut` 脚本或解码二进制 `.blk` 无需安装第三方解包器,在仓库根目录运行下面这段 Node.js 脚本(把 `<原版目录>` 换成你的官方客户端路径,只读不写): ```powershell # 示例 A:列出 gui.vromfs.bin 中匹配关键字的脚本路径,并直接打印某个 .nut 原文 node --input-type=module -e " import { readFileSync } from 'node:fs'; import { getFile, readArchive } from '@wto/vromfs'; const archive = readArchive(readFileSync(String.raw`<原版目录>\gui.vromfs.bin`)); console.log([...archive.files.keys()].filter((p) => p.includes('tutorial'))); console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8')); " # 示例 B:读取 char.vromfs.bin(或 aces.vromfs.bin)里的紧凑二进制 .blk 并格式化为可读文本 # (自动加载包内共享键名表 nm 与可选的 .dict 压缩字典) node --input-type=module -e " import { readFileSync } from 'node:fs'; import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk'; import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs'; const archive = readArchive(readFileSync(String.raw`<原版目录>\char.vromfs.bin`)); const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1]; const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : []; const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary }); console.log(formatBlkText(blk).slice(0, 2000)); " ``` ### 1.2 使用 `tools/re/cli.py` 对 `aces.exe` 做只读静态逆向定位 先按 [环境准备](contributing.md#zh-cn) 初始化 `.venv`(`pip install -e ./tools`)。随后即可直接在命令行查字符串交叉引用、查调用者、反汇编函数(**注意:所有地址参数均为十六进制 RVA,且务必显式传入 `--exe "<原版目录>\win64\aces.exe"`**): ```powershell # 1. 查找固定英文字符串在 .rdata 中的 RVA,以及所有通过 rip-relative lea 引用它的代码位置与所属函数 .\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "<原版目录>\win64\aces.exe" # 2. 查找所有以 rip-relative 方式读写某个全局变量 RVA 的指令 .\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "<原版目录>\win64\aces.exe" # 3. 查找所有直接 call 或 jmp 到目标函数 RVA 的调用点 .\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "<原版目录>\win64\aces.exe" # 4. 反汇编指定 RVA(默认打印 40 条指令,带字符串和调用注释;可传 --count、--end 或 --function 反汇编整函数) .\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "<原版目录>\win64\aces.exe" .\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<原版目录>\win64\aces.exe" ``` ### 1.3 选对客户端修改方式与通用编写规范 | 你要改什么 | 代码放哪里 | 真实参考例子 | | --- | --- | --- | | 修改机库/弹窗/结算界面脚本(Quirrel `.nut`) | `patches/gui/<领域>/<名称>/` | [`patches/gui/tutorials/immediate-save-skip-tutorial/`](../patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc) | | 改写 `aces.exe` 内寥寥几条跳转/比较指令或 `.rdata` 固定字符串 | `patches/exe/<领域>/<名称>/` | [`patches/exe/battle/allow-local-host-bot-spawns/`](../patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc) | | 用 C 语言写 MinHook 钩子补齐 `LocalMP` 局内裁判逻辑(`wto_ws.dll`) | `patches/native/<模块>.jsonc` + `native/wto-net/src/<模块>.c` | [`patches/native/local_mp_scores.jsonc`](../patches/native/local_mp_scores.jsonc) | | 改写 `network.blk`、`shop.blk`、`gui.blk` 等数据包静态配置 | `packages/patcher/src/`(**不放 `patches/`**) | `packages/patcher/src/char-pack.ts`、`main-pack.ts` | **所有 `patches/` 定义共享的四条基本约定**: 1. **一处独立行为对应一个目录/模块**,不在同一个补丁里顺手塞两件不相关的改动; 2. **`patch.jsonc` / `<模块>.jsonc` 顶部必须写三行英文注释**: - 第 1 行:这个补丁具体改了什么; - 第 2 行(`Why the client:` / `Why the exe:`):为什么本地服务器或原版配置解决不了; - 第 3 行(`Without it:`):如果不打这个补丁,玩家会遇到什么具体现象。 3. **`title` 与 `features` 统一写英文**(注:仓库内个别早期补丁保留了中文 `title` 历史遗留,**所有新增补丁请一律使用清晰的英文 `title`**),并优先复用现有的 `A-`..`K-` 功能标签(见 [核心概念词典第 7 节](README.md#glossary-zh)); 4. **唯一命中校验**:无论多少个 `variants`,对任意一个客户端版本**必须且只能有恰好 1 个 `variant` 命中(且单次定位全局唯一命中 1 处)**;0 命中或多处命中都会被补丁引擎安全拒绝,避免误写。 --- ## 2. GUI 补丁(`patches/gui/`)—— 完整三文件实例与严格 Schema 校验 ### 2.1 看一个完整的真实 GUI 补丁:`tutorials/immediate-save-skip-tutorial` 在原版 `scripts/tutorials/nexttutorialhandler.nut` 中,当玩家弹出「是否参加新手教程」询问框并勾选「不再询问」时,脚本调用 `saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)` 时没传第 3 个参数,默认走延迟 60 秒防抖的 `saveProfile()`——如果玩家勾选后在 60 秒内重启或崩溃退出,设置根本没发到服务端落盘,下次进机库弹窗又会冒出来。服务端无法替客户端缩短前端自己的 60 秒定时器,因此需要补上第 3 个回调参数 `@() save_profile(false)` 立即保存。 该补丁目录 `patches/gui/tutorials/immediate-save-skip-tutorial/` 下共有 **3 个文件**,完整内容如下: **① `patch.jsonc`**(注:此早期补丁保留了中文 `title`,你编写新补丁时请将 `title` 写为英文,如 `"Save tutorial opt-out immediately after ticking 'do not ask again'"`): ```jsonc // Save the tutorial opt-out immediately via save_profile(false). // Why the client: the stock callback waits 60 s before writing or sending anything to the service. // Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back. { "id": "tutorials/immediate-save-skip-tutorial", "title": "新手教程询问窗勾选「不再询问」后立即落盘保存", "features": [ "A-Tutorials" ], "variants": [ { "written_for": "2.61.0.37", "file": "scripts/tutorials/nexttutorialhandler.nut", "edits": [ { "find": "find.nut", "replace": "replace.nut" } ] } ] } ``` **② `find.nut`**(原版脚本中**最小且在目标文件内唯一出现 1 次**的原文,保留原始 4 空格缩进): ```squirrel skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) } ``` **③ `replace.nut`**(替换后的脚本片段): ```squirrel skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false)) } ``` ### 2.2 `gui-patch-definition.ts` 严格 Schema 白名单与编写细节(极易踩坑!) `packages/patcher/src/gui-patch-definition.ts` 会调用 `rejectUnknownKeys` 对每一层字段做严格白名单检查,**多写任何一个未定义字段都会直接抛出 `DefinitionError`**: - **顶层只允许 4 个键**:`"id"`、`"title"`、`"features"`、`"variants"`。 > **特别警告:GUI 的 `patch.jsonc` 没有 `"requires"` 字段!** 不要把 EXE 补丁里的 `"requires": []` 复制到 `patches/gui/` 里,否则加载器会当场抛错拒绝构建! - **`variants[]` 元素只允许 3 个键**:`"written_for"`、`"file"`、`"edits"`。其中 `"file"` 必须是 `gui.vromfs.bin` 内部**全小写、以 `/` 分隔且不带前导 `/` 的相对路径**(例如 `"scripts/tutorials/nexttutorialhandler.nut"`,注意原版归档内文件名全被转为小写!)。 - **`edits[]` 元素只允许 2 个键**:`"find"`、`"replace"`,值必须是**同一补丁目录下的纯文件名**(不允许包含 `/` 或 `\` 子路径)。 - **换行与唯一匹配规则**:读取 `.nut` 片段时会自动剥离 UTF-8 BOM、将 `\r\n` 归一化为 `\n`,并去掉文件末尾的**单个终止换行符**(因此 Git 自动换行转换不会破坏匹配);`find.nut` 的内容在目标脚本里必须**精确出现 1 次**(0 次或 ≥2 次均报错)。 - **本地服务地址占位符**:如果 `replace.nut` 里需要拼出本地服务器地址,直接写 `{{LOCAL_ENDPOINT}}`,构建副本时 `gui-pack.ts` 会自动替换成 `127.0.0.1:<实际端口>`。 - **跨版本演进**:如果新版本游戏修改了附近代码导致 `find.nut` 不再命中,**切勿直接覆盖旧片段破坏老版本兼容性**——新建 `find-58.nut` 与 `replace-58.nut`,在 `variants` 数组里追加一条 `"written_for": "<新版本号>"` 的记录即可。 - **必跑 `sq.exe` 字节码检查**:只要改过任何 `patches/gui/` 文件,提交前**必须运行**: ```powershell .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe" ``` 它会把补丁打在内存里的原版脚本上并调用 `sq.exe` 执行 `compilestring` 字节码编译,精准拦截与顶部 `from ... import *` 词法重名、未绑定函数前向引用以及误用 `base` 等保留字导致的进机库无限卡加载 Bug。 --- ## 3. EXE 补丁(`patches/exe/`)—— 57 字节完整逐指令解剖与进阶参考 当需要改动 `aces.exe` 内部某条分支判断或常量字符串时,我们使用 `@wto/exepatch` 的声明式补丁格式,做到**零硬编码地址、跨小版本自动重定位**。 ### 3.1 完整无省略实例:`patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc` 在 `LocalMP` 对局中,原版 `BotSystem::changeUnit` 在通过出生点检查后,会检查全局变量 `g_multiplayer` 是否为空(`cmp qword ptr [rip + disp32], 0`):单机试驾时 `g_multiplayer == NULL`,直接 `jz` 跳去调用 `Unit::changeAircraft` 刷出 AI;一旦处于 `LocalMP` 多人会话(`g_multiplayer != NULL`),零售客户端因为裁掉了专用服务器的脚本刷怪许可,落入后续分支只会打印 `"spawn denied by scripts"`,导致整场对局一辆 AI 载具都刷不出来。 下面是仓库中 [`patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc`](../patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc) 的**一字不差完整原文**(`pattern` 共 **57 字节**,无任何省略号): ```jsonc // Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer // null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e). // Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer // session the function only logs "spawn denied by scripts"; non-host sessions already return at its start. // Without it: no AI vehicle ever spawns in a LocalMP battle. { "id": "battle/allow-local-host-bot-spawns", "title": "Let BotSystem spawn AI vehicles on a LocalMP host", "features": [ "K-AI opponents and teammates" ], "requires": [], "variants": [ // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010) // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards. // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a). // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard. { "written_for": "2.61.0.37", "locate": { "method": "signature", "section": ".text", "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20", "captures": { "spawn_call": { "offset": 48, "type": "rel32" } } }, "edit": { "offset": 38, "asm": [ "jmp {spawn_call}", "nop", "nop", "nop", "nop", "nop", "nop", "nop", "nop", "nop" ], "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90", "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??", "fixups": [ { "at": 1, "type": "rel32", "target": "spawn_call" } ] } } ] } ``` ### 3.2 `+0..+56` 全部 57 字节逐指令拆解表 为什么 `edit.offset` 是 `38`?为什么 `spawn_call` 的 `offset` 是 `48`?为什么 `fixups[0].at` 又是 `1`?把这 57 个字节按 x86-64 指令逐条摊开,一眼就彻底明白了(以 `2.61.0.37` 命中起点 `site = 0x11b2c14` 为例): | 相对 `site` 偏移 | 长度 | `pattern` 中的十六进制字节 | 对应的 x86-64 反汇编指令 | 在补丁中扮演的角色 | | --- | --- | --- | --- | --- | | `+0 .. +6` | 7 B | `48 8b 05 ?? ?? ?? ??` | `mov rax, qword ptr [rip + disp32]` | 前置上下文锚点;`??` 通配随版本变化的全局变量 RIP 位移 | | `+7 .. +13` | 7 B | `48 8b 88 e0 03 00 00` | `mov rcx, qword ptr [rax + 0x3e0]` | 前置上下文锚点 | | `+14 .. +18` | 5 B | `48 8b 5c 24 20` | `mov rbx, qword ptr [rsp + 0x20]` | 前置上下文锚点 | | `+19 .. +21` | 3 B | `48 89 da` | `mov rdx, rbx` | 前置上下文锚点 | | `+22 .. +24` | 3 B | `4d 89 f0` | `mov r8, r14` | 前置上下文锚点 | | `+25 .. +29` | 5 B | `e8 ?? ?? ?? ??` | `call rel32`(出生点检查函数) | 前置上下文锚点;`??` 通配被调函数相对距离 | | `+30 .. +31` | 2 B | `84 c0` | `test al, al` | 前置上下文锚点 | | `+32 .. +37` | 6 B | `0f 84 ?? ?? ?? ??` | `jz rel32`(无可用出生点则提前返回) | 前置上下文锚点;确保我们不会覆盖到前面的合法返回分支 | | **`+38 .. +45`** | **8 B** | `48 83 3d ?? ?? ?? ?? 00` | `cmp qword ptr [rip + disp32], 0` | **被改写区第 1 条指令(起点 `edit.offset = 38`)**:原版 `g_multiplayer == 0` 判空检查 | | **`+46 .. +51`** | **6 B** | `0f 84 ?? ?? ?? ??` | `jz rel32`(跳向 `Unit::changeAircraft`) | **被改写区第 2 条指令**:操作码 `0f 84` 占 `+46..+47`,4 字节 `rel32` 位移位于 **`+48..+51`**,由 `captures.spawn_call`(`offset: 48`)动态读出跳转目标 RVA! | | `+52 .. +56` | 5 B | `48 8b 54 24 20` | `mov rdx, qword ptr [rsp + 0x20]` | 后置上下文锚点:锁死指令边界,确认 `+51` 之后紧跟预期的下一条指令 | 从上面这张表可以提炼出编写任何 EXE 补丁的 **5 个核心要点**: 1. **首尾锚点保证 `.text` 全局唯一命中**:单靠 `48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??`(判空后条件跳转)在整个 `aces.exe` 里会撞上成百上千处;加上前后 `+0..+37` 与 `+52..+56` 的寄存器与调用序列后,80 MB 代码段里就只剩这唯一 1 处命中。 2. **`edit.offset: 38` 精准对齐被替换指令首字节**:只改写 `+38..+51` 这两条指令(`8 + 6 = 14` 字节),前后的上下文锚点纹丝不动。 3. **`captures.spawn_call` 动态抠出跳转目的地**:原 `jz rel32` 的 4 字节有符号位移位于 `site + 48..51`,未传 `end` 时默认指令结尾为 `offset + 4 = 52`,因此补丁引擎自动算出目标 RVA = `site + 52 + disp32`(在 `2.61.0.37` 上即 `0x11b2c14 + 52 + disp32 = 0x11b314e`)。哪怕下个版本目标函数挪到了别的地址,只要相对跳转还在,捕获出的目标就永远准确! 4. **`expect_original`、`bytes` 与 `asm` 三重互锁**:`expect_original`(`8 + 6 = 14` 字节)与写入的 `bytes`(5 字节 `e9 ?? ?? ?? ??` 无条件跳转 + 9 个 `90` `nop` = **14 字节**)长度必须严丝合缝相等;运行 `wtotools check-patches` 时还会调用汇编器把 `asm` 编译成机器码与 `bytes` 逐字节比对,杜绝手算机器码出错。 5. **务必分清两套偏移基准点(新手头号易混点!)**: - `edit.offset`(`38`)和 `locate.captures.*.offset`(`48`)都是**从 `locate` 匹配起点 `site`(`+0`)开始算的**; - 而 `edit.fixups[].at`(`1`)和 `edit.fixups[].end`(默认 `at + 4 = 5`)是**从 `edit.bytes` 的第 0 字节(即 `site + edit.offset = site + 38`)开始算的**!因为 `bytes` 第 0 字节是 `e9`(`jmp` 操作码),紧跟其后的 4 个 `??` 洞口就在 `at: 1`,回填位移公式为 `spawn_call - ((site + 38) + 5)`。 ### 3.3 EXE 与 Native 定位进阶参考(必读防坑指南) #### (1)`rel32` 捕获的 `"end"` 陷阱:带尾随立即数的 RIP 相对寻址指令! x86-64 CPU 计算 `[rip + disp32]` 内存地址时,基准点永远是**整条指令结束处(下一条指令的首地址)**,而不是 `disp32` 这 4 个字节结束的位置! - 对于 `mov rax, [rip + disp32]`(`48 8b 05 ?? ?? ?? ??`,共 7 字节)或 `jz rel32`(`0f 84 ?? ?? ?? ??`,共 6 字节),`disp32` 恰好位于指令最末尾,所以默认的 `end = offset + 4` 刚好等于指令结尾,无需写 `"end"`。 - **但如果指令在 `disp32` 后面还跟着立即数操作数**,默认 `end` 就会算错地址!例如单条指令: `c6 05 ?? ?? ?? ?? 00` —— `mov byte ptr [rip + disp32], 0`(整条指令共 **7 字节**:`c6 05` 占 `0..1`,`disp32` 占 `2..5`,末尾立即数 `00` 占第 `6` 字节,指令在偏移 **`7`** 处结束)。如果你只写 `{ "offset": 2, "type": "rel32" }`,默认 `end` 会取 `2 + 4 = 6`,算出来的全局变量 RVA 就会**偏小 1 个字节**!此时**必须显式加上 `"end": 7`**: ```jsonc "captures": { "some_flag": { "offset": 2, "type": "rel32", "end": 7 } } ``` 仓库真实范例见 [`patches/native/local_mp_core.jsonc`](../patches/native/local_mp_core.jsonc) 的 `disabled_slots_mask` 站点:`31 c0`(`+0..+1`)后面紧跟 `48 83 3d ?? ?? ?? ?? 00`(`+2..+9`,`cmp qword ptr [rip + disp32], 0`),`disp32` 在 `offset: 5`,末尾还有 1 字节立即数 `00`(`+9`),因此显式声明了 `"multiplayer": { "offset": 5, "type": "rel32", "end": 10 }`。 #### (2)`captures` 支持的全部 7 种数值类型(`packages/exepatch/src/captures.ts`) | `type` | 字节宽度 | 读取语义 | 典型用途 | | --- | --- | --- | --- | | `"rel32"` | 4 B(小端有符号) | 计算并返回 `site + end + int32`(即目标 RVA) | 捕获 `call`、`jmp`/`jcc` 跳转目标或 `[rip + disp32]` 全局变量地址 | | `"u8"` | 1 B(无符号) | 原样读取 `0..255` | 捕获短位移成员偏移(如 `[r8 + 0x61]` 中的 `0x61`) | | `"u16"` | 2 B(小端无符号) | 原样读取 `0..65535` | 捕获 16 位消息号或协议常量(如 MPI 消息 ID) | | `"u32"` | 4 B(小端无符号) | 原样读取 32 位无符号整数 | 捕获常规 C++ 结构体大偏移(如 `[rax + 0x6d8]` 中的 `0x6d8`)或元素步长 | | `"i8"` | 1 B(有符号) | 原样读取 `-128..127` | 捕获带负号的单字节指针偏置(如循环步进指针向回偏移 `-0x10`) | | `"i16"` | 2 B(小端有符号) | 原样读取 `-32768..32767` | 捕获 16 位有符号位移 | | `"i32"` | 4 B(小端有符号) | 原样读取 32 位有符号整数 | 捕获可能为负数的 32 位有符号结构体/栈位移 | #### (3)改写 `.rdata` 只读字符串的 `"data"` 写法 当你在 `.rdata` 数据段替换等长 ASCII 字符串(而不是改 `.text` 汇编指令)时,在 `edit` 中用 `"data"` 代替 `"asm"`(真实范例见 [`patches/exe/online/network-hook-library/patch.jsonc`](../patches/exe/online/network-hook-library/patch.jsonc)): ```jsonc "edit": { "offset": 0, "data": { "encoding": "ascii", "text": "wto_ws.dll" }, "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00", "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00" } ``` 注意:`bytes` 与 `expect_original` 都包含末尾的 C 字符串终止零字节 `00`(共 11 字节),`wtotools check-patches` 会自动核对 `"text"` 的 ASCII 编码加终止零与 `"bytes"` 完全一致。 --- ## 4. Native 模块(`patches/native/` + `native/wto-net/`)—— 三种定位器与 6 文件完整串联教程 当需要在 `wto_ws.dll` 中用 C 语言挂载 MinHook 钩子或调用引擎内部函数时,**不要在 C 源码里写死十六进制地址或游戏结构体偏移常量**——所有值都由 `patches/native/<模块>.jsonc` 定位,经 `wto_ws.cfg` 传入 C 侧全局结构体 `g_lmp`。 ### 4.1 三种代码定位方法详解(`signature` / `string_ref` / `within`) 1. **`"method": "signature"`**:在指定段(默认 `".text"`,可通过 `"section"` 覆盖)搜索全局唯一命中的字节特征码,支持 `captures`。 2. **`"method": "string_ref"`**(`packages/exepatch/src/locate/string-ref.ts`,**最抗编译器重排与小版本更新的利器!**):先在 `".rdata"`(或指定 `"section"`)中找到以 `\0` 结尾的 UTF-8 字符串,再检索 `.text` 中所有加载该字符串地址的 7 字节 RIP 相对 `lea` 指令(`48 8d` / `4c 8d`)。它共有 **3 种工作模式**: - **模式 A(默认 `"target": "reference"`,不带 `"pattern"`)**:直接返回那条 7 字节 `lea` 指令本身的 RVA(可校验字节长度为 7); - **模式 B(`"target": "function"`)**:通过 PE 异常表(`.pdata`)反查包含该 `lea` 引用的**外层函数起始 RVA** 并去重返回(注意:此模式可校验字节长度为 0,不能直接在它上面挂 `captures`,专门用来定位函数入口供 MinHook 挂钩或作为下方 `within` 的父锚点!); - **模式 C(`"pattern"` + `"lea_at"`,此时 `"target"` 必须保持默认 `"reference"`)**:围绕字符串 `lea` 匹配一段局部指令序列,要求加载该字符串的 7 字节 `lea` 恰好位于 `pattern` 内部偏移 `lea_at` 处,返回 `pattern` 起点 RVA——这样就能顺手用 `captures` 把紧挨着字符串引用的结构体字段偏移抠出来!(例如通过字段名 `"kills"` 直接抠出 `MPlayer` 里的击杀计数字段偏移)。 3. **`"method": "within"`**(`packages/exepatch/src/locate/within.ts`):在**同一个或被 `requires` 依赖的模块中已经先行定位好的站点 `"in"`** 所属函数的 `.pdata` `[begin, end)` 范围内搜索 `"pattern"`。因为在单个函数内部搜索,哪怕只有一两条指令的短特征码也能唯一命中,彻底避免全程序撞码。 ### 4.2 跟着 `local_mp_scores` 走完从 JSONC 到 C 落地的全部 6 个文件 假设我们要实现 `LocalMP` 局内记分牌分值读取模块 `local_mp_scores`(本地服务器把各事件得分写进任务配置的 `customScoreParams` 子块,客户端 `MissionSettings::load` 会把它拷进 `MissionSettings` 结构体内部某偏移处,但客户端自己从不读它;我们的 C 模块需要调用引擎的 `DataBlock::getReal` 从该偏移处读出分值)。看看这 **6 个真实文件**是怎么严丝合缝串起来的: #### 第 1 步:编写定位定义 [`patches/native/local_mp_scores.jsonc`](../patches/native/local_mp_scores.jsonc) 文件名必须与 `"module"` 字段完全同名。由于我们要复用 `local_mp_core.jsonc` 里已经用 `"string_ref"`(`"string": "customScoreParams", "target": "function"`)定位好的函数 `"mission_settings_load"`,在 `"requires"` 中声明 `"local_mp_core"`: ```jsonc // Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it // in the mission's customScoreParams; the host reads it there. // Without it: kills, assists and captures score nothing. { "module": "local_mp_scores", "features": [ "K-Kill, assist and capture scoring" ], "requires": [ "local_mp_core" ], "sites": { // DataBlock::getReal wrapper. // 2.61.0.37: 0x5445270 "datablock_get_real": { "variants": [ { "written_for": "2.61.0.37", "locate": { "method": "signature", "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15" } } ] }, // MissionSettings customScoreParams copy. // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...) "mission_score_params": { "variants": [ { "written_for": "2.61.0.37", "locate": { "method": "within", "in": "mission_settings_load", "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00", "captures": { "custom_score_params": { "offset": 3, "type": "u32" } } } } ] } } } ``` 看 `mission_score_params` 首条指令 `48 8d 88 ?? ?? ?? ??`(`lea rcx, [rax + disp32]`):前 3 字节是 `48 8d 88`,第 `3..6` 字节就是 `MissionSettings` 里的结构体偏移,因此 `"offset": 3, "type": "u32"` 直接把 `0x6d8` 抠了出来! #### 第 2 步:构建器自动生成 `<离线副本>/win64/wto_ws.cfg`(`packages/patcher/src/native/`) 构建副本时,`native-resolve.ts` 与 `native-settings.ts` 会把当前 `aces.exe` 的 PE 头指纹连同所有已就绪模块的 `<站点>` 与 `<站点>.<捕获名>` 写入 `win64/wto_ws.cfg`: ```ini port=27015 exe.time_date_stamp=0x67e5a1b2 exe.size_of_image=0x83f4000 native.datablock_get_real=0x5445270 native.mission_score_params=0x126d762 native.mission_score_params.custom_score_params=0x6d8 ``` #### 第 3 步:在 [`native/wto-net/src/local_mp_values.h`](../native/wto-net/src/local_mp_values.h) 声明 `LmpValues` 字段 地址一律声明为 `uint8_t *`,无符号偏移/大小声明为 `size_t`(有符号位移声明为 `ptrdiff_t`): ```c typedef struct LmpValues { /* ... 其他模块字段 ... */ /* local_mp_scores */ uint8_t *datablock_get_real; size_t mis_custom_score_params; } LmpValues; extern LmpValues g_lmp; ``` #### 第 4 步:在 [`native/wto-net/src/local_mp_values.c`](../native/wto-net/src/local_mp_values.c) 绑定 `SPECS[]` 映射表 `local_mp_values.c` 通过三个宏把 `wto_ws.cfg` 里的键名映射到 `g_lmp` 的成员: - **`A(module, name, field)`**(`LMP_ADDRESS`):读取 RVA 后自动加上当次进程基址 `(uint8_t *)GetModuleHandleW(NULL) + value`,存成可直接调用的运行时指针; - **`O(module, name, field)`**(`LMP_OFFSET`):存为无符号 `size_t` 结构体偏移或步长; - **`S(module, name, field)`**(`LMP_SIGNED`):存为有符号 `ptrdiff_t` 位移; - 如果某个复合偏移需要由两个捕获值相加减(客户端没有单独访问它的指令),则写在同文件的 `derive_values()` 中。 ```c #define SCORES "local_mp_scores" static const LmpValueSpec SPECS[] = { /* ... */ A(SCORES, "datablock_get_real", datablock_get_real), O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params), /* ... */ }; ``` #### 第 5 步:在 [`native/wto-net/src/local_mp_offsets.h`](../native/wto-net/src/local_mp_offsets.h) 定义可读偏移宏 ```c #define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params) ``` #### 第 6 步:实现 [`local_mp_scores.c`](../native/wto-net/src/local_mp_scores.c)、注册到 [`local_mp_core.c`](../native/wto-net/src/local_mp_core.c) 并加入 [`build.ps1`](../native/wto-net/build.ps1) - 在 `local_mp_scores.c` 中只读取 `g_lmp` 与 `local_mp_core` 导出的公共指针: ```c typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def); static DataBlockGetRealFn fn_datablock_get_real; float local_mp_score_param(const char *key) { if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL) return 0.0f; return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f); } int install_local_mp_score_reader(void) { fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real; return 1; } ``` - 在 `local_mp_core.c` 中,启动时 `install_local_mp_hooks()` 会先用 `config_native_matches_executable()` 核对当前运行中 `aces.exe` 的 PE `TimeDateStamp` 与 `SizeOfImage` 是否与 `wto_ws.cfg` 完全一致(不一致则整套 `LocalMP` 桥接器安全关闭),然后按依赖顺序遍历 `MODULES[]` 数组,对每个模块先跑 `lmp_values_load(MODULES[i].name)` 确认值一个不少,再调用安装函数并在最后统一 `MH_ApplyQueued()`。 - **如果新增了一个全新的 `.c` 源文件**:除了在 `local_mp_internal.h` 声明安装函数并加入 `local_mp_core.c` 的 `MODULES[]`,还**必须把该 `.c` 文件路径加进 `native/wto-net/build.ps1` 的 `$sources` 数组**! - **多模块共享钩子**:如果两个模块都需要拦截或调用同一个引擎函数(例如 `Unit::onEvent` 同时被 `local_mp_damage_notifications` 和 `local_mp_air_events` 使用),请把站点放进 `local_mp_core.jsonc` 统一解析分发,避免在两个模块里用 MinHook 重复挂钩同一个目标地址。 --- ## 5. 适配新版本客户端(标准四步流程) 每当《战争雷霆》发布小版本更新(例如 `2.61.0.37` → `2.61.0.58`)时,按下面四步跟进适配: 1. **对只读原版客户端运行版本核对脚本**: ```powershell node scripts/record-game-version.ts --game "<原版目录>" ``` 该脚本会只读扫描原版客户端,一次性跑完所有 `patches/exe/`、`patches/gui/` 和 `patches/native/` 的定位测试。如果三条核心安全锁(`ESSENTIAL_FEATURES`)中有补丁失效,脚本会直接拒绝生成版本记录并列出阻断项;若核心安全锁全部命中,则会写出 `patches/versions/<版本号>.jsonc` 并打印所有 `unavailable`(暂不可用)的非关键补丁/模块。 2. **排查失配项并追加新 `variant`**: 打开失配的补丁或原生站点,用第 1 节的 Node 拆包脚本或 `tools/re/cli.py`(优先用 `find-string` 找不变的字符串锚点!)查看新版本原版文件发生了什么变化。**保留原有旧版本的 `variant` 不动**,在 `variants` 数组中追加一条 `"written_for": "<新版本号>"` 的新写法。 3. **跑完完整工具链核对**: 重新运行 `record-game-version.ts` 确认 `unavailable` 清零,并依次跑通: - `.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"` - `.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"` - 若改了 `native/wto-net/`,运行 `powershell -NoProfile -File .\native\wto-net\build.ps1` - 用临时输出目录跑一遍 `node scripts/build-game-copy.ts` 确认副本完整生成。 4. **隔离副本实机进游戏验收后再提交 `patches/versions/<版本号>.jsonc`**: 启动器依赖 `patches/versions/<版本号>.jsonc` 向玩家展示「该客户端版本已核对通过」。请在隔离副本里实际登录进机库并完成一局 `LocalMP` 对局验收后,再提交 `patches/versions/<版本号>.jsonc`,不要仅凭命令行脚本通过就直接入库。 新建补丁时可直接复制空白脚手架模板:[`dev-docs/templates/gui/`](templates/gui/patch.jsonc)、[`dev-docs/templates/exe/`](templates/exe/patch.jsonc)、[`dev-docs/templates/native/`](templates/native/local_mp_example.jsonc)。 --- [简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english) This handbook covers authoring client patches (Quirrel UI scripts, `aces.exe` machine-code/data patches, and `wto_ws.dll` `LocalMP` native modules) and adapting WTOffline to new War Thunder client builds. > **Check first before touching the client**: Read [Development Rules — Section 1](development-rules.md#architecture-en) and verify that the issue **genuinely cannot** be solved in `apps/server` or via stock mission/config BLK fields. Client patches are strictly for code paths that retail client builds omit or hardcode. --- ## 1. Step 0: Unpacking Stock Archives, Reading Binary BLK, Disassembling `aces.exe`, and Choosing a Patch Type Never modify any file inside your official stock installation. Using `@wto/vromfs`, `@wto/blk`, and `tools/re/cli.py`, you can inspect every stock script, binary `.blk`, and `aces.exe` function purely in memory. ### 1.1 Inspect `.nut` Scripts or Binary `.blk` Files Inside Stock `.vromfs.bin` Archives Run these one-liners from the repository root (replacing `` with your read-only official War Thunder path): ```powershell # Example A: List matching .nut paths inside gui.vromfs.bin and print a stock Quirrel script node --input-type=module -e " import { readFileSync } from 'node:fs'; import { getFile, readArchive } from '@wto/vromfs'; const archive = readArchive(readFileSync(String.raw`\gui.vromfs.bin`)); console.log([...archive.files.keys()].filter((p) => p.includes('tutorial'))); console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8')); " # Example B: Decode a slimmed binary .blk from char.vromfs.bin (or aces.vromfs.bin) as readable text # (automatically loads the archive's shared name map `nm` and optional `.dict` zstd dictionary) node --input-type=module -e " import { readFileSync } from 'node:fs'; import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk'; import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs'; const archive = readArchive(readFileSync(String.raw`\char.vromfs.bin`)); const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1]; const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : []; const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary }); console.log(formatBlkText(blk).slice(0, 2000)); " ``` ### 1.2 Static Reverse Engineering on `aces.exe` with `tools/re/cli.py` Once your `.venv` is installed (`pip install -e ./tools`; see [Environment Setup](contributing.md#english)), use `tools/re/cli.py` to locate strings, cross-references, callers, and disassembly (**all addresses are hex RVAs, and always pass `--exe "\win64\aces.exe"` explicitly**): ```powershell # 1. Find where a C string lives in .rdata and every rip-relative `lea` instruction + function referencing it .\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "\win64\aces.exe" # 2. Find every instruction with a rip-relative reference to a target RVA (e.g., a global pointer) .\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "\win64\aces.exe" # 3. Find every direct `call` or `jmp` targeting a function RVA .\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "\win64\aces.exe" # 4. Disassemble an RVA with string and call annotations (defaults to 40 instructions; supports --count, --end, or --function) .\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "\win64\aces.exe" .\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "\win64\aces.exe" ``` ### 1.3 Choosing the Right Patch Type & Universal Conventions | What needs changing | Where it belongs | Real codebase example | | --- | --- | --- | | Hangar, modal, store, or debriefing UI scripts (Quirrel `.nut`) | `patches/gui///` | [`patches/gui/tutorials/immediate-save-skip-tutorial/`](../patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc) | | A few machine instructions or a constant `.rdata` string in `aces.exe` | `patches/exe///` | [`patches/exe/battle/allow-local-host-bot-spawns/`](../patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc) | | In-process C hooks restoring `LocalMP` battle host logic (`wto_ws.dll`) | `patches/native/.jsonc` + `native/wto-net/src/.c` | [`patches/native/local_mp_scores.jsonc`](../patches/native/local_mp_scores.jsonc) | | Static archive config rewrites (`network.blk`, `shop.blk`, `gui.blk`) | `packages/patcher/src/` (**not** under `patches/`) | `packages/patcher/src/char-pack.ts`, `main-pack.ts` | **Four universal rules across all `patches/` definitions**: 1. **One behavior per directory/module**—never bundle unrelated fixes into a single patch definition. 2. **Start every `patch.jsonc` / `.jsonc` with a 3-line English comment**: - Line 1: What the patch changes; - Line 2 (`Why the client:` / `Why the exe:`): Why the local server or stock config cannot provide it; - Line 3 (`Without it:`): What breaks for the player if this patch is missing. 3. **Write `title` and `features` in English** (note: a few early historical patches still carry Chinese `title` strings, **but all new patches must write `title` in English**), reusing existing `A-`..`K-` inventory tags ([Glossary — Section 7](README.md#glossary-en)). 4. **Exact single-variant, single-site match**: On any given client build, **exactly one `variant` must apply, and its locator must hit exactly one site**; zero hits or multiple hits fail safely rather than corrupting the output copy. --- ## 2. GUI Patches (`patches/gui/`) — Full 3-File Example & Strict Schema Rules ### 2.1 Complete Real Example: `tutorials/immediate-save-skip-tutorial` In stock `scripts/tutorials/nexttutorialhandler.nut`, when a player ticks **"Do not ask me again"** on the tutorial prompt, the script calls `saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)` with no third argument. That falls back to `saveProfile()`, which waits on a **60-second debounce timer** before sending anything to the server—so closing or crashing within 60 seconds loses the opt-out and brings the prompt back on next login. Because `apps/server` cannot speed up a client-side timer before a request is ever sent, this patch passes `@() save_profile(false)` as the immediate-save callback. Here are **all three files** in `patches/gui/tutorials/immediate-save-skip-tutorial/` verbatim (note: this early patch kept a Chinese `title`, whereas new patches should use an English `title` such as `"Save tutorial opt-out immediately after ticking 'do not ask again'"`): **1. `patch.jsonc`**: ```jsonc // Save the tutorial opt-out immediately via save_profile(false). // Why the client: the stock callback waits 60 s before writing or sending anything to the service. // Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back. { "id": "tutorials/immediate-save-skip-tutorial", "title": "新手教程询问窗勾选「不再询问」后立即落盘保存", "features": [ "A-Tutorials" ], "variants": [ { "written_for": "2.61.0.37", "file": "scripts/tutorials/nexttutorialhandler.nut", "edits": [ { "find": "find.nut", "replace": "replace.nut" } ] } ] } ``` **2. `find.nut`** (the smallest verbatim stock snippet occurring **exactly once** in the target `.nut` file, preserving exact indentation): ```squirrel skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) } ``` **3. `replace.nut`** (the replacement text): ```squirrel skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue()) saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false)) } ``` ### 2.2 Strict `gui-patch-definition.ts` Schema Whitelist & Authoring Rules `packages/patcher/src/gui-patch-definition.ts` calls `rejectUnknownKeys` at every level—**any extra property immediately throws `DefinitionError`**: - **Top-level keys are strictly `id`, `title`, `features`, `variants`**. > **Watch out: GUI `patch.jsonc` does NOT have a `requires` key!** Do not copy `"requires": []` from an EXE patch into `patches/gui/`, or `loadGuiPatches` will throw `DefinitionError`! - **`variants[]` keys are strictly `written_for`, `file`, `edits`**. `file` must be the **exact lowercase, `/`-separated relative path** inside `gui.vromfs.bin` without a leading slash (e.g., `"scripts/tutorials/nexttutorialhandler.nut"`—archive paths are all lowercased!). - **`edits[]` keys are strictly `find`, `replace`**, naming plain filenames directly inside the patch folder (no `/` or `\` subdirectories). - **Line endings & exact-once matching**: `readFragment` strips any UTF-8 BOM, normalizes `\r\n` to `\n`, and removes a single trailing newline at EOF (so Git `autocrlf` never breaks patches). `find.nut` must match **exactly once** in the target script. - **`{{LOCAL_ENDPOINT}}` placeholder**: Whenever replacement Quirrel code needs the local server address, write `{{LOCAL_ENDPOINT}}`; `gui-pack.ts` expands it to `127.0.0.1:` during copy builds. - **Adding a variant for a newer build**: Never edit an existing `find.nut` in a way that breaks older supported builds—create `find-58.nut` / `replace-58.nut` and append a new entry to `variants`. - **Mandatory `sq.exe` bytecode check**: Every change under `patches/gui/` **must** pass: ```powershell .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe" ``` `check-gui` applies all GUI patches in memory and runs `sq.exe` (`compilestring`) on every patched `.nut` script, catching lexical binding clashes with top-of-file `from ... import *` imports, unbound forward calls, and reserved keywords like `base` that otherwise hang the client forever on `"Loading..."`. --- ## 3. EXE Patches (`patches/exe/`) — Full 57-Byte Anatomy & Reference When modifying instructions or constant data inside `aces.exe`, `@wto/exepatch` lets you express edits with **zero hardcoded addresses** so patches survive minor game updates automatically. ### 3.1 Un-Elided Real Example: `patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc` In `BotSystem::changeUnit`, after verifying a valid spawn point, stock `aces.exe` checks whether `g_multiplayer` is null (`cmp qword ptr [rip + disp32], 0`): in single-player test flights (`g_multiplayer == NULL`), `jz` jumps straight to the `Unit::changeAircraft` call to spawn the AI unit; in a `LocalMP` session (`g_multiplayer != NULL`), because retail `aces.exe` strips the Dedicated Server's script spawn permission, execution falls through to `"spawn denied by scripts"` and no AI vehicle ever spawns. Here is the **complete, un-elided** [`patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc`](../patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc) (**all 57 pattern bytes**, zero `...`): ```jsonc // Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer // null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e). // Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer // session the function only logs "spawn denied by scripts"; non-host sessions already return at its start. // Without it: no AI vehicle ever spawns in a LocalMP battle. { "id": "battle/allow-local-host-bot-spawns", "title": "Let BotSystem spawn AI vehicles on a LocalMP host", "features": [ "K-AI opponents and teammates" ], "requires": [], "variants": [ // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010) // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards. // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a). // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard. { "written_for": "2.61.0.37", "locate": { "method": "signature", "section": ".text", "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20", "captures": { "spawn_call": { "offset": 48, "type": "rel32" } } }, "edit": { "offset": 38, "asm": [ "jmp {spawn_call}", "nop", "nop", "nop", "nop", "nop", "nop", "nop", "nop", "nop" ], "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90", "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??", "fixups": [ { "at": 1, "type": "rel32", "target": "spawn_call" } ] } } ] } ``` ### 3.2 Instruction-by-Instruction Breakdown (`+0..+56`, All 57 Bytes) Breaking down every byte from the match start `site` (`0x11b2c14` on `2.61.0.37`) makes every offset number self-evident: | Offset from `site` | Size | Hex bytes in `pattern` | x86-64 instruction | Role in this patch | | --- | --- | --- | --- | --- | | `+0 .. +6` | 7 B | `48 8b 05 ?? ?? ?? ??` | `mov rax, qword ptr [rip + disp32]` | Leading context anchor (`??` masks build-varying RIP displacement) | | `+7 .. +13` | 7 B | `48 8b 88 e0 03 00 00` | `mov rcx, qword ptr [rax + 0x3e0]` | Leading context anchor | | `+14 .. +18` | 5 B | `48 8b 5c 24 20` | `mov rbx, qword ptr [rsp + 0x20]` | Leading context anchor | | `+19 .. +21` | 3 B | `48 89 da` | `mov rdx, rbx` | Leading context anchor | | `+22 .. +24` | 3 B | `4d 89 f0` | `mov r8, r14` | Leading context anchor | | `+25 .. +29` | 5 B | `e8 ?? ?? ?? ??` | `call rel32` (spawn-point check) | Leading context anchor (`??` masks call displacement) | | `+30 .. +31` | 2 B | `84 c0` | `test al, al` | Leading context anchor | | `+32 .. +37` | 6 B | `0f 84 ?? ?? ?? ??` | `jz rel32` (early-out if spawn check failed) | Leading context anchor (kept intact!) | | **`+38 .. +45`** | **8 B** | `48 83 3d ?? ?? ?? ?? 00` | `cmp qword ptr [rip + disp32], 0` | **Edited instruction #1 (`edit.offset = 38`)**: the `g_multiplayer` null guard | | **`+46 .. +51`** | **6 B** | `0f 84 ?? ?? ?? ??` | `jz rel32` (to `Unit::changeAircraft` call) | **Edited instruction #2**: 2-byte opcode `0f 84` (`+46..+47`) + 4-byte `rel32` at **`+48..+51`**, captured as `spawn_call` (`offset: 48`)! | | `+52 .. +56` | 5 B | `48 8b 54 24 20` | `mov rdx, qword ptr [rsp + 0x20]` | Trailing context anchor verifying exact instruction boundary after `+51` | Notice the **five key mechanics** working together here: 1. **Surrounding anchors guarantee a unique hit**: `48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??` alone appears hundreds of times across `.text`, whereas anchoring `+0..+37` before it and `+52..+56` after it narrows 80 MB of code down to a single unambiguous hit. 2. **`edit.offset: 38` leaves the anchors untouched**: Only the 14 bytes at `+38..+51` are overwritten. 3. **`captures.spawn_call` (`offset: 48, type: "rel32"`) resolves the jump target dynamically**: The `jz` instruction's 4-byte displacement sits at `+48..+51`, so default `end = 48 + 4 = 52`, yielding target RVA = `site + 52 + disp32` (`0x11b314e` on `2.61.0.37`). Even when future builds shift `Unit::changeAircraft`, the captured RVA updates automatically. 4. **Exact 14-byte parity & `asm` verification**: `expect_original` is `8 + 6 = 14` bytes and `bytes` is `5` (`e9 ?? ?? ?? ??`) + `9` (`90` NOPs) = **14 bytes**. Running `wtotools check-patches` assembles `asm` and verifies byte-for-byte agreement with `bytes`. 5. **Crucial offset base distinction (most common beginner mistake!)**: - `edit.offset` (`38`) and `locate.captures.*.offset` (`48`) count from **`site` (`+0` of `locate.pattern`)**; - `edit.fixups[].at` (`1`) and `edit.fixups[].end` (default `at + 4 = 5`) count from **byte `0` of `edit.bytes` (`site + 38`)**, right after the `e9` opcode! ### 3.3 Reference: The `rel32` `"end"` Trap, All 7 Capture Types & `.rdata` Edits #### (1) The `rel32` `"end"` Trap (Instructions with Trailing Immediate Bytes!) On x86-64, RIP-relative addressing always adds `disp32` to the **address of the next instruction (where the current instruction ends)**, NOT where the 4-byte `disp32` ends! - For `mov rax, [rip + disp32]` (`48 8b 05 ?? ?? ?? ??`, 7 B) or `jz rel32` (`0f 84 ?? ?? ?? ??`, 6 B), `disp32` is at the very end of the instruction, so the default `end = offset + 4` matches the instruction end automatically. - **However, when an instruction has trailing immediate byte(s) after `disp32`**, omitting `"end"` resolves the wrong address! Take `c6 05 ?? ?? ?? ?? 00` (`mov byte ptr [rip + disp32], 0`): the instruction is **7 bytes** total (`c6 05` at `0..1`, `disp32` at `2..5`, trailing immediate `00` at `6`, ending at **`7`**). Writing `{ "offset": 2, "type": "rel32" }` defaults `end` to `2 + 4 = 6`, landing **1 byte before** the real global variable! You **must** pass `"end": 7`: ```jsonc "captures": { "some_flag": { "offset": 2, "type": "rel32", "end": 7 } } ``` For a real example in the repo, see `disabled_slots_mask.multiplayer` in [`patches/native/local_mp_core.jsonc`](../patches/native/local_mp_core.jsonc): after `31 c0` (`+0..+1`), `48 83 3d ?? ?? ?? ?? 00` (`cmp qword ptr [rip + disp32], 0`) spans `+2..+9` with `disp32` at `offset: 5` and trailing `00` at `+9`, so it specifies `"end": 10`. #### (2) All 7 Capture Types (`packages/exepatch/src/captures.ts`) | `type` | Width | How it is read | Typical use | | --- | --- | --- | --- | | `"rel32"` | 4 B (signed LE) | Computes target RVA = `site + end + int32` | Target of `call`, `jmp`/`jcc`, or `[rip + disp32]` global variable | | `"u8"` | 1 B (unsigned) | Raw `0..255` | Compact 8-bit struct field offset (e.g., `[r8 + 0x61]`) | | `"u16"` | 2 B (unsigned LE) | Raw `0..65535` | 16-bit wire/MPI message IDs | | `"u32"` | 4 B (unsigned LE) | Raw 32-bit unsigned integer | Standard C++ struct member offsets (e.g., `[rax + 0x6d8]`) or array strides | | `"i8"` | 1 B (signed) | Raw `-128..127` | Signed 1-byte pointer biases in loop iterators | | `"i16"` | 2 B (signed LE) | Raw `-32768..32767` | Signed 16-bit displacements | | `"i32"` | 4 B (signed LE) | Raw 32-bit signed integer | Signed 32-bit stack or struct displacements | #### (3) Constant String / Data Edits in `.rdata` When replacing a fixed-length string in `.rdata` instead of assembly instructions, use `"data"` in place of `"asm"` (real example: [`patches/exe/online/network-hook-library/patch.jsonc`](../patches/exe/online/network-hook-library/patch.jsonc)): ```jsonc "edit": { "offset": 0, "data": { "encoding": "ascii", "text": "wto_ws.dll" }, "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00", "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00" } ``` Both `bytes` and `expect_original` include the terminating `00` byte (11 bytes total), and `wtotools check-patches` verifies that `data` encodes identically to `bytes`. --- ## 4. Native Modules (`patches/native/` + `native/wto-net/`) — Locators & Complete 6-File Wiring Walkthrough When writing MinHook detours or calling engine functions in `wto_ws.dll`, **never put a single build-specific RVA or game struct offset in C code**. Instead, declare sites in `patches/native/.jsonc`, let the patcher emit resolved hex values into `win64/wto_ws.cfg`, and read them in C from `extern LmpValues g_lmp`. ### 4.1 All Three Locate Methods (`signature`, `string_ref`, `within`) 1. **`"method": "signature"`**: Scans `".text"` (or a specified `"section"`) for a unique byte pattern, supporting `captures`. 2. **`"method": "string_ref"`** (`packages/exepatch/src/locate/string-ref.ts` — **most resilient across compiler codegen shifts!**): Finds UTF-8 `string + \0` in `".rdata"` (or `"section"`) and locates 7-byte RIP-relative `lea` (`48 8d` / `4c 8d`) instructions loading that string in `.text`. Supports **three modes**: - **Mode A (`"target": "reference"`, default without `"pattern"`)**: Returns the RVA of the 7-byte `lea` instruction itself (checked length = 7 bytes); - **Mode B (`"target": "function"`)**: Looks up the enclosing function's start RVA in the PE `.pdata` exception directory (checked length = 0, so no direct `captures`—ideal for locating function entry points to hook or use as `within` anchors); - **Mode C (`"pattern"` + `"lea_at"`, with default `"target": "reference"`)**: Matches `pattern` around the string reference where the 7-byte `lea` sits at byte offset `lea_at`, returning the `pattern` start RVA so `captures` can read adjacent struct offsets right next to the string reference! 3. **`"method": "within"`** (`packages/exepatch/src/locate/within.ts`): Searches `pattern` strictly within the `[begin, end)` PE `.pdata` bounds of an already-resolved site named in `"in"` (from an earlier site in the same module or a `requires` module), allowing short field-access patterns to match uniquely inside one function. ### 4.2 Complete 6-File Wiring Walkthrough: `local_mp_scores` Here is how `local_mp_scores` (which reads per-event scoreboard points placed by `apps/server` into `MissionSettings.customScoreParams`) connects end-to-end across **all 6 real files**: #### File 1: [`patches/native/local_mp_scores.jsonc`](../patches/native/local_mp_scores.jsonc) The filename must match `"module"`. Because `"mission_settings_load"` is already resolved via `string_ref` (`"string": "customScoreParams", "target": "function"`) in `local_mp_core.jsonc`, `"local_mp_scores"` lists `"local_mp_core"` in `"requires"` and searches inside `"mission_settings_load"` using `"within"`: ```jsonc // Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it // in the mission's customScoreParams; the host reads it there. // Without it: kills, assists and captures score nothing. { "module": "local_mp_scores", "features": [ "K-Kill, assist and capture scoring" ], "requires": [ "local_mp_core" ], "sites": { // DataBlock::getReal wrapper. // 2.61.0.37: 0x5445270 "datablock_get_real": { "variants": [ { "written_for": "2.61.0.37", "locate": { "method": "signature", "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15" } } ] }, // MissionSettings customScoreParams copy. // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...) "mission_score_params": { "variants": [ { "written_for": "2.61.0.37", "locate": { "method": "within", "in": "mission_settings_load", "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00", "captures": { "custom_score_params": { "offset": 3, "type": "u32" } } } } ] } } } ``` In `48 8d 88 ?? ?? ?? ??` (`lea rcx, [rax + disp32]`), bytes `0..2` are `48 8d 88` and bytes `3..6` hold the struct offset (`0x6d8` on `2.61.0.37`), captured via `"offset": 3, "type": "u32"`. #### File 2: Generated `/win64/wto_ws.cfg` (`packages/patcher/src/native/native-settings.ts`) During copy builds, the patcher writes the executable's PE identity stamps alongside `` and `.` entries for all completely resolved modules: ```ini port=27015 exe.time_date_stamp=0x67e5a1b2 exe.size_of_image=0x83f4000 native.datablock_get_real=0x5445270 native.mission_score_params=0x126d762 native.mission_score_params.custom_score_params=0x6d8 ``` #### File 3: [`native/wto-net/src/local_mp_values.h`](../native/wto-net/src/local_mp_values.h) Add pointer (`uint8_t *`), unsigned offset (`size_t`), or signed displacement (`ptrdiff_t`) fields to `struct LmpValues`: ```c typedef struct LmpValues { /* ... other modules ... */ /* local_mp_scores */ uint8_t *datablock_get_real; size_t mis_custom_score_params; } LmpValues; extern LmpValues g_lmp; ``` #### File 4: [`native/wto-net/src/local_mp_values.c`](../native/wto-net/src/local_mp_values.c) Wire the `wto_ws.cfg` keys into `SPECS[]` using the three storage macros: - **`A(module, name, field)`** (`LMP_ADDRESS`): computes `(uint8_t *)GetModuleHandleW(NULL) + rva` and stores the live process pointer; - **`O(module, name, field)`** (`LMP_OFFSET`): stores an unsigned `size_t` struct offset or stride; - **`S(module, name, field)`** (`LMP_SIGNED`): stores a signed `ptrdiff_t` displacement; - Use `derive_values()` in the same file when a relative offset must be computed from two captured values (e.g., subtracting `econ_change_req` from an outer `econ_req_*` offset). ```c #define SCORES "local_mp_scores" static const LmpValueSpec SPECS[] = { /* ... */ A(SCORES, "datablock_get_real", datablock_get_real), O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params), /* ... */ }; ``` #### File 5: [`native/wto-net/src/local_mp_offsets.h`](../native/wto-net/src/local_mp_offsets.h) Expose a descriptive macro backed by `g_lmp`: ```c #define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params) ``` #### File 6: [`local_mp_scores.c`](../native/wto-net/src/local_mp_scores.c), [`local_mp_core.c`](../native/wto-net/src/local_mp_core.c) & [`native/wto-net/build.ps1`](../native/wto-net/build.ps1) - Consume the resolved function and offset in `local_mp_scores.c`: ```c typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def); static DataBlockGetRealFn fn_datablock_get_real; float local_mp_score_param(const char *key) { if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL) return 0.0f; return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f); } int install_local_mp_score_reader(void) { fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real; return 1; } ``` - In `local_mp_core.c`, `install_local_mp_hooks()` first calls `config_native_matches_executable()` to verify that the running `aces.exe`'s PE `TimeDateStamp` and `SizeOfImage` match `wto_ws.cfg` (disabling the entire `LocalMP` bridge if `wto_ws.cfg` came from a different build), loads `local_mp_core`, iterates `MODULES[]` in dependency order (`{ "local_mp_scores", install_local_mp_score_reader }`) calling `lmp_values_load(MODULES[i].name)` before `install()`, and enables all queued hooks in one pass via `MH_ApplyQueued()`. - **Adding a brand-new `.c` file**: Declare its installer in `local_mp_internal.h`, register it in `MODULES[]` (`local_mp_core.c`), **and add the `.c` file to `$sources` in `native/wto-net/build.ps1`**. - **Sharing common engine hooks**: When two modules need the same target function (e.g., `unit_on_event` shared by `local_mp_damage_notifications` and `local_mp_air_events`), define and dispatch it once in `local_mp_core` rather than calling `MH_CreateHook` twice on the same address. --- ## 5. Adapting a New Client Build (4-Step Workflow) When War Thunder releases a minor client update (e.g., `2.61.0.37` -> `2.61.0.58`), follow these four steps: 1. **Run the build recorder against your read-only stock client**: ```powershell node scripts/record-game-version.ts --game "" ``` `record-game-version.ts` tests every `patches/exe/`, `patches/gui/`, and `patches/native/` definition without modifying the stock folder. If any essential safety patch (`ESSENTIAL_FEATURES`) fails, it refuses to write a record and prints the blocking failures; otherwise it writes `patches/versions/.jsonc` and lists any `unavailable` optional patches/modules. 2. **Add new variants only for failing patches/sites**: Inspect the updated `.nut` script or `aces.exe` function using the Step 0 Node snippet or `tools/re/cli.py` (prefer `find-string` anchors!). **Keep existing `variants` untouched** so earlier builds continue working, and append a new variant with `"written_for": ""`. 3. **Run the full verification suite**: Re-run `record-game-version.ts` to confirm zero `unavailable` items, then run: - `.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "\win64\aces.exe"` - `.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"` - `powershell -NoProfile -File .\native\wto-net\build.ps1` (if any C file changed) - `node scripts/build-game-copy.ts` into a temporary copy directory to confirm clean assembly. 4. **Verify live in-game inside an isolated copy BEFORE committing `patches/versions/.jsonc`**: The launcher relies on `patches/versions/.jsonc` to badge a client build as verified. Boot the isolated copy, sign into the hangar, and play through a `LocalMP` battle before committing `patches/versions/.jsonc` rather than relying on CLI checks alone. Starter templates for new patches live under [`dev-docs/templates/gui/`](templates/gui/patch.jsonc), [`dev-docs/templates/exe/`](templates/exe/patch.jsonc), and [`dev-docs/templates/native/`](templates/native/local_mp_example.jsonc).