Expand dev-docs with a plain-language glossary, accurate single-port server flow, real apps/server directory map and cln_set_researchable trace, un-elided 57-byte EXE patch anatomy, 6-file Native C wiring guide, real Good vs. Bad code comparisons, AI constraint prompt, and traffic-log debugging steps at 1:1 zh-CN/en parity.
64 KiB
补丁编写与新版本适配指南 / Patch Authoring & Adaptation Guide
简体中文 · English · 返回 Dev Docs
这篇手册面向需要修改客户端(Quirrel 界面脚本、aces.exe 二进制指令、或 wto_ws.dll 局内 LocalMP 原生裁判模块)以及协助适配游戏新版本的开发者。
动手前的第一道自检:请先阅读 开发规范第 1 节,确认问题确实无法通过修改
apps/server协议响应或下发原版任务/配置 BLK 字段解决。只有原版客户端真正缺失对应通路时,才编写客户端补丁。
1. 第 0 步:只读拆包、查看二进制 BLK、反汇编定位与选型
请将原版客户端目录视为只读,不要直接修改其中的文件。利用仓库自带的 @wto/vromfs、@wto/blk 和 Python 静态分析工具 tools/re/cli.py,你可以在内存中直接查看原版脚本、配置与反汇编代码。
1.1 一行命令读取原版 .vromfs.bin 中的 .nut 脚本或解码二进制 .blk
无需安装第三方解包器,在仓库根目录运行下面这段 Node.js 脚本(把 <原版目录> 换成你的官方客户端路径,只读不写):
# 示例 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 做只读静态逆向定位
先按 环境准备 初始化 .venv(pip install -e ./tools)。随后即可直接在命令行查字符串交叉引用、查调用者、反汇编函数(注意:所有地址参数均为十六进制 RVA,且务必显式传入 --exe "<原版目录>\win64\aces.exe"):
# 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/ |
改写 aces.exe 内寥寥几条跳转/比较指令或 .rdata 固定字符串 |
patches/exe/<领域>/<名称>/ |
patches/exe/battle/allow-local-host-bot-spawns/ |
用 C 语言写 MinHook 钩子补齐 LocalMP 局内裁判逻辑(wto_ws.dll) |
patches/native/<模块>.jsonc + native/wto-net/src/<模块>.c |
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/ 定义共享的四条基本约定:
- 一处独立行为对应一个目录/模块,不在同一个补丁里顺手塞两件不相关的改动;
patch.jsonc/<模块>.jsonc顶部必须写三行英文注释:- 第 1 行:这个补丁具体改了什么;
- 第 2 行(
Why the client:/Why the exe:):为什么本地服务器或原版配置解决不了; - 第 3 行(
Without it:):如果不打这个补丁,玩家会遇到什么具体现象。
title与features统一写英文(注:仓库内个别早期补丁保留了中文title历史遗留,所有新增补丁请一律使用清晰的英文title),并优先复用现有的A-..K-功能标签(见 核心概念词典第 7 节);- 唯一命中校验:无论多少个
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'"):
// 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 空格缩进):
skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
}
③ replace.nut(替换后的脚本片段):
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/文件,提交前必须运行:它会把补丁打在内存里的原版脚本上并调用.\.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 的一字不差完整原文(pattern 共 57 字节,无任何省略号):
// 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 个核心要点:
- 首尾锚点保证
.text全局唯一命中:单靠48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??(判空后条件跳转)在整个aces.exe里会撞上成百上千处;加上前后+0..+37与+52..+56的寄存器与调用序列后,80 MB 代码段里就只剩这唯一 1 处命中。 edit.offset: 38精准对齐被替换指令首字节:只改写+38..+51这两条指令(8 + 6 = 14字节),前后的上下文锚点纹丝不动。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)。哪怕下个版本目标函数挪到了别的地址,只要相对跳转还在,捕获出的目标就永远准确!expect_original、bytes与asm三重互锁:expect_original(8 + 6 = 14字节)与写入的bytes(5 字节e9 ?? ?? ?? ??无条件跳转 + 9 个90nop= 14 字节)长度必须严丝合缝相等;运行wtotools check-patches时还会调用汇编器把asm编译成机器码与bytes逐字节比对,杜绝手算机器码出错。- 务必分清两套偏移基准点(新手头号易混点!):
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:仓库真实范例见"captures": { "some_flag": { "offset": 2, "type": "rel32", "end": 7 } }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):
"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)
"method": "signature":在指定段(默认".text",可通过"section"覆盖)搜索全局唯一命中的字节特征码,支持captures。"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里的击杀计数字段偏移)。
- 模式 A(默认
"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
文件名必须与 "module" 字段完全同名。由于我们要复用 local_mp_core.jsonc 里已经用 "string_ref"("string": "customScoreParams", "target": "function")定位好的函数 "mission_settings_load",在 "requires" 中声明 "local_mp_core":
// 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:
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 声明 LmpValues 字段
地址一律声明为 uint8_t *,无符号偏移/大小声明为 size_t(有符号位移声明为 ptrdiff_t):
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 绑定 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()中。
#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 定义可读偏移宏
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
第 6 步:实现 local_mp_scores.c、注册到 local_mp_core.c 并加入 build.ps1
- 在
local_mp_scores.c中只读取g_lmp与local_mp_core导出的公共指针: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的 PETimeDateStamp与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)时,按下面四步跟进适配:
- 对只读原版客户端运行版本核对脚本:
该脚本会只读扫描原版客户端,一次性跑完所有
node scripts/record-game-version.ts --game "<原版目录>"patches/exe/、patches/gui/和patches/native/的定位测试。如果三条核心安全锁(ESSENTIAL_FEATURES)中有补丁失效,脚本会直接拒绝生成版本记录并列出阻断项;若核心安全锁全部命中,则会写出patches/versions/<版本号>.jsonc并打印所有unavailable(暂不可用)的非关键补丁/模块。 - 排查失配项并追加新
variant: 打开失配的补丁或原生站点,用第 1 节的 Node 拆包脚本或tools/re/cli.py(优先用find-string找不变的字符串锚点!)查看新版本原版文件发生了什么变化。保留原有旧版本的variant不动,在variants数组中追加一条"written_for": "<新版本号>"的新写法。 - 跑完完整工具链核对:
重新运行
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确认副本完整生成。
- 隔离副本实机进游戏验收后再提交
patches/versions/<版本号>.jsonc: 启动器依赖patches/versions/<版本号>.jsonc向玩家展示「该客户端版本已核对通过」。请在隔离副本里实际登录进机库并完成一局LocalMP对局验收后,再提交patches/versions/<版本号>.jsonc,不要仅凭命令行脚本通过就直接入库。
新建补丁时可直接复制空白脚手架模板:dev-docs/templates/gui/、dev-docs/templates/exe/、dev-docs/templates/native/。
简体中文 · English · Back to Dev Docs
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 and verify that the issue genuinely cannot be solved in
apps/serveror 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 <stock-dir> with your read-only official War Thunder path):
# 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`<stock-dir>\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`<stock-dir>\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), use tools/re/cli.py to locate strings, cross-references, callers, and disassembly (all addresses are hex RVAs, and always pass --exe "<stock-dir>\win64\aces.exe" explicitly):
# 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 "<stock-dir>\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 "<stock-dir>\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 "<stock-dir>\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 "<stock-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<stock-dir>\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/<domain>/<name>/ |
patches/gui/tutorials/immediate-save-skip-tutorial/ |
A few machine instructions or a constant .rdata string in aces.exe |
patches/exe/<domain>/<name>/ |
patches/exe/battle/allow-local-host-bot-spawns/ |
In-process C hooks restoring LocalMP battle host logic (wto_ws.dll) |
patches/native/<module>.jsonc + native/wto-net/src/<module>.c |
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:
- One behavior per directory/module—never bundle unrelated fixes into a single patch definition.
- Start every
patch.jsonc/<module>.jsoncwith 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.
- Write
titleandfeaturesin English (note: a few early historical patches still carry Chinesetitlestrings, but all new patches must writetitlein English), reusing existingA-..K-inventory tags (Glossary — Section 7). - Exact single-variant, single-site match: On any given client build, exactly one
variantmust 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:
// 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):
skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
}
3. replace.nut (the replacement text):
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.jsoncdoes NOT have arequireskey! Do not copy"requires": []from an EXE patch intopatches/gui/, orloadGuiPatcheswill throwDefinitionError! variants[]keys are strictlywritten_for,file,edits.filemust be the exact lowercase,/-separated relative path insidegui.vromfs.binwithout a leading slash (e.g.,"scripts/tutorials/nexttutorialhandler.nut"—archive paths are all lowercased!).edits[]keys are strictlyfind,replace, naming plain filenames directly inside the patch folder (no/or\subdirectories).- Line endings & exact-once matching:
readFragmentstrips any UTF-8 BOM, normalizes\r\nto\n, and removes a single trailing newline at EOF (so Gitautocrlfnever breaks patches).find.nutmust match exactly once in the target script. {{LOCAL_ENDPOINT}}placeholder: Whenever replacement Quirrel code needs the local server address, write{{LOCAL_ENDPOINT}};gui-pack.tsexpands it to127.0.0.1:<port>during copy builds.- Adding a variant for a newer build: Never edit an existing
find.nutin a way that breaks older supported builds—createfind-58.nut/replace-58.nutand append a new entry tovariants. - Mandatory
sq.exebytecode check: Every change underpatches/gui/must pass:.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"check-guiapplies all GUI patches in memory and runssq.exe(compilestring) on every patched.nutscript, catching lexical binding clashes with top-of-filefrom ... import *imports, unbound forward calls, and reserved keywords likebasethat 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 (all 57 pattern bytes, zero ...):
// 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:
- Surrounding anchors guarantee a unique hit:
48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??alone appears hundreds of times across.text, whereas anchoring+0..+37before it and+52..+56after it narrows 80 MB of code down to a single unambiguous hit. edit.offset: 38leaves the anchors untouched: Only the 14 bytes at+38..+51are overwritten.captures.spawn_call(offset: 48, type: "rel32") resolves the jump target dynamically: Thejzinstruction's 4-byte displacement sits at+48..+51, so defaultend = 48 + 4 = 52, yielding target RVA =site + 52 + disp32(0x11b314eon2.61.0.37). Even when future builds shiftUnit::changeAircraft, the captured RVA updates automatically.- Exact 14-byte parity &
asmverification:expect_originalis8 + 6 = 14bytes andbytesis5(e9 ?? ?? ?? ??) +9(90NOPs) = 14 bytes. Runningwtotools check-patchesassemblesasmand verifies byte-for-byte agreement withbytes. - Crucial offset base distinction (most common beginner mistake!):
edit.offset(38) andlocate.captures.*.offset(48) count fromsite(+0oflocate.pattern);edit.fixups[].at(1) andedit.fixups[].end(defaultat + 4 = 5) count from byte0ofedit.bytes(site + 38), right after thee9opcode!
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) orjz rel32(0f 84 ?? ?? ?? ??, 6 B),disp32is at the very end of the instruction, so the defaultend = offset + 4matches the instruction end automatically. - However, when an instruction has trailing immediate byte(s) after
disp32, omitting"end"resolves the wrong address! Takec6 05 ?? ?? ?? ?? 00(mov byte ptr [rip + disp32], 0): the instruction is 7 bytes total (c6 05at0..1,disp32at2..5, trailing immediate00at6, ending at7). Writing{ "offset": 2, "type": "rel32" }defaultsendto2 + 4 = 6, landing 1 byte before the real global variable! You must pass"end": 7:For a real example in the repo, see"captures": { "some_flag": { "offset": 2, "type": "rel32", "end": 7 } }disabled_slots_mask.multiplayerinpatches/native/local_mp_core.jsonc: after31 c0(+0..+1),48 83 3d ?? ?? ?? ?? 00(cmp qword ptr [rip + disp32], 0) spans+2..+9withdisp32atoffset: 5and trailing00at+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):
"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/<module>.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)
"method": "signature": Scans".text"(or a specified"section") for a unique byte pattern, supportingcaptures."method": "string_ref"(packages/exepatch/src/locate/string-ref.ts— most resilient across compiler codegen shifts!): Finds UTF-8string + \0in".rdata"(or"section") and locates 7-byte RIP-relativelea(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-byteleainstruction itself (checked length = 7 bytes); - Mode B (
"target": "function"): Looks up the enclosing function's start RVA in the PE.pdataexception directory (checked length = 0, so no directcaptures—ideal for locating function entry points to hook or use aswithinanchors); - Mode C (
"pattern"+"lea_at", with default"target": "reference"): Matchespatternaround the string reference where the 7-byteleasits at byte offsetlea_at, returning thepatternstart RVA socapturescan read adjacent struct offsets right next to the string reference!
- Mode A (
"method": "within"(packages/exepatch/src/locate/within.ts): Searchespatternstrictly within the[begin, end)PE.pdatabounds of an already-resolved site named in"in"(from an earlier site in the same module or arequiresmodule), 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
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":
// 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 <copy>/win64/wto_ws.cfg (packages/patcher/src/native/native-settings.ts)
During copy builds, the patcher writes the executable's PE identity stamps alongside <site> and <site>.<capture> entries for all completely resolved modules:
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
Add pointer (uint8_t *), unsigned offset (size_t), or signed displacement (ptrdiff_t) fields to struct LmpValues:
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
Wire the wto_ws.cfg keys into SPECS[] using the three storage macros:
A(module, name, field)(LMP_ADDRESS): computes(uint8_t *)GetModuleHandleW(NULL) + rvaand stores the live process pointer;O(module, name, field)(LMP_OFFSET): stores an unsignedsize_tstruct offset or stride;S(module, name, field)(LMP_SIGNED): stores a signedptrdiff_tdisplacement;- Use
derive_values()in the same file when a relative offset must be computed from two captured values (e.g., subtractingecon_change_reqfrom an outerecon_req_*offset).
#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
Expose a descriptive macro backed by g_lmp:
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
File 6: local_mp_scores.c, local_mp_core.c & native/wto-net/build.ps1
- Consume the resolved function and offset in
local_mp_scores.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 callsconfig_native_matches_executable()to verify that the runningaces.exe's PETimeDateStampandSizeOfImagematchwto_ws.cfg(disabling the entireLocalMPbridge ifwto_ws.cfgcame from a different build), loadslocal_mp_core, iteratesMODULES[]in dependency order ({ "local_mp_scores", install_local_mp_score_reader }) callinglmp_values_load(MODULES[i].name)beforeinstall(), and enables all queued hooks in one pass viaMH_ApplyQueued(). - Adding a brand-new
.cfile: Declare its installer inlocal_mp_internal.h, register it inMODULES[](local_mp_core.c), and add the.cfile to$sourcesinnative/wto-net/build.ps1. - Sharing common engine hooks: When two modules need the same target function (e.g.,
unit_on_eventshared bylocal_mp_damage_notificationsandlocal_mp_air_events), define and dispatch it once inlocal_mp_corerather than callingMH_CreateHooktwice 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:
- Run the build recorder against your read-only stock client:
node scripts/record-game-version.ts --game "<stock-dir>"record-game-version.tstests everypatches/exe/,patches/gui/, andpatches/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 writespatches/versions/<version>.jsoncand lists anyunavailableoptional patches/modules. - Add new variants only for failing patches/sites:
Inspect the updated
.nutscript oraces.exefunction using the Step 0 Node snippet ortools/re/cli.py(preferfind-stringanchors!). Keep existingvariantsuntouched so earlier builds continue working, and append a new variant with"written_for": "<new-version>". - Run the full verification suite:
Re-run
record-game-version.tsto confirm zerounavailableitems, then run:.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe".\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\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.tsinto a temporary copy directory to confirm clean assembly.
- Verify live in-game inside an isolated copy BEFORE committing
patches/versions/<version>.jsonc: The launcher relies onpatches/versions/<version>.jsoncto badge a client build as verified. Boot the isolated copy, sign into the hangar, and play through aLocalMPbattle before committingpatches/versions/<version>.jsoncrather than relying on CLI checks alone.
Starter templates for new patches live under dev-docs/templates/gui/, dev-docs/templates/exe/, and dev-docs/templates/native/.