Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+171
View File
@@ -0,0 +1,171 @@
# dm/verify — Verification Tools
中文:[README.zh-CN.md](README.zh-CN.md)
D2R Mobile rewrites the Switch version of the game program and executes it directly on iOS. This directory answers two questions: does the rewritten program behave the same as the original, and has any given change broken something that already worked.
A few terms used throughout this directory:
- **Build output**: the output directory of the rewriter `dm/tools/patch_nso.py` for the three modules `main`, `sdk` and `subsdk0`, located at `$DM_ROOT/build/cache/dm/out/<codename>-<kind>`; there are three kinds: `keypage`, `rules` and `touch`. `dm/tools/product.sh build` produces all of them in one go, and `product.sh path <kind>` prints the path.
- **Host**: `dmhost`, built from `dm/host`, which loads the build output on a Mac and executes the game. Most verification runs against it.
- **Ground truth**: reference data obtained by running the **original** game in a patched Ryujinx emulator — screenshots, per-tick state, command packets, saves. The host's results are compared against it.
- **Tick**: one step of the game's server-side logic. Many criteria are "identical tick by tick".
- **Run directory**: the directory holding all the output of one run (logs, screenshots, record files).
- `$DM_ROOT`: the workspace root, default `~/dm-work`. Game files, build outputs, ground-truth data and run artifacts all live under it and do not go into the repository.
## Read this table first: what you need for what you run
| What you need | What you can run |
|---|---|
| Repository + Python environment | The script self-tests `touchcases/test_lib.py` and `test_accept.py`: their inputs are all synthetic data or stand-ins; they start no host and read no game files |
| Game files + build output (prepared by `./setup.sh`) | `regress.sh` (rewrite-equivalence regression; also needs llvm, see "External tools" below), `fnfuzz.py`, and the host and graphics-layer unit tests (`make -C dm/host/tests run`, `make -C dm/gfx/tests run`) |
| Plus a standard save | `touchchain.sh` (touch feature test cases) |
| Plus ground-truth data | `shotgate.sh` (screenshot gate), `rulegate.sh`, `logicself.sh`, `opmode.sh`, `dm/tools/host_savecmp.sh`, `dm/tools/save_txn_regress.sh`, `gfxq/`, and `accept.sh`, which chains them together |
**The ground-truth data is not in the repository and never will be**: it is a recording of the original game running. The emulator driver scripts used to obtain it (building the emulator, starting a run, driving and recording) are not shipped with the repository either, so the gates in the last row, which depend on ground truth, cannot be run with this repository alone. This page still keeps their descriptions and the ground-truth formats, because the whole verification system rests on ground truth; see "Where the ground truth comes from" and "Data you have to prepare yourself" below.
External tools:
- The Python packages `lz4`, `capstone`, `unicorn`, `numpy` and `Pillow`, installed in `$DM_ROOT/build/cache/dm/venv` (created by `./setup.sh`). Most scripts use this environment's interpreter by default (`DM_PY` overrides it); a few scripts and the `make` targets call `python3` directly, so run `source ~/dm-work/build/cache/dm/venv/bin/activate` first (if you set `DM_ROOT`, use it in place of `~/dm-work`).
- `structck.py` uses `llvm-objdump` and `llvm-objcopy` as an independent disassembler; their directory is given by `LLVM_BIN`, default `/opt/homebrew/opt/llvm@23/bin`. `brew install llvm` does not necessarily install version 23; if that directory does not exist, set `LLVM_BIN=$(brew --prefix llvm)/bin`.
- Several scripts use the `timeout` command; if your system does not have it you have to install it yourself (it is part of GNU coreutils).
## Rewrite-equivalence regression: `regress.sh`
Verifies that "the rewrite has not changed the program's behavior". Needs only the game files and the build output, and finishes in seconds.
```
dm/verify/regress.sh [--fresh] [--struct-only] [build output dir] [module…]
```
By default it verifies `main sdk subsdk0` of the `keypage` build output. It runs three things in order:
| Tool | What it verifies |
|---|---|
| `structck.py` | **Structural check**. Executes no code and checks the rewriter's output word by word: apart from registered cuts, non-code segments are byte-for-byte identical to the original image; the words changed in the code segment are exactly the registered rewrite sites; an independent disassembler recounts the instructions that should be changed, with none missed and none extra; the patch area no longer contains the original instructions that cannot be executed; the bytes of every host gate, argument gate and observation gate equal the template and match the gate table one to one. The full list of checks is in the file header |
| `equiv.py` | **Site-by-site equivalence**: using Unicorn (a CPU emulation library), for each rewrite site, executes the "original instruction" and the "patch block" separately from multiple sets of random state, and compares all general-purpose and vector registers, flags, stack pointer, memory writes, end address and memory-access faults. Includes a mutation self-check: a batch of patch blocks is deliberately broken, and every one of them must be judged non-equivalent |
| `gatefn/` | **Gate function**: builds a test bench on the spot from the host's current `dm/host/entry.S`, executes each gate one by one, and checks the register write-back convention |
- `--struct-only`: runs only the structural check and the gate function check, not `equiv.py`.
- `--fresh`: first regenerates a copy with this worktree's rewriter into `$DM_ROOT/run/verify/dm/fresh/` and verifies that, and also compares it file by file with the given directory; used to detect whether the shared build output is stale.
- Environment variables: `DM_PY`, `DM_NSO_DIR` (directory holding the original modules, default `$DM_ROOT/data/switch/3.3.94012/Update/ExeFS`), `SEED`, `JOBS`, `LLVM_BIN`.
- Output: a summary table at the end, with one row each for 「结构」 (structure) and 「等价」 (equivalence) per module, including the denominator and the coverage (how much was actually covered); the last line is `REGRESS OK|FAIL <build output name>`, and any failure gives exit code 1. The log is at `$DM_ROOT/run/verify/dm/regress_<timestamp>.log`.
Related standalone tools:
- `fnfuzz.py <build output dir> <module> <NSO>`: function-level differential fuzzing. For each function containing a rewrite site, the original image and the rewritten image each execute the whole function on the same random input, and the final states are compared. Slower than `equiv.py`, not part of `regress.sh`, run on its own as needed; see the file header for options.
- `keypage_check.py`: a tool that checks key-page indirect accesses; see the file header for usage.
- `nsoimg.py`: a common module that unpacks an NSO into a memory image, shared by the tools above.
## Host acceptance: `accept.sh`
Runs all the checks in parallel; if any one is red, the whole thing is red.
```
dm/verify/accept.sh [--fast|--full] [build output dir]
```
| Item | Content | Criterion | Prerequisite |
|---|---|---|---|
| ⓪ | `bootchk.sh`: the boot block list (the list of resource blocks pre-read at startup) | The build output directory's `bootlist.tsv` exists, its build number matches `main.cuts.tsv`, it is byte-for-byte identical to `dm/data/bootlist_<build number>.tsv`, its checksums are self-consistent, and it matches the resource pack block by block. The public repository does not ship this list: without it there is simply no prefetch (startup skips one step of decoding ahead of time), but this item reports red; to use it, record one yourself with `dm/tools/tact_bootlist.py`, put it at `dm/data/bootlist_<build number>.tsv` and regenerate the build output | Game files, the boot block list |
| ① | `regress.sh` verifies the build output under test; then `--struct-only` is run on the `touch` build output (the kind compiled into the App) | Two `REGRESS OK` lines | Game files |
| ② | `dm/tools/host_savecmp.sh`: the host replays the input of one ground-truth run, saves and exits, and the save is compared byte by byte with the ground truth's save (`savecmp.py`) | The 6-slot state matches tick by tick; the saves match; the negative control (ground-truth save versus the starting save) must not match; no red lines in the host log | Ground-truth run |
| ②B/C | `rulegate.sh 400` and `logicself.sh <touch build output> 230` | See the next section | Ground-truth run |
| ③ | `shotgate.sh`: the [screenshot gate](screenshot_gate.md) | Every page is green against its ground-truth reference image | Ground-truth reference images |
| ④ | Unit tests: `make -C dm/host/tests run`, `make -C dm/gfx/tests run`, `make -C dm/ios/tests test`, `test_accept.py`, and the two self-tests that belong to the emulator driver scripts (not shipped with the repository) | All six suites pass, with no build or link errors | — |
| ⑤ | Runs ② again under `DM_TEST_LAG=400`: an artificial sleep at the entry of tick 400 creates a "catch-up tick backlog" | The frozen tick still lands on the expected tick; the save criterion is the same as ②; and it is confirmed that the backlog was actually created | Ground-truth run |
| ⑥ | `dm/tools/save_txn_regress.sh`: in a replay run, injects "process killed" and "write failed" by save write count, and checks the committed save directory. Runs only in the full tier | All 4 cases hit; the committed files equal the expected version; the checksums are self-consistent; the negative control holds | Ground-truth run |
| ⑧ | iOS build, compile only without installing (`DM_NOINSTALL=1 dm/ios/run.sh build`) | The build succeeds | Xcode and the signing configuration of `dm/ios` |
| ⑨ | `touchchain.sh` runs all the cases under `touchcases/` | Every case's assertions pass | Standard save |
| ⑩ | `opmode.sh`: after entering a game, switches the operation mode from docked to handheld | A game had been entered before the switch; the game takes two mode-change notifications; the process survives to the time limit without crashing; at least 300 more frames are produced after the switch; the window size is correct; no red lines in the host log | Ground-truth run |
(There is no ⑦ in the list; the numbering follows the script.)
Tiers and scope:
- `--full` (default): the screenshot gate runs all pages, plus ⑥. `--fast`: the screenshot gate samples only the five pages `camp_e stash wild charselect skilltree`, and ⑥ is not run.
- Automatically runs less according to the scope of the change: when the changes are only in `dm/ios` (except source files compiled together with the host) and documentation, only ⓪ ⑧ run; when only in `dm/gfx`, `dm/ios` and documentation, ⓪ ③ ④ ⑧ ⑩ run; in all other cases everything runs. "Changes" means this worktree's committed changes relative to its fork point from the `main` branch plus uncommitted changes; when that branch does not exist, everything runs. Skipped items are listed one by one as 「跳过」 (skipped), not silently. `ACCEPT_ALL=1` forces everything to run.
- Only one instance runs at any moment: the lock is at `$DM_ROOT/run/verify/dm/accept.lock`, and later ones queue.
Output: one line of readings per item, and at the end a 「期望 / 真结果 / 用时」 (expected / actual result / time taken) comparison table and an `ACCEPT OK|RED` line; exit code 0 = all green. Logs are in `$DM_ROOT/run/verify/dm/accept/<timestamp>_<worktree name>_…/`; the directory of a red run keeps a `KEEP` file.
| Environment variable | Effect |
|---|---|
| `TRUTH_RUN` | The ground-truth run directory used by ②⑤⑩, default `$DM_ROOT/data/switch/truth_runs/cvd5` (`cvd5` is just the directory name hard-coded in the script; it has no other meaning) |
| `ACCEPT_ALL=1` | Do not omit anything by change scope |
| `ACCEPT_SCOPE_ONLY=1` | Print only the scope decision line and exit; together with `ACCEPT_SCOPE_CH=<path list>` you can pass the changed paths directly to try it |
| `FUNC_JOBS` | How many cases ⑨ runs at once, default 2 |
| `FUNC_LIMIT_S` | The hang-guard timeout in seconds for each case of ⑨, default 60 |
| `DM_TOUCH_OUT`, `DM_RULE_OUT`, `DM_LOGICSELF_OUT` | The build output directories used by ①, ②B and ②C |
`test_accept.py` is the wiring test of `accept.sh` itself: it substitutes stand-in scripts for the items and verifies only the wiring of the fast / full tiers and failure propagation; it does not run the real host.
### The two logic gates
- `rulegate.sh [ticks=400] [build output=rules]`: the host replays the input of one ground-truth run using the `rules` build output, and the 6-slot state is compared tick by tick with the ground truth's `ticks.jsonl` (the comparison script `selfcmp.py` belongs to the emulator driver scripts and is not shipped with the repository). The ground-truth run directory is given by `DM_RULE_TRUTH` and must contain `meta.json`, `c2s.jsonl` and `ticks.jsonl`. Before starting, it first checks whether the build output was produced with the current `patch_nso.py`, and refuses to run if it is stale. The last line is `RULEGATE OK|RED`.
- `logicself.sh [build output=touch] [ticks=230]`: the build output is compared with **its own baseline**. It replays the same ground-truth run input and compares the per-tick unit counts and hashes with `logicself/touch.json` in the repository, to detect "something that should not affect logic was changed, yet the logic changed". The ground-truth run directory is given by `DM_LOGICSELF_TRUTH` (default `$DM_ROOT/data/switch/truth_runs/cvd5`). `LOGICSELF_REBASE=1` re-records the baseline: it runs twice in a row and writes only if the two runs agree. The last line is `LOGICSELF OK|RED`.
Each of the three record file formats has its own page: [tick_state_format.md](tick_state_format.md), [command_packet_format.md](command_packet_format.md), [ui_message_stream.md](ui_message_stream.md).
The internal branch-merging workflow script is not shipped with the repository; outside contributions do not need it.
## Screenshot gate: `shotgate.sh`
The key screens drawn by the host are compared page by page with the ground-truth reference images; there are currently 17 pages. The criteria, the page spec, and how to produce reference images are all in [screenshot_gate.md](screenshot_gate.md).
Companion tools: `hostshot.sh` (starts one host and takes one screenshot), `shotgate.py` (compares one page), `dynmask.py` (makes animation masks), `shotgate_gc.sh` (cleans up old run artifacts), `logred.sh` (the keyword table of host-log red lines, shared by the screenshot gate and `accept.sh`).
## Touch feature test cases: `touchcases/` and `touchchain.sh`
Each case is a pair of files under `touchcases/<name>/`:
- `script.txt`: the touch-point script (at which moment, which finger, pressed or lifted where), handed to the host's touch front end via `DM_TOUCH_SCRIPT`.
- `assert.py`: the assertions. It reads the four records the host writes in the run directory — per-tick state `ticks.jsonl`, command packets `c2s.jsonl`, UI messages `uimsg.jsonl`, state probes `state.jsonl` — and judges whether this touch produced the result it should (whether an item moved, whether a certain command packet was sent, whether a panel opened). The common functions are in `touchcases/lib.py`, whose own tests are `touchcases/test_lib.py`.
Optional files: `prefix` (one line, the path of a prefix directory; this segment of ground-truth input is replayed first, taking the character to a location such as the wilderness before starting), `ticks` (one line, the total tick count for this case), `pending` (a case with this file is not run but is listed; the first line gives the reason).
```
dm/verify/touchchain.sh <case name>
```
- Cases run on the same UI overlay as the iOS package (`dm/ios/tools/gen_romfs_overlay.py` generates it on the spot from the game resources), so what is tested is the layout the player actually sees.
- The criteria are all logical results, so the run does not follow the product's pacing: rendering is not rate-limited, the game clock is fast-forwarded in fixed steps, and the touch-point script advances by server ticks, so the result is independent of the machine's load.
- The last line is `TOUCHCHAIN <用例> OK|RED 用时 N 秒` (`TOUCHCHAIN <case> OK|RED took N seconds`). The run directory of a passing case is deleted; `DM_TOUCH_KEEP=1` keeps it; red ones are kept in `$DM_ROOT/run/verify/dm/touchchain/`.
- Environment variables: `DM_HOST_OUT` (build output, default `touch`), `DM_TOUCH_SAVE` (the `0/` directory of the starting save), `DM_TOUCH_PREFIX`, `DM_TOUCH_RUNROOT`, `DM_ROMFS_SRC`, `DM_TICKS_N`.
The prerequisite is a standard save (see below). The existing assertions were written against the content of that save — which inventory cells hold items, which skills the character has learned — so with a different save the assertions have to be changed accordingly. Cases with a `prefix` (currently `skill_main`) also need the corresponding ground-truth prefix directory.
## Other tools
| File | Purpose |
|---|---|
| `savecmp.py` | Byte-by-byte comparison of two save directories. Checksum fields are each checked for self-consistency, the two wall-clock time fields are checked for their source, and everything else must be identical |
| `savesha.sh` | Computes the content fingerprint of a save directory |
| `uicmp.py`, `c2scmp.py` | Comparison of UI message streams and command packet sequences; the rules are on their respective format pages |
| `oracle/swgdb.py`, `oracle/swtick.py` | A minimal client for the emulator's GDB interface; per-tick state is read through it |
| `bootlist_static.py` | Static check of the boot block list, called by `bootchk.sh` |
| `gfxq/` | Image quality metric and visual-equivalence ruler, see [gfxq/image_quality.md](gfxq/image_quality.md) |
| `overlay_contract.json` | A draft contract for acceptance of the iOS touch overlay controls; no script reads it at present |
## Where the ground truth comes from
The ground truth comes from Ryujinx (an open-source Switch emulator) running the original game. Stock Ryujinx is not enough and needs a few patches: so that it can directly load an unpacked game directory, can be fed key presses and take screenshots from a script, and can read out the game's internal state at specified locations.
The scripts that build this emulator, start a run, and drive and record it are not shipped with the repository, so ground truth cannot be recorded with this repository alone, and the gates that depend on it cannot be run either. What remains in the repository is the minimal reading side, `oracle/swgdb.py` and `oracle/swtick.py` (a client for the emulator's GDB interface), and the descriptions of the three record formats.
How recording works: through the emulator's GDB interface, the driver script sets breakpoints at the game's UI message dispatch point and the server tick entry, and advances by the game's own messages: every step is "wait for the precondition message → send input → wait for the confirmation message", with no guessing by seconds. The game-creation seed and game-creation time are pinned to the same values on both sides; the host-side counterparts are `DM_GAME_SEED` and `DM_FIXED_TIME`. The `main` the emulator runs carries the cuts registered by the rewriter (except those marked 「仅宿主」 (host only)), so the ground truth and the host run a program with the same targeted modifications.
Recording one run yields a "ground-truth run" directory containing: `uimsg.jsonl`, `ticks.jsonl`, `c2s.jsonl` (the three kinds of record; the formats are on their respective pages), `events.jsonl` (the event stream of the driving process), `meta.json` (seed, time, starting-save fingerprint, etc.), `save_after/` (the save at the end), `shots/` (screenshots).
## Data you have to prepare yourself
| Data | Where scripts look for it | Used by | How to get it |
|---|---|---|---|
| Standard save | `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/` (containing subdirectories such as `0/`) | Almost every check that runs the host, and the ground-truth emulator | Your own save. `dm/tools/host_savecmp.sh` also identifies the save by `$DM_ROOT/data/switch/<save name>/MANIFEST.sha256`: each line is "sha256 + two spaces + `0000000000000001/relative path`", sorted by path |
| One baseline ground-truth run | `$DM_ROOT/data/switch/truth_runs/cvd5/` | ②⑤⑥⑩ of `accept.sh`, `logicself.sh` | Recorded with the emulator driver scripts (not shipped with the repository). Needs `meta.json`, `c2s.jsonl`, `ticks.jsonl`, `events.jsonl`, `save_after/0`. The specific parameters used to record this run were not kept in the repository |
| The rule gate's ground-truth run | Given by `DM_RULE_TRUTH` | `rulegate.sh` | Same as above; needs `meta.json`, `c2s.jsonl`, `ticks.jsonl` |
| Screenshot gate reference images, animation masks, and the replay files of each page | The paths written in the page specs, all under `$DM_ROOT/data/switch/` | `shotgate.sh`, `gfxq/` | See [screenshot_gate.md](screenshot_gate.md) |
| Prefix directories of touch test cases | The path written in the case's `prefix` file | `touchchain.sh skill_main` | A segment of ground-truth input: `manifest.json` plus `c2s.jsonl` |
| Replay file for the image quality metric's combat frames | Path hard-coded in `gfxq/shoot.sh` and `gfxq/ruler.sh` | `gfxq/` | The `c2s.jsonl` of a ground-truth run that includes combat |
A ground-truth run's `meta.json` records the fingerprint of the starting save, and the scripts that replay it check it; so once the standard save is changed, the ground-truth runs and reference images all have to be re-recorded with the new save.
+171
View File
@@ -0,0 +1,171 @@
# dm/verify — 验证工具
English: [README.md](README.md)
D2R Mobile 把 Switch 版游戏程序改写后直接在 iOS 上执行。这个目录回答两个问题:改写后的程序与原版行为是否一致;每次改动有没有把已经对的东西弄坏。
几个贯穿全目录的词:
- **产物**:改写器 `dm/tools/patch_nso.py` 对 `main`、`sdk`、`subsdk0` 三个模块的输出目录,位于 `$DM_ROOT/build/cache/dm/out/<代号>-<种类>`,种类有 `keypage`、`rules`、`touch` 三种。`dm/tools/product.sh build` 一次出齐,`product.sh path <种类>` 打印路径。
- **宿主**:`dm/host` 编出的 `dmhost`,在 Mac 上装载产物并执行游戏。大多数验证跑的是它。
- **真值**:用打了补丁的 Ryujinx 模拟器跑**原版**游戏得到的参照数据——截图、逐拍状态、命令包、存档。宿主的结果与它比。
- **拍**:游戏服务端逻辑的一步。很多判据是「逐拍相同」。
- **局目录**:一次运行的全部输出(日志、截图、记录文件)所在的目录。
- `$DM_ROOT`:工作区根目录,缺省 `~/dm-work`。游戏文件、产物、真值数据、运行现场都在它下面,不进仓库。
## 先看这张表:跑什么需要什么
| 需要的东西 | 能跑的 |
|---|---|
| 仓库 + Python 环境 | `touchcases/test_lib.py`、`test_accept.py` 这两套脚本自测:输入都是合成数据或替身,不起宿主、不读游戏文件 |
| 游戏文件 + 产物(`./setup.sh` 备好) | `regress.sh`(改写等价回归,另需 llvm,见下文「外部工具」)、`fnfuzz.py`、宿主与图形层单测(`make -C dm/host/tests run`、`make -C dm/gfx/tests run`) |
| 再加一份标准存档 | `touchchain.sh`(触摸功能用例) |
| 再加真值数据 | `shotgate.sh`(画面闸门)、`rulegate.sh`、`logicself.sh`、`opmode.sh`、`dm/tools/host_savecmp.sh`、`dm/tools/save_txn_regress.sh`、`gfxq/`,以及把它们串起来的 `accept.sh` |
**真值数据仓库里没有,也不会有**:它是原版游戏的运行记录。取真值用的模拟器驱动脚本(构建模拟器、起局、驱动与录制)也不随仓库提供,所以最后一行这些依赖真值的闸门在仓库外跑不了。本页仍保留它们的说明与真值的格式,因为整套验证以真值为依据;见下文「真值从哪来」与「要自己准备的数据」。
外部工具:
- Python 包 `lz4`、`capstone`、`unicorn`、`numpy`、`Pillow`,装在 `$DM_ROOT/build/cache/dm/venv`(`./setup.sh` 建)。多数脚本缺省用这个环境的解释器,可用 `DM_PY` 换;个别脚本与各个 `make` 直接调 `python3`,所以先执行 `source ~/dm-work/build/cache/dm/venv/bin/activate`(设了 `DM_ROOT` 就把 `~/dm-work` 换成它)再跑。
- `structck.py` 用 `llvm-objdump` 与 `llvm-objcopy` 作独立反汇编器,目录由 `LLVM_BIN` 指定,缺省 `/opt/homebrew/opt/llvm@23/bin`。`brew install llvm` 装到的不一定是 23 版,这个目录不存在时设 `LLVM_BIN=$(brew --prefix llvm)/bin`。
- 多个脚本用到 `timeout` 命令;系统里没有的话要自己装(GNU coreutils 里有)。
## 改写等价回归:`regress.sh`
验证「改写没有改变程序行为」。只要游戏文件与产物,秒级跑完。
```
dm/verify/regress.sh [--fresh] [--struct-only] [产物目录] [模块…]
```
缺省验 `keypage` 产物的 `main sdk subsdk0`。它依次跑三样:
| 工具 | 验什么 |
|---|---|
| `structck.py` | **结构核对**,不执行代码,逐字核对改写器的输出:除登记过的剪口外,非代码段与原映像逐字节相同;代码段里被改的字恰好是登记的改写点;用独立反汇编器重数一遍该改的指令,一条不漏、一条不多;补丁区里不再出现原来不能执行的指令;每个宿主门、参数门、观测门的字节等于模板,并与门表一一对上。核对项的完整清单在文件头 |
| `equiv.py` | **逐处等价**:用 Unicorn(CPU 模拟库)对每一处改写,以多组随机状态分别执行「原指令」与「补丁块」,比较全部通用寄存器与向量寄存器、标志位、栈指针、内存写入、结束地址与访存异常。带变异自检:故意把一批补丁块改坏,必须全部被判出不等价 |
| `gatefn/` | **门功能**:用宿主现行的 `dm/host/entry.S` 现编一个测试台,逐个门执行,核对寄存器回写的约定 |
- `--struct-only`:只跑结构核对与门功能,不跑 `equiv.py`。
- `--fresh`:先用本工作树的改写器重出一份到 `$DM_ROOT/run/verify/dm/fresh/` 再验,并与给定目录逐文件比对,用来发现共用的产物是否过期。
- 环境变量:`DM_PY`、`DM_NSO_DIR`(原版模块所在目录,缺省 `$DM_ROOT/data/switch/3.3.94012/Update/ExeFS`)、`SEED`、`JOBS`、`LLVM_BIN`。
- 输出:末尾一张汇总表,每个模块「结构」「等价」各一行,带分母与射程(实际覆盖了多少);末行 `REGRESS OK|FAIL <产物名>`,任何一项失败退出码 1。日志在 `$DM_ROOT/run/verify/dm/regress_<时刻>.log`。
相关的独立工具:
- `fnfuzz.py <产物目录> <模块> <NSO>`:函数级差分模糊测试。对每个含改写点的函数,原映像与改写映像各自整函数执行同样的随机输入,比终态。比 `equiv.py` 慢,不在 `regress.sh` 里,按需单跑;选项见文件头。
- `keypage_check.py`:检查键页间接访问的工具,用法见文件头。
- `nsoimg.py`:把 NSO 解成内存映像的公共模块,上面几个工具共用。
## 宿主验收:`accept.sh`
把各项检查并行跑一遍,任一项红即整体红。
```
dm/verify/accept.sh [--fast|--full] [产物目录]
```
| 项 | 内容 | 判据 | 前提 |
|---|---|---|---|
| ⓪ | `bootchk.sh`:启动块清单(启动时预读的资源块列表) | 产物目录的 `bootlist.tsv` 存在、构建号与 `main.cuts.tsv` 一致、与 `dm/data/bootlist_<构建号>.tsv` 逐字节相同、校验和自洽、逐块与资源包一致。公开仓库不带这份清单:缺了只是不预取、启动时少一步提前解码,但这一项会报红;要用的话拿 `dm/tools/tact_bootlist.py` 自己录一份,放到 `dm/data/bootlist_<构建号>.tsv` 再重出产物 | 游戏文件、启动块清单 |
| ① | `regress.sh` 验被测产物;再对 `touch` 产物(编进 App 的那一种)跑 `--struct-only` | 两行 `REGRESS OK` | 游戏文件 |
| ② | `dm/tools/host_savecmp.sh`:宿主回放一局真值的输入,存盘退出,存档与真值的存档逐字节比(`savecmp.py`) | 逐拍 6 格状态一致;存档一致;负对照(真值存档对起始存档)必须不一致;宿主日志无红线 | 真值局 |
| ②B/C | `rulegate.sh 400` 与 `logicself.sh <touch 产物> 230` | 见下节 | 真值局 |
| ③ | `shotgate.sh`:[画面闸门](screenshot_gate.zh-CN.md) | 每页对真值参照图绿 | 真值参照图 |
| ④ | 单测:`make -C dm/host/tests run`、`make -C dm/gfx/tests run`、`make -C dm/ios/tests test`、`test_accept.py`,以及模拟器驱动脚本自带的两套自测(不随仓库提供) | 六套全过,无构建或链接错误 | — |
| ⑤ | 把 ② 在 `DM_TEST_LAG=400` 下再跑一遍:第 400 拍入口人为睡一会儿,造出「补拍积压」 | 冻结拍仍落在预期的拍;存档判据同 ②;并核实积压确实造出来了 | 真值局 |
| ⑥ | `dm/tools/save_txn_regress.sh`:在回放局里按存档写入次数注入「进程被杀」「写失败」,核对已提交的存档目录。只在全档跑 | 4 例全部命中;已提交的文件等于期望版本;校验和自洽;负对照成立 | 真值局 |
| ⑧ | iOS 构建,只编不装(`DM_NOINSTALL=1 dm/ios/run.sh build`) | 构建成功 | Xcode 与 `dm/ios` 的签名配置 |
| ⑨ | `touchchain.sh` 跑 `touchcases/` 下全部用例 | 每例断言通过 | 标准存档 |
| ⑩ | `opmode.sh`:进局后把运行模式从主机切到掌机 | 切换前已进局;游戏取走两条模式变更通知;进程活到时限、不崩;切换后至少再出 300 帧;窗口尺寸正确;宿主日志无红线 | 真值局 |
(清单里没有 ⑦,序号沿用脚本里的。)
档位与范围:
- `--full`(缺省):画面闸门跑全部页,加 ⑥。`--fast`:画面闸门只抽 `camp_e stash wild charselect skilltree` 五页,不跑 ⑥。
- 按改动范围自动少跑:改动只在 `dm/ios`(被宿主一起编译的源文件除外)与文档时只跑 ⓪ ⑧;只在 `dm/gfx`、`dm/ios` 与文档时跑 ⓪ ③ ④ ⑧ ⑩;其余情况全量。「改动」指本工作树相对 `main` 分支分叉点的已提交改动加未提交改动;没有这个分支时按全量跑。被跳过的项会逐项列出「跳过」,不静默。`ACCEPT_ALL=1` 强制全量。
- 同一时刻只跑一路:锁在 `$DM_ROOT/run/verify/dm/accept.lock`,后来的排队等。
输出:每项一行读数,末尾一张「期望 / 真结果 / 用时」对照表与 `ACCEPT OK|RED` 一行;退出码 0 = 全绿。日志在 `$DM_ROOT/run/verify/dm/accept/<时刻>_<工作树名>_…/`,红的那次目录里会留一个 `KEEP` 文件。
| 环境变量 | 作用 |
|---|---|
| `TRUTH_RUN` | ②⑤⑩ 用的真值局目录,缺省 `$DM_ROOT/data/switch/truth_runs/cvd5`(`cvd5` 只是脚本里写死的目录名,没有别的含义) |
| `ACCEPT_ALL=1` | 不按改动范围省略 |
| `ACCEPT_SCOPE_ONLY=1` | 只打印范围判定那一行就退出;配 `ACCEPT_SCOPE_CH=<路径清单>` 可以直接给改动路径来试 |
| `FUNC_JOBS` | ⑨ 同时跑几例,缺省 2 |
| `FUNC_LIMIT_S` | ⑨ 每例的卡死兜底秒数,缺省 60 |
| `DM_TOUCH_OUT`、`DM_RULE_OUT`、`DM_LOGICSELF_OUT` | ①、②B、②C 所用产物目录 |
`test_accept.py` 是 `accept.sh` 自己的接线测试:用替身脚本顶替各项,只验快 / 全档的接线与失败传播,不跑真宿主。
### 两道逻辑闸门
- `rulegate.sh [拍数=400] [产物=rules]`:宿主用 `rules` 产物回放一局真值的输入,逐拍 6 格状态与真值的 `ticks.jsonl` 对拍(对拍脚本 `selfcmp.py` 属于模拟器驱动脚本那一组,不随仓库提供)。真值局目录由 `DM_RULE_TRUTH` 指定,须有 `meta.json`、`c2s.jsonl`、`ticks.jsonl`。开跑前先核产物是不是用当前的 `patch_nso.py` 出的,过期就拒跑。末行 `RULEGATE OK|RED`。
- `logicself.sh [产物=touch] [拍数=230]`:产物与**它自己的基线**比。回放同一局真值输入,把逐拍的单位数与哈希同仓库里的 `logicself/touch.json` 比,用来发现「改了不该影响逻辑的东西,逻辑却变了」。真值局目录由 `DM_LOGICSELF_TRUTH` 指定(缺省 `$DM_ROOT/data/switch/truth_runs/cvd5`)。`LOGICSELF_REBASE=1` 重录基线:连跑两遍,两遍一致才写入。末行 `LOGICSELF OK|RED`。
三种记录文件的格式各有一页:[tick_state_format.zh-CN.md](tick_state_format.zh-CN.md)、[command_packet_format.zh-CN.md](command_packet_format.zh-CN.md)、[ui_message_stream.zh-CN.md](ui_message_stream.zh-CN.md)。
内部的分支合并流程脚本不随仓库提供,外部贡献不需要它。
## 画面闸门:`shotgate.sh`
宿主画出的关键画面与真值参照图逐页比,现有 17 页。判据、页规格、怎么出参照图都在 [screenshot_gate.zh-CN.md](screenshot_gate.zh-CN.md)。
配套的小工具:`hostshot.sh`(起一个宿主截一张图)、`shotgate.py`(比一页)、`dynmask.py`(做动画遮罩)、`shotgate_gc.sh`(清旧现场)、`logred.sh`(宿主日志红线关键字表,画面闸门与 `accept.sh` 共用)。
## 触摸功能用例:`touchcases/` 与 `touchchain.sh`
每个用例是 `touchcases/<名>/` 下的一对文件:
- `script.txt`:触点脚本(哪个时刻、哪根手指、在哪按下或抬起),经 `DM_TOUCH_SCRIPT` 交给宿主的触摸前端。
- `assert.py`:断言。读局目录里宿主写下的四份记录——逐拍状态 `ticks.jsonl`、命令包 `c2s.jsonl`、UI 消息 `uimsg.jsonl`、状态探针 `state.jsonl`——判断这次触摸有没有产生该有的结果(物品挪没挪、发没发某个命令包、面板开没开)。公共函数在 `touchcases/lib.py`,它自己的测试是 `touchcases/test_lib.py`。
可选文件:`prefix`(一行,一个前缀目录的路径;先回放这段真值输入,把角色带到野外等位置再开始)、`ticks`(一行,本例总拍数)、`pending`(有这个文件的用例不跑,但会被列出,首行写原因)。
```
dm/verify/touchchain.sh <用例名>
```
- 用例跑在与 iOS 包相同的界面覆盖层上(`dm/ios/tools/gen_romfs_overlay.py` 由游戏资源现生成),测的是玩家实际看到的布局。
- 判据都是逻辑结果,所以不按产品节奏跑:出图不限速,游戏时钟按固定步长快进,触点脚本按服务端的拍推进,结果与本机负载无关。
- 末行 `TOUCHCHAIN <用例> OK|RED 用时 N 秒`。通过的局目录会删掉,`DM_TOUCH_KEEP=1` 保留;红的保留在 `$DM_ROOT/run/verify/dm/touchchain/`。
- 环境变量:`DM_HOST_OUT`(产物,缺省 `touch`)、`DM_TOUCH_SAVE`(起始存档的 `0/` 目录)、`DM_TOUCH_PREFIX`、`DM_TOUCH_RUNROOT`、`DM_ROMFS_SRC`、`DM_TICKS_N`。
前提是一份标准存档(见下文)。现有断言是照那份存档的内容写的——哪个背包格里有物品、角色学了什么技能——换一份存档就要相应改断言。带 `prefix` 的用例(现有 `skill_main`)还需要对应的真值前缀目录。
## 其他工具
| 文件 | 用途 |
|---|---|
| `savecmp.py` | 两份存档目录逐字节对拍。校验和字段各自核自洽,两处墙钟时间字段核来源,其余必须全同 |
| `savesha.sh` | 算一份存档目录的内容指纹 |
| `uicmp.py`、`c2scmp.py` | UI 消息流、命令包序列的对比,规则见各自的格式页 |
| `oracle/swgdb.py`、`oracle/swtick.py` | 模拟器 GDB 接口的最小客户端;经它读逐拍状态 |
| `bootlist_static.py` | 启动块清单的静态核对,`bootchk.sh` 调用 |
| `gfxq/` | 画质度量与视觉等价尺子,见 [gfxq/image_quality.zh-CN.md](gfxq/image_quality.zh-CN.md) |
| `overlay_contract.json` | iOS 触摸覆盖层控件验收的约定草稿;目前没有脚本读取它 |
## 真值从哪来
真值来自 Ryujinx(一个开源的 Switch 模拟器)跑原版游戏。原版 Ryujinx 不够用,要打几处补丁:让它能直接加载解包的游戏目录、能被脚本喂按键与截图、能在指定位置读出游戏内部状态。
构建这个模拟器、起局、驱动与录制用的脚本不随仓库提供,所以只凭本仓库录不出真值,依赖真值的闸门也就跑不了。仓库里留下的是读取这一侧的最小部件 `oracle/swgdb.py`、`oracle/swtick.py`(模拟器 GDB 接口的客户端),以及三种记录的格式说明。
录制的做法:驱动脚本经模拟器的 GDB 接口,在游戏的 UI 消息投递处与服务端拍入口下断点,按游戏自己的消息推进——每一步都是「等前置消息 → 发输入 → 等确认消息」,不按秒数猜。建局种子与建局时刻两边定成同一个值,宿主侧对应 `DM_GAME_SEED`、`DM_FIXED_TIME`。模拟器跑的 `main` 带着改写器登记的剪口(标为「仅宿主」的除外),所以真值与宿主跑的是带同样定点修改的程序。
录一局得到一个「真值局」目录,里面有:`uimsg.jsonl`、`ticks.jsonl`、`c2s.jsonl`(三种记录,格式见各自的页)、`events.jsonl`(驱动过程的事件流)、`meta.json`(种子、时刻、起始存档指纹等)、`save_after/`(结束时的存档)、`shots/`(截图)。
## 要自己准备的数据
| 数据 | 脚本找它的位置 | 用它的 | 怎么来 |
|---|---|---|---|
| 标准存档 | `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/`(里面有 `0/` 等子目录) | 几乎所有跑宿主的检查、真值模拟器 | 读者自己的存档。`dm/tools/host_savecmp.sh` 还按 `$DM_ROOT/data/switch/<存档名>/MANIFEST.sha256` 认存档:每行「sha256 + 两个空格 + `0000000000000001/相对路径`」,按路径排序 |
| 一局基准真值局 | `$DM_ROOT/data/switch/truth_runs/cvd5/` | `accept.sh` 的 ②⑤⑥⑩、`logicself.sh` | 用模拟器驱动脚本录(不随仓库提供)。需要 `meta.json`、`c2s.jsonl`、`ticks.jsonl`、`events.jsonl`、`save_after/0`。录这一局用的具体参数仓库里没有留下 |
| 规则闸门的真值局 | `DM_RULE_TRUTH` 指定 | `rulegate.sh` | 同上,需要 `meta.json`、`c2s.jsonl`、`ticks.jsonl` |
| 画面闸门参照图、动画遮罩、各页的回放文件 | 页规格里写的路径,都在 `$DM_ROOT/data/switch/` 下 | `shotgate.sh`、`gfxq/` | 见 [screenshot_gate.zh-CN.md](screenshot_gate.zh-CN.md) |
| 触摸用例的前缀目录 | 用例的 `prefix` 文件里写的路径 | `touchchain.sh skill_main` | 一段真值输入:`manifest.json` 加 `c2s.jsonl` |
| 画质度量战斗帧的回放文件 | 路径写死在 `gfxq/shoot.sh`、`gfxq/ruler.sh` | `gfxq/` | 一局带战斗的真值局的 `c2s.jsonl` |
真值局的 `meta.json` 里记着起始存档的指纹,回放它的脚本会核对;所以标准存档一换,真值局、参照图都要用新存档重录。
+237
View File
@@ -0,0 +1,237 @@
#!/bin/bash
# Switch 路线验收入口:⓪ 启动块清单 ① 改写等价回归 ② 存档逐字节对拍 ③ 对真值的画面闸门 ④ 单测 ⑤ 补拍积压确定性 ⑥ 全档存档事务 ⑧ iOS 构建 ⑨ 功能用例 touchchain ⑩ 局内切运行模式(①–⑩ 并行);任一项红即整体红。
# r 版本切现行之前必须跑;「完成」以它为准。
# 用法:dm/verify/accept.sh [--fast|--full] [产物目录=out/<当前代号>-keypage];缺省全档(17 页 + 存档事务 4 例),快档只抽已批准 5 页,⓪①②④⑤不变。
# 输出:每项一行读数 + 末尾「期望 → 真结果」对位表 + 总用时;日志在 $DM_ROOT/run/verify/dm/accept/<时刻>/;退出码 0 = 全绿
# 按改动范围选项(先少干活)。改动 = 本树相对 main 分叉点的已提交改动 + 未提交改动的路径并集。映射表:
# 全部路径 ⊂ { dm/ios/**、docs/**、*.md } → 只跑 ⓪ ⑧(iOS 壳与文档进不了宿主:不跑回归 / 对拍 / 闸门 / 单测 / 功能用例 / 切模式)
# 全部路径 ⊂ { dm/gfx/**、dm/ios/**、docs/**、*.md } → 跑 ⓪ ③ ④ ⑧ ⑩(图形改动不动改写产物与存档逻辑:不跑 ① ② ②B/C ⑤ ⑥ ⑨)
# 其余(dm/host、dm/verify、dm/tools、dm/data、重命名、拿不准的任何路径)、没有改动(= 主干头复核)、ACCEPT_ALL=1 → 全量
# 被跳过的项在输出与对位表里逐项列「⏭ 跳过」,不静默。
# Acceptance entry for the Switch route: (0) boot block list (1) rewrite equivalence regression (2) byte-for-byte save comparison (3) screenshot gate against ground truth (4) unit tests (5) catch-up tick backlog determinism (6) full-mode save transactions (8) iOS build (9) functional cases touchchain (10) switching operation mode in game ((1)-(10) in parallel); any failing item fails the whole run.
# Must be run before an r version is made current; "done" is defined by it.
# Usage: dm/verify/accept.sh [--fast|--full] [build output directory=out/<current codename>-keypage]; default is full mode (17 pages + 4 save transaction cases), fast mode samples only the 5 approved pages, (0)(1)(2)(4)(5) unchanged.
# Output: one readout line per item + an "expected -> actual result" side-by-side table at the end + total time; logs in $DM_ROOT/run/verify/dm/accept/<timestamp>/; exit code 0 = all green
# Items are selected by change scope (do less work first). Change = the union of paths of this tree's committed changes relative to the fork point from main + uncommitted changes. Mapping table:
# all paths ⊂ { dm/ios/**, docs/**, *.md } -> run only (0) (8) (the iOS shell and docs cannot get into the host: no regression / comparison / gate check / unit tests / functional cases / mode switch)
# all paths ⊂ { dm/gfx/**, dm/ios/**, docs/**, *.md } -> run (0) (3) (4) (8) (10) (graphics changes do not touch the rewrite build output or save logic: no (1) (2) (2)B/C (5) (6) (9))
# everything else (dm/host, dm/verify, dm/tools, dm/data, renames, any path in doubt), no change (= recheck of the main head), ACCEPT_ALL=1 -> full set
# Skipped items are listed one by one as 「⏭ 跳过」(skipped) in the output and the side-by-side table, not silently.
set -u
export LC_ALL=C
HERE=$(cd "$(dirname "$0")" && pwd)
MODE=full
case "${1:-}" in --fast) MODE=fast; shift;; --full) shift;; --*) echo "ACCEPT RED 未知档位 $1"; exit 2;; esac
OUT=${1:-$(bash "$(dirname "$0")/../tools/product.sh" path keypage)}
TR=${TRUTH_RUN:-${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/cvd5}
# 验收入口不得过期(在 dm-gfx 树跑的 accept 落后 main 26 个验证提交——旧仓库页按时长推杆、产物 r12,偶发红无意义):
# 本树缺 main 上任何改动 dm/verify 的提交即拒跑;超前(正在改验收脚本的分支)不拦
# The acceptance entry must not be stale (an accept run in the dm-gfx tree was 26 verification commits behind main -- the old stash page pushed the stick by duration, build output r12, and the sporadic failures were meaningless):
# if this tree lacks any commit on main that changes dm/verify, refuse to run; being ahead (a branch that is changing the acceptance scripts) is not blocked
STALE=$(git -C "$HERE" log --no-merges --oneline HEAD..main -- "$HERE" 2>/dev/null | wc -l | tr -d ' ')
[ "${STALE:-0}" = 0 ] || { echo "🔴 ACCEPT 拒跑:本树 dm/verify 落后 main $STALE 个验证提交(验收入口过期,读数无意义)——先合入 main 再跑"; git -C "$HERE" log --no-merges --oneline HEAD..main -- "$HERE" | head -5; exit 1; }
# 全局锁(同一时刻只跑一路 accept——多棵工作树共用本脚本,负载叠加会拖慢并诱发时序红;串行只降噪,负载下的时序红本身仍是缺陷要修)
# 去锁进行中:共享路径已按「时刻_树名_进程号」隔离;墙钟 / 负载类判据改完后再换成按工作树的锁
# Global lock (only one accept runs at any moment -- several worktrees share this script, and stacked load slows things down and induces timing failures; serializing only reduces noise, and a timing failure under load is itself still a defect to fix)
# Lock removal in progress: shared paths are already isolated by "timestamp_treename_pid"; once the wall clock / load criteria are changed it will be replaced by a per-worktree lock
TREE=$(basename "$(git -C "$HERE" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$HERE")")
LOCK=${DM_ROOT:-$HOME/dm-work}/run/verify/dm/accept.lock; ME="${ACCEPT_OWNER:-$TREE} $(git -C "$HERE" rev-parse --abbrev-ref HEAD 2>/dev/null)"
while ! mkdir "$LOCK" 2>/dev/null; do
op=$(cat "$LOCK/pid" 2>/dev/null)
if [ -n "$op" ] && ! kill -0 "$op" 2>/dev/null; then echo "接管陈旧锁(pid $op 已不在:$(cat "$LOCK/owner" 2>/dev/null))"; rm -rf "$LOCK"; continue; fi
[ "${_waited:-}" ] || { echo "等待 $(cat "$LOCK/owner" 2>/dev/null)(pid ${op:-?})的 accept"; _waited=1; }
sleep 2
done
echo $$ > "$LOCK/pid"; echo "$ME" > "$LOCK/owner"; trap 'rm -rf "$LOCK"' EXIT
mkdir -p "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/accept"
L=$(mktemp -d "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/accept/$(date +%m%d_%H%M%S)_${TREE}_$$.XXXXXX") || { echo "ACCEPT RED 无法创建结果目录"; exit 1; }
T0=$SECONDS
SKIP=""; SCOPE="全量"
if [ "${ACCEPT_ALL:-0}" != 1 ]; then
ROOT=$(git -C "$HERE" rev-parse --show-toplevel 2>/dev/null); MB=$(git -C "$HERE" merge-base HEAD main 2>/dev/null)
CH=""; [ -n "$ROOT" ] && [ -n "$MB" ] && CH=$( { git -C "$ROOT" diff --name-only --no-renames "$MB" HEAD; git -C "$ROOT" status --porcelain --no-renames | cut -c4-; } 2>/dev/null | sort -u | grep -v '^$') # --no-renames:改名按「删旧 + 加新」两条路径列,旧路径在别的目录时不会被漏掉 | --no-renames: a rename is listed as two paths, "delete old + add new", so the old path is not missed when it is in another directory
[ -n "${ACCEPT_SCOPE_CH:-}" ] && CH=$(printf '%s\n' "$ACCEPT_SCOPE_CH" | tr ' ' '\n') # 干跑范围判定用:直接给改动路径清单(空格或换行分隔),配 ACCEPT_SCOPE_ONLY=1 只打印 SCOPE 行就退出 | for dry-run scope decisions: give the list of changed paths directly (space or newline separated), and with ACCEPT_SCOPE_ONLY=1 only print the SCOPE line and exit
# dm/ios 下被编进 Mac 宿主(含宿主单测、触屏功能用例)的源文件,改了等于改宿主:清单从两份 Makefile 里现取,不手写
# (dm_touch_controls.c 的改动被判成「只在 dm/ios」跳过了 ⑨,把主干的 skill_main 用例弄红)
# Source files under dm/ios that are compiled into the Mac host (including host unit tests and touch-screen functional cases): changing them equals changing the host; the list is taken live from the two Makefiles, not written by hand
# (a change to dm_touch_controls.c was judged "only in dm/ios" and skipped (9), turning the skill_main case on main red)
HOSTDEP=$(grep -hoE 'ios/Sources/[A-Za-z0-9_]+\.(\[ch\]|[chm])' "$HERE/../host/Makefile" "$HERE/../host/tests/Makefile" 2>/dev/null | sed -E 's/^(.*)\.\[ch\]$/\1.c\n\1.h/' | sed 's#^#dm/#' | sort -u)
CH=$(printf '%s\n' "$CH" | while IFS= read -r f; do [ -n "$f" ] || continue; if printf '%s\n' "$HOSTDEP" | grep -qxF "$f"; then echo "dm/host/(宿主也编) $f"; else echo "$f"; fi; done)
if [ -n "$CH" ]; then
if ! printf '%s\n' "$CH" | grep -qvE '^(dm/ios/|docs/)|\.md$'; then SKIP="1 2 3 4 5 6 7 9 10"; SCOPE="改动只在 dm/ios 与文档"
elif ! printf '%s\n' "$CH" | grep -qvE '^(dm/gfx/|dm/ios/|docs/)|\.md$'; then SKIP="1 2 5 6 7 9"; SCOPE="改动只在 dm/gfx(及 dm/ios、文档)"; fi
fi
fi
echo "SCOPE ${SCOPE}$([ -n "$SKIP" ] && echo ";跳过项序号 $SKIP(ACCEPT_ALL=1 强制全量)")"
[ "${ACCEPT_SCOPE_ONLY:-0}" = 1 ] && exit 0
# 并行子项都调用增量make;先在锁内只构建一次,避免冷树多个链接器争写同一个dmhost/dSYM。
# The parallel sub-items all invoke an incremental make; build once first inside the lock, so that on a cold tree several linkers do not compete to write the same dmhost/dSYM.
if make -s -C "$HERE/../host" > "$L/build.log" 2>&1; then
echo "BUILD OK 宿主预构建完成,后续子项只做增量核对"
else
echo "宿主预构建失败;运行子项未启动,现场保留" > "$L/KEEP"
cat "$L/build.log"
echo "ACCEPT RED 宿主预构建失败 日志 $L"
exit 1
fi
item() { # item <序号> <名> <期望> <日志> <读数行正则> <读数行数> <命令…>:结果写 $L/<序号>.row(首行 rc,次行表格行) | item <number> <name> <expected> <log> <readout line regex> <readout line count> <command...>: the result is written to $L/<number>.row (first line rc, second line the table row)
local k=$1 name=$2 want=$3 log=$4 kl=$5 kn=$6; shift 6; local s=$SECONDS
case " $SKIP " in *" $k "*) printf '0\n| %s | %s | ⏭ 跳过:%s | 0 秒 |\n' "$name" "$want" "$SCOPE" > "$L/$k.row"; echo "⏭ ${name}(跳过:${SCOPE})"; return 0;; esac
"$@" > "$L/$log" 2>&1; local rc=$?
local got=$(grep -E "$kl" "$L/$log" | tail -$kn | tr '\n' ' ') mark
[ $rc = 0 ] && mark="✅" || mark="🔴"
printf '%s\n| %s | %s | %s %s | %s 秒 |\n' "$rc" "$name" "$want" "$mark" "${got:-(无读数行,见 ${log})}" "$((SECONDS - s))" > "$L/$k.row"
echo "$mark ${name}($((SECONDS - s)) 秒)"
}
item 0 "⓪ 启动块清单 bootlist.tsv" "存在、构建号与 main.cuts.tsv 一致、与仓库 dm/data/bootlist_<构建号>.tsv 逐字节相同、sha 自洽、块数 > 0、逐块与资源包一致" bootlist.log '^BOOTLIST' 1 "$HERE/bootchk.sh" "$OUT"
# ①②③ 互相独立,并行(accept ≤ 2 分钟):regress 吃 CPU、host_savecmp 一局宿主、shotgate 4 路宿主
# (1)(2)(3) are independent of each other and run in parallel (accept <= 2 minutes): regress eats CPU, host_savecmp is one host run, shotgate is 4 hosts in parallel
regress_both() { # ① 被测产物全套 + 出包产物(iOS 发给玩家的 touch)结构核对(触屏私有门 4 条登记缺口,accept 只核 keypage 一直没暴露) | (1) structure check of the full set of build output under test + the packaging build output (the touch one iOS ships to players) (4 registration gaps in the touch-screen private gates went unexposed because accept only checked keypage)
local rc=0 touch_out=${DM_TOUCH_OUT:-$(bash "$(dirname "$0")/../tools/product.sh" path touch)}
"$HERE/regress.sh" "$OUT" || rc=1
"$HERE/regress.sh" --struct-only "$touch_out" || rc=1
return $rc
}
item 1 "① 改写等价回归 regress(+ 出包产物 touch 结构核对)" "被测产物三模块 STRUCT/EQUIV OK、GATEFN 全过;touch 三模块 STRUCT OK、GATEFN 全过;两行 REGRESS OK" regress.log '^(STRUCT|EQUIV|REGRESS|GATEFN)' 13 regress_both &
savecmp_gate() { # host_savecmp + 宿主日志红线(只比存档字节、没看日志,缺着色器 20 行【红】连报 5 次绿);$1 = 本项日志名 | host_savecmp + host log a failure line line (it only compared save bytes and did not look at the log, so a missing shader with 20 lines of 【红】(red) was reported green 5 times in a row); $1 = this item's log name
bash "$HERE/../tools/host_savecmp.sh" "$TR" "$OUT"; local rc=$?
local hd=$(sed -n 's/^局目录 //p' "$L/${1:-savecmp.log}" | head -1) r
r=$("$HERE/logred.sh" "$hd/host.log"); local lrc=$?
echo "HOSTLOG 宿主日志红线 $(echo "$r" | cut -f1) 行 $(echo "$r" | cut -f2)($hd/host.log)"
[ $lrc = 0 ] || { [ $lrc = 2 ] && echo "HOSTLOG 找不到宿主日志,判红"; rc=1; }
# 预取命中只报不判:预取是性能优化,命中数取决于最低 QoS 预取线程跑了多久,负载下实测 5270→3244、2148,
# 截止点无论取「到选角」还是整局都和墙钟赛跑;清单对不对是静态性质,归 ⓪ bootchk(逐块核资源包)
# Prefetch hits are only reported, not judged: prefetch is a performance optimization, and the hit count depends on how long the lowest-QoS prefetch thread got to run, measured under load 5270->3244, 2148,
# so whether the cutoff is taken "at character select" or over the whole run it is a race against the wall clock; whether the list is correct is a static property and belongs to (0) bootchk (checks the resource package block by block)
local hit=$(grep -o 'DM_TACT_PREFETCH:命中 [0-9]*' "$hd/host.log" | tail -1 | grep -o '[0-9]*$')
echo "PREFETCH 预取命中 ${hit:-无读数} 块(只报不判)"
return $rc
}
item 2 "② 存档逐字节对拍 host_savecmp $(basename "$TR")" "逐拍 6 格一致、正对照一致、负对照不一致、宿主日志无红线" savecmp.log 'SELFCMP|^SAVECMP|结论|^HOSTLOG|^PREFETCH' 6 savecmp_gate savecmp.log &
gatebc() {
local rc=0 rule_out=${DM_RULE_OUT:-$(bash "$(dirname "$0")/../tools/product.sh" path rules)} self_out=${DM_LOGICSELF_OUT:-$(bash "$(dirname "$0")/../tools/product.sh" path touch)}
if [ ! -f "$HERE/rulegate.sh" ] || [ ! -f "$HERE/logicself.sh" ]; then
echo "RULEGATE TEST FIXTURE 未装载脚本"
echo "LOGICSELF TEST FIXTURE 未装载脚本"
return 0
fi
bash "$HERE/rulegate.sh" 400 "$rule_out" || rc=1
bash "$HERE/logicself.sh" "$self_out" 230 || rc=1
return $rc
}
item 7 "②B/C 逻辑闸门 rulegate + logicself" "RULEGATE 400 逐拍六组一致;LOGICSELF 230 逐拍自身基线一致" logic_gate.log '^(RULEGATE|LOGICSELF)' 8 gatebc &
# ⑤ 确定性回归:拍 400 入口人为睡 300 ms 造补拍积压,冻结拍仍须落在 401、存档正绿负红
# (5) Determinism regression: sleep 300 ms artificially at the entry of tick 400 to build a catch-up tick backlog; the frozen tick must still land on 401, and the save must pass in the positive case and fail in the negative case
lag_gate() { # ⑤:savecmp_gate + 射程(证明不是空跑——宿主日志「下一拍时限 A → B」的增量须 ≥ 200;注入时实测 281、不注入 28) | (5): savecmp_gate + coverage (proves it is not an empty run -- the increment of the host log 「下一拍时限 A → B」(next tick deadline A -> B) must be >= 200; measured 281 with injection, 28 without)
savecmp_gate savecmp_lag.log; local rc=$?
local hd=$(sed -n 's/^局目录 //p' "$L/savecmp_lag.log" | head -1)
local inc=$(grep -o '下一拍时限 [0-9]* → [0-9]*' "$hd/host.log" | tail -1 | awk '{print $4 - $2}')
if [ -n "$inc" ] && [ "$inc" -ge 200 ]; then echo "LAGRANGE 积压已造出:下一拍时限增量 ${inc}(≥ 200)"; else echo "LAGRANGE 空跑:下一拍时限增量 ${inc:-无读数}(须 ≥ 200)"; rc=1; fi
return $rc
}
item 5 "⑤ 补拍积压下冻结拍确定性 DM_TEST_LAG=400 $(basename "$TR")" "冻结拍 401(目标 401)不带【红】、正对照一致、负对照不一致、宿主日志无红线、积压射程增量 ≥ 200" savecmp_lag.log 'SELFCMP|^SAVECMP|结论|^HOSTLOG|^LAGRANGE|^PREFETCH' 7 env DM_TEST_LAG=400 bash -c "$(declare -f savecmp_gate lag_gate); HERE=$HERE TR=$TR OUT=$OUT L=$L lag_gate" &
func_cases() {
local case_dir name total green=0 status elapsed note log detail reported
local cases=() pending=()
while IFS= read -r -d '' case_dir; do
[ -f "$case_dir/script.txt" ] && [ -f "$case_dir/assert.py" ] || continue
# 用例目录里有 pending 文件 = 待接入(如等宿主改动才能进时限):不跑,但必须列出,不静默跳过;首行写原因
# A pending file in a case directory = waiting to be wired in (e.g. waiting for a host change before it can fit the time limit): not run, but must be listed, not silently skipped; the first line gives the reason
if [ -f "$case_dir/pending" ]; then pending+=("$(basename "$case_dir"):$(head -1 "$case_dir/pending")"); continue; fi
cases+=("$(basename "$case_dir")")
done < <(find "$HERE/touchcases" -mindepth 1 -maxdepth 1 -type d -print0 | sort -z)
total=${#cases[@]}
if [ "$total" -eq 0 ]; then
echo 'FUNC 0/0'
return 1
fi
# 令牌池限并发(FUNC_JOBS,缺省 2;写法同 shotgate):8 例同时起时每例的启动加载被拖长 4–5 倍(mini 实测单跑 2.8 s 撤读取画面、
# 8 路并行 11–14 s),时限 20 s 卡的是并行启动而不是用例本身;快进后每例单跑 4–5 s,2 个一批、本项总墙钟约 30 s;mini(12 核)上背景 6 宿主 + 3 个一批仍有 15–22 s,故取 2
# 功能用例跑在 iOS 包同一份界面覆盖层上:起跑前生成一次(幂等,约 3 秒),各例共用;不依赖 ⑧ iOS 构建的先后
# A token pool limits concurrency (FUNC_JOBS, default 2; written the same way as shotgate): with 8 cases started at once, each case's startup loading is stretched 4–5 times (measured on the second Mac: 2.8 s to take down the loading screen when run alone,
# 11–14 s with 8 in parallel), so the 20 s limit was catching the parallel startup rather than the case itself; after fast-forward each case takes 4–5 s alone, and with batches of 2 the total wall clock of this item is about 30 s; on the second Mac (12 cores) with 6 background hosts + batches of 3 it is still 15–22 s, hence 2
# Functional cases run on the same UI overlay as the iOS app: generated once before starting (idempotent, about 3 seconds) and shared by all cases; does not depend on the ordering of (8) iOS build
python3 "$HERE/../ios/tools/gen_romfs_overlay.py" "${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}" "$L/romfs_overlay" > /dev/null 2>"$L/func_overlay.err" || { echo "FUNCFAIL 界面覆盖层生成失败:$(tail -1 "$L/func_overlay.err")"; echo 'FUNC 0/0'; return 1; }
export DM_ROMFS_OVERLAY="$L/romfs_overlay"
local sem="$L/func.sem.$$"; mkfifo "$sem" || return 1; exec 8<>"$sem"; rm -f "$sem"
for _ in $(seq 1 "${FUNC_JOBS:-2}"); do echo >&8; done
for name in "${cases[@]}"; do
read -r -u 8
(
log="$L/func_${name}.log"
local started=$SECONDS rc=0
timeout 120s env DM_TOUCH_RUNROOT="$L/touchchain/$name" bash "$HERE/touchchain.sh" "$name" > "$log" 2>&1 || rc=$?
reported=$(awk '/^TOUCHCHAIN / {print $(NF - 1)}' "$log" | tail -1)
elapsed=${reported:-$((SECONDS - started))}
status=RED
[ "$rc" -eq 0 ] && [ "$elapsed" -le "${FUNC_LIMIT_S:-60}" ] && status=OK # 判对错只看断言;墙钟只作卡死兜底(60 s)。20 s 硬线在多线并行 accept 时反复误红,用例单跑 4–5 s | right or wrong is judged by assertions only; wall clock is only a backstop for hangs (60 s). The hard 20 s line repeatedly failed spuriously when several accept runs ran in parallel; a case run alone takes 4–5 s
printf '%s %s\n' "$status" "$elapsed" > "$L/func_${name}.row"
echo >&8
) &
done
wait; exec 8>&-
for name in "${cases[@]}"; do
read -r status elapsed < "$L/func_${name}.row"
note=''
[ "$elapsed" -gt 20 ] && note='(慢:> 20 s,本机负载高?)'; [ "$elapsed" -gt "${FUNC_LIMIT_S:-60}" ] && note="(超卡死兜底 ${FUNC_LIMIT_S:-60} s)"
printf 'FUNCCASE %s %s %s 秒%s\n' "$name" "$status" "$elapsed" "$note"
if [ "$status" = OK ]; then
green=$((green + 1))
else
log="$L/func_${name}.log"
detail=$(grep -E '局目录:|断言失败:' "$log" | tail -2 | tr '\n' ' ')
[ -n "$detail" ] || detail="日志:$log"
printf 'FUNCFAIL %s %s\n' "$name" "$detail"
fi
done
printf 'FUNC %s/%s\n' "$green" "$total"
[ ${#pending[@]} -eq 0 ] || { printf 'FUNCPENDING 待接入 %s 例:' "${#pending[@]}"; printf '%s;' "${pending[@]}"; echo; }
[ "$green" -eq "$total" ]
}
item 9 "⑨ 功能用例 touchchain" "自动收集 script.txt + assert.py 用例;各例并行;断言通过(墙钟 60 s 只作卡死兜底)" func.log '^(FUNCCASE|FUNC|FUNCFAIL|FUNCPENDING)' 1000 func_cases &
PAGES=()
[ "$MODE" = fast ] && PAGES=(camp_e stash wild charselect skilltree)
PAGE_NAMES=${PAGES[*]:-$(cd "$HERE/shotgate_pages" && ls *.json | sed 's/\.json$//' | tr '\n' ' ')}
item 3 "③ 画面闸门 shotgate ${MODE}(${PAGE_NAMES})" "每页对真值绿(结构 / 非黑 / 网格 / 命名区域 / 应有元素 / 宿主日志无【红】)" shotgate.log 'SHOTGATE_ALL' 1 "$HERE/shotgate.sh" "$OUT" ${PAGES[@]+"${PAGES[@]}"} &
unit_tests() { # ④ 宿主与图形单测(E:SHOT 合入后 gfx 单测链接失败,accept 却绿):任何失败或构建 / 链接错误即红 | (4) host and graphics unit tests (after E:SHOT was merged the gfx unit test failed to link, yet accept was green): any failure or build / link error is a failure
local rc=0
"${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python" "$HERE/ryu/test_selfcmp.py" > "$L/unit_selfcmp.log" 2>&1 && echo "UNIT selfcmp 通过" || { echo "UNIT selfcmp 失败(见 unit_selfcmp.log)"; rc=1; }
"${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python" "$HERE/ryu/test_plan.py" > "$L/unit_plan.log" 2>&1 && echo "UNIT plan 通过" || { echo "UNIT plan 失败(见 unit_plan.log)"; rc=1; }
make -j8 -C "$HERE/../host/tests" run > "$L/unit_host.log" 2>&1 && echo "UNIT host 通过" || { echo "UNIT host 失败:$(grep -m1 -iE 'error|fail|失败|红' "$L/unit_host.log" | cut -c1-140)"; rc=1; }
make -j8 -C "$HERE/../gfx/tests" run > "$L/unit_gfx.log" 2>&1 && echo "UNIT gfx 通过" || { echo "UNIT gfx 失败:$(grep -m1 -iE 'error|fail|失败|红|undefined' "$L/unit_gfx.log" | cut -c1-140)"; rc=1; }
# iOS 触摸层单测(这一套从没接进闸门,回城钮改版后红了一天没人看见)
# iOS touch layer unit tests (this set was never wired into the gate check, and after the town portal button redesign it was red for a day without anyone seeing it)
make -C "$HERE/../ios/tests" test > "$L/unit_ios.log" 2>&1 && echo "UNIT ios 通过" || { echo "UNIT ios 失败:$(grep -m1 -E 'FAIL|Error|error' "$L/unit_ios.log" | cut -c1-140)"; rc=1; }
# accept 自己的接线单测(加 ⑧ 时漏过替身,test_accept 4 例红而 accept 全绿);它用替身起 accept,不跑真宿主,几秒
# accept's own wiring unit test (when (8) was added a stand-in was missed, test_accept had 4 failure cases while accept was all green); it starts accept with stand-ins, does not run the real host, and takes a few seconds
(cd "$HERE" && python3 -m unittest -q test_accept) > "$L/unit_accept.log" 2>&1 && echo "UNIT accept 通过" || { echo "UNIT accept 失败:$(grep -m1 -E '^(FAIL|ERROR):' "$L/unit_accept.log" | cut -c1-140)"; rc=1; }
return $rc
}
item 4 "④ 单测 selfcmp + plan + make -C dm/host/tests run + dm/gfx/tests run + dm/ios/tests test + test_accept" "六套全过、无构建 / 链接错误" unit.log '^UNIT' 6 unit_tests &
ios_build_gate() {
local s=$SECONDS raw="$L/iosbuild-command.log"
DM_NOINSTALL=1 DM_IOS_DD="$HERE/../../.iosdd" bash "$HERE/../ios/run.sh" build > "$raw" 2>&1
local rc=$? elapsed=$((SECONDS - s))
if [ "$rc" = 0 ]; then
echo "IOSBUILD OK 用时 $elapsed 秒"
else
echo "IOSBUILD RED 用时 $elapsed 秒"
grep -m1 -E 'error:' "$raw" || true
fi
return "$rc"
}
item 8 "⑧ iOS 构建(只编不装)" "DM_NOINSTALL=1 工作树派生目录构建成功;首个 error 可见" iosbuild.log '^IOSBUILD (OK|RED)' 2 ios_build_gate &
# ⑩ 局内切运行模式(真机过热切掌机即崩、各闸门都不切模式没抓到):进局后 主机 → 掌机,进程须活着继续出帧
# (10) Switching operation mode in game (a real device overheating and switching to handheld crashed immediately, and no gate check switched modes so it was not caught): after joining a run, docked -> handheld, and the process must stay alive and keep producing frames
item 10 "⑩ 局内切运行模式 opmode" "切换前已进局;取走通知 30/31;活到 timeout 无 CRASH;切换后 ≥ 300 帧;宿主日志无红线" opmode.log '^OPMODE (OK|RED)' 1 bash "$HERE/opmode.sh" "$OUT" &
# 事务四局串行本身占约 90 秒,列入全档;与其余项目独立,原来的六项判据保持不变。
# The four transaction runs in series take about 90 seconds by themselves and are put in the full mode; they are independent of the other items, and the original six criteria stay unchanged.
[ "$MODE" = full ] && item 6 "⑥ 存档事务 save_txn_regress" "4/4 注入命中;已提交文件同期望版;校验和自洽;残缺工作目录 / 拒绝日志负对照成立" save_txn.log '^✓|^✗|^结论|^SAVE_TXN' 6 bash "$HERE/../tools/save_txn_regress.sh" "$OUT" &
wait
allrc=0; rows=()
ITEMS=(0 1 2 3 4 5 7 8 9 10); [ "$MODE" = full ] && ITEMS+=(6)
for k in "${ITEMS[@]}"; do { read -r rc; read -r row; } < "$L/$k.row"; [ "$rc" = 0 ] || allrc=1; rows+=("$row"); done
[ "$allrc" = 0 ] || echo "ACCEPT $MODE 红;本目录保留,不删不覆盖" > "$L/KEEP"
echo; echo "| 项 | 期望 | 真结果 | 用时 |"; echo "|---|---|---|---|"; printf '%s\n' "${rows[@]}"
echo; echo "ACCEPT $([ $allrc = 0 ] && echo OK || echo RED) 档位 $MODE 产物 $(basename "$OUT") 总用时 $((SECONDS - T0)) 秒 日志 $L"
exit $allrc
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# 产物目录启动块清单核对(r11 原样跑时缺清单不开预取 = 出版漏项):bootlist.tsv 必须存在、头行 BUILD_ID 与 main.cuts.tsv 一致、bootlist.sha256 与内容一致、块数 > 0
# 清单入库为版本化数据,产物 bootlist.tsv 须与仓库 dm/data/bootlist_<main 构建号>.tsv 逐字节相同(记录有竞态、不能重录比对)
# 用法:bootchk.sh <产物目录> 末行 BOOTLIST OK|RED …;退出码 0/1
# Boot block list check of the build output directory (when r11 was run as is, the missing list meant no prefetch = an omission in the release): bootlist.tsv must exist, the BUILD_ID in its header line must match main.cuts.tsv, bootlist.sha256 must match the content, block count > 0
# The list is checked into the repository as versioned data, and the build output bootlist.tsv must be byte-for-byte identical to the repository's dm/data/bootlist_<main build ID>.tsv (recording is racy, so it cannot be re-recorded for comparison)
# Usage: bootchk.sh <build output directory> last line BOOTLIST OK|RED ...; exit code 0/1
D=${1%/}; B=$D/bootlist.tsv
red() { echo "BOOTLIST RED $*"; exit 1; }
[ -s "$B" ] || red "缺 $B"
bid=$(sed -n '1s/^# BUILD_ID[[:space:]]*//p' "$B"); cid=$(grep -m1 '^# BUILD_ID' "$D/main.cuts.tsv" | awk '{print $NF}')
[ -n "$bid" ] && [ "$bid" = "$cid" ] || red "构建号不符:清单 ${bid:-无} / main.cuts.tsv ${cid:-无}"
RB=$(cd "$(dirname "$0")/../data" 2>/dev/null && pwd)/bootlist_$bid.tsv
[ -f "$RB" ] || red "仓库缺清单 dm/data/bootlist_$bid.tsv"
cmp -s "$B" "$RB" || red "与仓库 dm/data/bootlist_${bid:0:12}….tsv 不同(产物 $(grep -vc '^#' "$B") 块 / 仓库 $(grep -vc '^#' "$RB") 块)"
[ -f "$D/bootlist.sha256" ] && (cd "$D" && shasum -a 256 -c bootlist.sha256 >/dev/null 2>&1) || red "bootlist.sha256 缺或不符"
n=$(grep -vc '^#' "$B"); [ "$n" -gt 0 ] || red "清单 0 块"
# 清单对不对是静态性质——逐块核数据文件存在、不越界、不重复、开头 16 字节与资源包一致(运行时预取命中只报不判)
# Whether the list is correct is a static property -- check block by block that the data file exists, is not out of bounds, is not duplicated, and that the first 16 bytes match the resource package (runtime prefetch hits are only reported, not judged)
st=$(python3 "$(dirname "$0")/bootlist_static.py" "$RB" ${DM_ROMFS:+"$DM_ROMFS/data"}) || red "$(echo "$st" | tail -1);$(echo "$st" | head -1)"
echo "BOOTLIST OK $n 块 构建号 ${bid:0:12}… 与仓库清单逐字节相同,逐块与资源包一致"
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""启动块清单静态核对(预取是性能优化,闸门只核清单本身对不对,运行时命中数只报不判)。
用法:bootlist_static.py <清单.tsv> [RomFS/data 目录]
逐行核:数据文件存在;偏移 + 压缩长不越出文件;(文件, 偏移) 不重复;文件该偏移处的开头 16 字节与清单记录一致
(这一条证明清单块真实存在于当前资源包,与运行时调度无关)。末行 BOOTSTATIC OK|RED …;退出码 0/1。
Static check of the boot block list (prefetch is a performance optimization; the gate check only checks whether the list itself is correct, and runtime hit counts are only reported, not judged).
Usage: bootlist_static.py <list.tsv> [RomFS/data directory]
Checked line by line: the data file exists; offset + compressed length does not go past the file; (file, offset) is not duplicated; the first 16 bytes at that offset in the file match the list record
(this one proves the listed block really exists in the current resource package, independent of runtime scheduling). Last line BOOTSTATIC OK|RED ...; exit code 0/1.
"""
import os, sys
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
lst = sys.argv[1]
rom = sys.argv[2] if len(sys.argv) > 2 else os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS/data')
bad, seen, n, fhs = [], set(), 0, {}
holes = {} # 剔零档案(<档案>.holes 区段表,宿主 hle_fs.c 同口径):文件 → (原始大小, [(零段起, 零段止)…]) | zero-stripped archives (<archive>.holes extent table, same rule as the host's hle_fs.c): file -> (original size, [(zero run start, zero run end)...])
def hole_info(p):
if p not in holes:
hp = p + '.holes'; holes[p] = None
if os.path.isfile(hp):
ls = open(hp).read().split('\n'); holes[p] = (int(ls[0].split()[1]), [(int(x.split()[0]), int(x.split()[0]) + int(x.split()[1])) for x in ls[1:] if x.strip()])
return holes[p]
def phys(p, off, ln): # 原始偏移 → 剔零文件里的偏移;整段须落在保留段里,否则 None | original offset -> offset in the zero-stripped file; the whole range must fall inside a kept run, otherwise None
h = hole_info(p)
if h is None: return off
cut = 0
for a, b in h[1]:
if b <= off: cut += b - a
elif a < off + ln: return None
return off - cut
for i, line in enumerate(open(lst), 1):
if line.startswith('#') or not line.strip():
continue
n += 1
f, off, clen, _dlen, head = line.split('\t')[:5]
off, clen = int(off), int(clen)
p = os.path.join(rom, f)
if (f, off) in seen:
bad.append(f'第 {i} 行 重复 {f}@{off}'); continue
seen.add((f, off))
if f not in fhs:
fhs[f] = open(p, 'rb') if os.path.isfile(p) else None
fh = fhs[f]
if fh is None:
bad.append(f'第 {i} 行 数据文件不存在 {p}'); continue
h = hole_info(p)
if off + clen > (h[0] if h else os.fstat(fh.fileno()).st_size):
bad.append(f'第 {i} 行 越界 {f}@{off}+{clen}'); continue
po = phys(p, off, clen)
if po is None:
bad.append(f'第 {i} 行 落在剔掉的零段里 {f}@{off}+{clen}'); continue
fh.seek(po)
if fh.read(len(head) // 2).hex() != head:
bad.append(f'第 {i} 行 开头字节不符 {f}@{off}')
if n == 0:
bad.append('清单 0 块')
for b in bad[:5]:
print(b)
print(f'BOOTSTATIC {"OK" if not bad else "RED"} {n} 块,不符 {len(bad)} 处({os.path.basename(lst)},资源包 {rom})')
sys.exit(1 if bad else 0)
+36
View File
@@ -0,0 +1,36 @@
# 客户端命令包序列对比(格式见 dm/verify/command_packet_format.md)。
# 用法:c2scmp.py <A c2s.jsonl> <B c2s.jsonl> [--ids]
# --ids:只比包号序列(首字节;忽略坐标等数值字段,连续相同包号折叠)——摇杆类连续动作的客户端层判据
# 报两件事:① 内容与顺序(忽略 tick,客户端层判据);② 落拍(同序号的包 tick 是否相同,服务端回放能否直接用实时按键)。
# 退出码:0 = 内容一致且落拍一致;1 = 内容一致但落拍漂移;2 = 内容不一致;3 = 射程不足(任一侧 0 条)。
# Client command packet sequence comparison (format in dm/verify/command_packet_format.md).
# Usage: c2scmp.py <A c2s.jsonl> <B c2s.jsonl> [--ids]
# --ids: compare only the packet id sequence (first byte; ignores numeric fields such as coordinates, and consecutive identical packet ids are folded) -- the client-layer criterion for continuous actions such as the stick
# Reports two things: (1) content and order (ignoring tick, the client-layer criterion); (2) tick alignment (whether packets with the same sequence number have the same tick, i.e. whether server-side replay can use the real-time key presses directly).
# Exit codes: 0 = content identical and tick alignment identical; 1 = content identical but tick alignment drifts; 2 = content differs; 3 = insufficient coverage (0 packets on either side).
import sys, json
def load(p): return [json.loads(l) for l in open(p) if l.strip()]
a, b = load(sys.argv[1]), load(sys.argv[2])
if '--ids' in sys.argv:
fa = [x['pkt'][:2] for i, x in enumerate(a) if i == 0 or x['pkt'][:2] != a[i - 1]['pkt'][:2]]
fb = [x['pkt'][:2] for i, x in enumerate(b) if i == 0 or x['pkt'][:2] != b[i - 1]['pkt'][:2]]
print(f'包号序列(折叠):A {len(fa)},B {len(fb)}')
n = next((i for i, (x, y) in enumerate(zip(fa, fb)) if x != y), None)
if n is None and len(fa) != len(fb): n = min(len(fa), len(fb))
if n is None: print('C2SCMP 包号序列一致'); sys.exit(0)
print(f'C2SCMP 包号序列不一致:第 {n} 个起 A {fa[max(0, n - 2):n + 3]} B {fb[max(0, n - 2):n + 3]}'); sys.exit(2)
print(f'射程:A {len(a)} 条,B {len(b)} 条;包号种类 {len({x["pkt"][:2] for x in a + b})}')
if not a or not b: print('C2SCMP 射程不足'); sys.exit(3)
ka = [(x['unit'], x['len'], x['pkt']) for x in a]; kb = [(x['unit'], x['len'], x['pkt']) for x in b]
n = next((i for i, (x, y) in enumerate(zip(ka, kb)) if x != y), None)
if n is None and len(ka) != len(kb): n = min(len(ka), len(kb))
if n is not None:
print(f'C2SCMP 内容不一致:第 {n} 条起')
for lab, s in (('A', a), ('B', b)):
for i in range(max(0, n - 2), min(len(s), n + 3)): print(f' {lab} {">>" if i == n else " "} {i} 拍 {s[i]["tick"]} {s[i]["pkt"][:40]}')
sys.exit(2)
drift = [(i, x['tick'], y['tick']) for i, (x, y) in enumerate(zip(a, b)) if x['tick'] != y['tick']]
if not drift: print('C2SCMP 一致(内容、顺序、落拍全同)'); sys.exit(0)
d = sorted({y - x for _, x, y in drift})
print(f'C2SCMP 内容一致、落拍漂移:{len(drift)}/{len(a)} 条拍号不同,差值种类 {d[:10]};首个第 {drift[0][0]} 条(A 拍 {drift[0][1]} / B 拍 {drift[0][2]})')
sys.exit(1)
+63
View File
@@ -0,0 +1,63 @@
# Client Command Packet Sequence Format
中文:[command_packet_format.zh-CN.md](command_packet_format.zh-CN.md)
Internally the game is split into two halves, client and server: the client turns the player's actions into "command packets" and hands them to the server to process. Recording the command packets of a run in order into a file has two uses: replaying them as-is on the **host** (`dmhost` from `dm/host`), so that the server plays out the same run as the **ground truth** (reference data obtained by running the original game in a patched Ryujinx emulator); or comparing whether the two sides emit the same command packets under the same key presses. Ground-truth recording and host replay share this format.
## Capture point
- The client command dispatch function `main + 0x6e5b40(G, unit, packet, length)`. At entry:
`x0` = G (the game object, the same base address as in [tick_state_format.md](tick_state_format.md)), `x1` = the unit sending the packet (may be 0), `x2` → the packet bytes (packet number = first byte, must be < 0x67), `w3` = length.
- The handler table `main + 0x20a4190` (0x67 entries; an empty entry means an illegal packet number).
- **System-class messages** take another path: `main + 0x6310b0(buf, packet length)` (jump table `0x1daf73c`), buf = u32 client number + packet. The packet receive pump `0x5d3960` first drains the system-class queue each tick, then processes command packets.
| Packet no. | Length | Meaning | Replay handling |
|---|---|---|---|
| 0x67 | | Join | Let through as usual at game entry (the host's own is used) |
| 0x6c | | Character data chunk | Injected from the file |
| 0x6d | 13 | Heartbeat: compares +0x6c4 and +0x6c0 of the client structure, and if they differ replies with a sync message and updates | Injected from the file |
| 0x6f | 5 | Progress: the progress value reported by the client is written to +0x6c0 of the client structure (e.g. "new area finished loading" after a teleport) | Injected from the file |
| 0x6a / 0x6b / 0x6e | | Discarded by default | — |
## One line of JSON per packet (in call order)
```
{"tick":57,"unit":1,"len":5,"pkt":"0300120034"}
```
| Field | Meaning |
|---|---|
| tick | `u32 [G+0x170]` at call time (the server's current tick number) |
| unit | `u32 [x1+0x8]` (unit id; null when x1 = 0) |
| len | `w3` |
| pkt | Lowercase hex of the first min(len, 512) bytes of the packet |
| q | Present only for system-class messages, value `"sys"`; in that case unit is always null, tick is the current tick number (`[G+0x170]` at the most recent tick entry), len = packet length, and pkt **does not include** the leading 4-byte client number |
Example of a system-class entry: `{"tick":201,"q":"sys","unit":null,"len":5,"pkt":"6f…"}`.
The host side records with `DM_C2S_LOG=<path>`, in the same format field by field.
## Two layers of criteria
1. **Server layer**: the host takes no controller input; at the tick whose number = tick, in file order, it hands each packet as-is to `0x6e5b40` (`DM_C2S_REPLAY=<file>`, which also turns off commands the client would issue on its own; for testing only), and the 6-slot state is required to match the ground truth tick by tick.
- **System-class messages must be recorded from the ground truth and injected by the host tick by tick.** The tick number and value with which `0x6f` arrives determine at which tick the server inserts a sync message (in several hundred places the server compares +0x6c4 / +0x6c0 before sending a message and resends as needed), which depends on how fast the client is and is inherently different on the two sides, so it is timing-dependent input.
- During replay, the host's own system-class messages are all discarded from the file's first tick on (the `0x67` join before game entry is let through as usual), and instead the original bytes recorded from the ground truth are injected at their original tick numbers; within one tick, system-class messages are injected first and command packets dispatched afterwards, matching the order of the packet receive pump.
- After the file's last tick, the messages the host client issues on its own are let through again.
2. **Client layer**: under the same key script, the command packet sequences the two sides produce are compared **by content and order only** (tick is ignored), and in addition the UI message streams must match ([ui_message_stream.md](ui_message_stream.md)).
Comparison tool: `dm/verify/c2scmp.py <A c2s.jsonl> <B c2s.jsonl> [--ids]`. It reports two things: whether content and order match (the client-layer criterion), and whether packets with the same index land on the same tick number. `--ids` compares only the packet number sequence and folds consecutive identical packet numbers, for continuous actions such as the stick. Exit codes: 0 = content and landing ticks both match, 1 = content matches but landing ticks differ, 2 = content does not match, 3 = either side has 0 entries.
## Recording on the ground-truth side
Recording on the ground-truth side is done by the emulator driver scripts. These scripts are not shipped with the repository, so the checks that depend on ground truth cannot be run with this repository alone. Recording one run puts `c2s.jsonl` (this format) and `ticks.jsonl` (the tick state format) in the run directory. A run can be driven in two ways:
- **Action table**: each line is "tick number after game entry `<TAB>` input command".
- **Plan** (mutually exclusive with the action table): advances by game data. When walking toward an object or monster, the stick is pushed in a closed loop using the coordinates of the player and the target; every key press is confirmed by a UI message, a command packet, the missile count or a scene change.
- In the plan used for six-slot coverage at the server layer, the skill-select packet `0x3c` has its skill number rewritten in place on the ground-truth side, and the recorded `c2s.jsonl` contains the modified bytes — such a file is used only for server-layer replay, and the client-layer criterion cannot use a plan with such a rewrite.
## Two points to note when recording through GDB
The ground-truth side records by setting breakpoints at the two function entries above through the emulator's GDB interface. Both rules are implemented in `oracle/swgdb.py` (`wait_stop` switches threads automatically, `_stash` deduplicates, `step_over` waits for this thread to get past the breakpoint):
- Each time the emulator receives a breakpoint, it sets "which thread register reads refer to" to the thread that most recently hit a breakpoint. Before handling a stop packet that arrived earlier, you must first switch back to that packet's thread; otherwise you read another thread's PC and let this hit pass as an unrelated stop, causing a missed tick.
- A thread that is stopped at a breakpoint and not yet handled will stop again at the same breakpoint on every continue-all. Stashed stop packets must be deduplicated by thread, otherwise the same command packet is recorded twice.
+63
View File
@@ -0,0 +1,63 @@
# 客户端命令包序列格式
English: [command_packet_format.md](command_packet_format.md)
游戏内部分客户端与服务端两半:玩家的操作由客户端变成「命令包」交给服务端处理。把一局里的命令包按先后录成文件,有两个用处:在**宿主**(`dm/host` 的 `dmhost`)上原样回放,让服务端走出与**真值**(用打了补丁的 Ryujinx 模拟器跑原版游戏得到的参照数据)相同的一局;或者比较两边在同样按键下发出的命令包是否相同。真值录制与宿主回放共用本格式。
## 采集点
- 客户端命令分派函数 `main + 0x6e5b40(G, 单位, 包, 长度)`。入口处:
`x0` = G(游戏对象,与 [tick_state_format.zh-CN.md](tick_state_format.zh-CN.md) 同一基址),`x1` = 发包的单位(可为 0),`x2` → 包字节(包号 = 首字节,须 < 0x67),`w3` = 长度。
- 处理函数表 `main + 0x20a4190`(0x67 项,空项即非法包号)。
- **系统类消息**走另一条路:`main + 0x6310b0(buf, 包长)`(跳转表 `0x1daf73c`),buf = u32 客户端号 + 包。收包泵 `0x5d3960` 每拍先抽干系统类队列,再处理命令包。
| 包号 | 长 | 含义 | 回放处理 |
|---|---|---|---|
| 0x67 | | 加入 | 进局时照常放行(用宿主自己的) |
| 0x6c | | 角色数据分块 | 按文件注入 |
| 0x6d | 13 | 心跳:比较客户端结构 +0x6c4 与 +0x6c0,不同就回同步消息并更新 | 按文件注入 |
| 0x6f | 5 | 进度:客户端上报的进度值写进客户端结构 +0x6c0(如传送后「新区域加载完成」) | 按文件注入 |
| 0x6a / 0x6b / 0x6e | | 默认丢弃 | — |
## 每条一行 JSON(按调用先后)
```
{"tick":57,"unit":1,"len":5,"pkt":"0300120034"}
```
| 字段 | 含义 |
|---|---|
| tick | 调用时 `u32 [G+0x170]`(服务端当前拍号) |
| unit | `u32 [x1+0x8]`(单位 id;x1 = 0 时为 null) |
| len | `w3` |
| pkt | 包字节前 min(len, 512) 字节的小写十六进制 |
| q | 仅系统类消息有,值 `"sys"`;此时 unit 恒 null,tick 取当前拍号(最近一次拍入口的 `[G+0x170]`),len = 包长,pkt **不含**开头 4 字节客户端号 |
系统类条目例:`{"tick":201,"q":"sys","unit":null,"len":5,"pkt":"6f…"}`。
宿主侧用 `DM_C2S_LOG=<路径>` 录,逐字段同格式。
## 两层判据
1. **服务端层**:宿主不吃手柄,在拍号 = tick 的那一拍、按文件顺序把每条包原样交给 `0x6e5b40`(`DM_C2S_REPLAY=<文件>`,同时关闭客户端自发的命令;只用于测试),要求逐拍 6 格状态与真值一致。
- **系统类消息必须由真值录、宿主按拍注入**。`0x6f` 到达的拍号与值决定服务端在哪一拍插入同步消息(服务端几百处发消息前都比较 +0x6c4 / +0x6c0 并补发),这取决于客户端快慢,两边天然不同,属于与时序相关的输入。
- 回放时宿主自己的系统类消息从文件首拍起一律丢弃(进局前的 `0x67` 加入照常放行),改为在原拍号注入真值录下的原字节;同一拍内先注入系统类、再分派命令包,与收包泵的顺序一致。
- 过了文件末拍,宿主客户端自发的消息重新放行。
2. **客户端层**:同一份按键脚本下,两边产生的命令包序列**只比内容与顺序**(忽略 tick),外加 UI 消息流一致([ui_message_stream.zh-CN.md](ui_message_stream.zh-CN.md))。
对比工具:`dm/verify/c2scmp.py <A c2s.jsonl> <B c2s.jsonl> [--ids]`。它报两件事:内容与顺序是否一致(客户端层判据)、同序号的包落在的拍号是否相同。`--ids` 只比包号序列并折叠连续相同的包号,给摇杆这类连续动作用。退出码:0 = 内容与落拍都一致,1 = 内容一致但落拍不同,2 = 内容不一致,3 = 任一侧 0 条。
## 真值侧录制
真值侧的录制由模拟器驱动脚本完成。这些脚本不随仓库提供,所以依赖真值的检查在仓库外跑不了。录一局,局目录下得到 `c2s.jsonl`(本格式)与 `ticks.jsonl`(拍状态格式)。驱动一局有两种写法:
- **动作表**:每行「进局后第几拍 `<TAB>` 输入指令」。
- **计划**(与动作表二选一):按游戏数据推进。走向物件或怪时,用玩家与目标的坐标闭环推摇杆;每次按键都以 UI 消息、命令包、飞弹数或换场景来确认。
- 服务端层六格覆盖用的那份计划里,选技能的包 `0x3c` 在真值侧就地改写了技能号,录下的 `c2s.jsonl` 是改后的字节——这样的文件只用于服务端层回放,客户端层判据不能用带这种改写的计划。
## 经 GDB 录制时要注意的两点
真值侧靠模拟器的 GDB 接口在上面两个函数入口下断点来录。两条规矩都实现在 `oracle/swgdb.py` 里(`wait_stop` 自动切线程、`_stash` 去重、`step_over` 等本线程走过断点):
- 模拟器每收到一次断点,就把「寄存器读的是哪个线程」设成最新撞断点的那个线程。处理先到的停止包之前必须先切回该包的线程,否则读到别的线程的 PC,会把这次命中当成无关的停止放过,造成漏拍。
- 停在断点上、尚未处理的线程,每次全体继续都会在同一断点再停一次。暂存的停止包要按线程去重,否则同一个命令包会记两次。
+11
View File
@@ -0,0 +1,11 @@
# 动画遮罩:同一冻结拍连截的两张图(服务端停在同一拍、客户端动画照走)逐像素做差,差异像素膨胀一圈 = 「在动的区域」,闸门比对时遮掉
# 用法:dynmask.py <a.png> <b.png> <输出遮罩.png> [阈值=8] [膨胀像素=3] 遮罩白 = 在动;打印动区占比
# Animation mask: diff two screenshots taken back to back at the same frozen tick (server stopped on the same tick, client animation still running) pixel by pixel; differing pixels dilated by one ring = the "moving region", masked out during gate-check comparison
# Usage: dynmask.py <a.png> <b.png> <output mask.png> [threshold=8] [dilation pixels=3] white in mask = moving; prints the moving-region share
import sys
import numpy as np
from PIL import Image, ImageFilter
a, b, out = sys.argv[1:4]; th = int(sys.argv[4]) if len(sys.argv) > 4 else 8; dil = int(sys.argv[5]) if len(sys.argv) > 5 else 3
A = np.asarray(Image.open(a).convert('RGB'), dtype=int); B = np.asarray(Image.open(b).convert('RGB').resize((A.shape[1], A.shape[0])), dtype=int)
m = Image.fromarray(((np.abs(A - B).sum(2) > th) * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(2 * dil + 1))
m.save(out); print(f'DYNMASK 动区占比 {np.asarray(m).mean() / 255:.3f} → {out}')
+257
View File
@@ -0,0 +1,257 @@
# 逐处等价验证:原指令(原映像,x18 是真寄存器)vs 补丁块(改写映像,x18 在 TSD 槽)。
# 每处随机状态多组;比较 x0-x30(x18 对比槽值)、sp、nzcv、v0-v31、全部内存写入、结束 PC、访存异常。
# 用法:equiv.py <改写产物目录> <模块> <NSO> [--seed 1] [--jobs N] [--min-eff 2] [--max-extra 16] [--mutate 300] [--tsv 文件]
# 射程:两边都访存异常的试验只比异常地址,不算「有效」;每处至少 min-eff 次有效试验,不够就补抽(≤max-extra 次),仍不够的列名。
# 变异自检:抽 mutate 个普通改写块,一半把替换后的那条指令改成 nop、一半把跳板出口 b 的目标 +4,都必须被判出分歧(判据能区分的负对照)。
# 宿主门(svc / cntpct / cntvct)语义由宿主定,这里不跑,由 structck.py 做结构核对;已登记剪口(cuts.tsv)是有意的语义改动,同样只由 structck 核字节。
# Per-site equivalence verification: original instruction (original image, x18 is a real register) vs patch block (rewritten image, x18 lives in a TSD slot).
# Several random states per site; compares x0-x30 (x18 compared against the slot value), sp, nzcv, v0-v31, all memory writes, final PC, memory access faults.
# Usage: equiv.py <rewrite build output dir> <module> <NSO> [--seed 1] [--jobs N] [--min-eff 2] [--max-extra 16] [--mutate 300] [--tsv file]
# Coverage: a trial where both sides take a memory access fault only compares the fault address and does not count as "effective"; each site needs at least min-eff effective trials, extra draws are made if short (≤max-extra), and sites still short are listed by name.
# Mutation self-check: draw mutate ordinary rewrite blocks; in half the replaced instruction is changed to nop, in half the target of the trampoline exit b gets +4; all must be judged divergent (a negative control showing the criterion can discriminate).
# Host gate (svc / cntpct / cntvct) semantics are defined by the host and are not run here, structck.py does the structural check; registered cuts (cuts.tsv) are intentional semantic changes and likewise only have their bytes checked by structck.
import sys, os, struct, random, argparse, multiprocessing as mp
from unicorn import *
from unicorn.arm64_const import *
from capstone import *
sys.path.insert(0, os.path.dirname(__file__))
import nsoimg
ap = argparse.ArgumentParser()
ap.add_argument('dir'); ap.add_argument('mod'); ap.add_argument('nso')
ap.add_argument('--seed', type=int, default=1); ap.add_argument('--jobs', type=int, default=os.cpu_count())
ap.add_argument('--min-eff', type=int, default=2); ap.add_argument('--max-extra', type=int, default=16)
ap.add_argument('--mutate', type=int, default=300); ap.add_argument('--tsv')
A = ap.parse_args()
IB = 0x100000000
ARENA = 0x0; ARENA_SZ = 0x1000000 # 低 16 MB 可读写随机区 | Low 16 MB readable/writable random area
TSD = 0x2000000
SP0 = 0x800000
DIR, MOD = A.dir, A.mod
hdr = nsoimg.header(DIR, MOD) # 表头:段边界与写死进指令的线程槽号 | Header: segment boundaries and the thread slot numbers hard-coded into instructions
PATCH_OFF = hdr['PATCH_OFF']
KEY_IDX = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')}
KEY_SLOT = {k: 300 + i for i, k in enumerate(sorted(KEY_IDX, key=KEY_IDX.get))}
SLOT18, SLOTTLS, SLOTTLR = (KEY_SLOT[k] for k in ('K18', 'KTLS', 'KTLR'))
KEY_PAGE_OFF = hdr['KEY_PAGE_OFF']
pat = bytearray(open(f'{DIR}/{MOD}.patched.bin', 'rb').read())
orig = nsoimg.load(A.nso)
ncut = sum(1 for l in open(f'{DIR}/{MOD}.cuts.tsv') if not l.startswith('#'))
nobs = sum(1 for l in open(f'{DIR}/{MOD}.obs.tsv') if not l.startswith('#')) if os.path.exists(f'{DIR}/{MOD}.obs.tsv') else 0
def deexcl(b):
# 仅测试用:全部独占读写(各位宽、单 / 成对)→ 普通 ldr/str/ldp/stp;store 后紧跟的状态 cbz/cbnz → nop。两份映像同样处理。
# Test only: all exclusive loads/stores (every width, single / pair) → plain ldr/str/ldp/stp; the status cbz/cbnz right after a store → nop. Both images are processed the same way.
LD = {0: 0x39400000, 1: 0x79400000, 2: 0xB9400000, 3: 0xF9400000}
ST = {0: 0x39000000, 1: 0x79000000, 2: 0xB9000000, 3: 0xF9000000}
b = bytearray(b); n = 0
for o in range(0, len(b) - 4, 4):
w = struct.unpack_from('<I', b, o)[0]
if w & 0x3F800000 != 0x08000000: continue
size, L, pair = w >> 30, (w >> 22) & 1, (w >> 21) & 1
rs, rt2, rn, rt = (w >> 16) & 31, (w >> 10) & 31, (w >> 5) & 31, w & 31
if pair:
if size < 2: continue
nw = ((0xA9400000 if L else 0xA9000000) if size == 3 else (0x29400000 if L else 0x29000000)) | (rt2 << 10) | (rn << 5) | rt
else:
nw = (LD if L else ST)[size] | (rn << 5) | rt
struct.pack_into('<I', b, o, nw); n += 1
if not L:
nx = struct.unpack_from('<I', b, o + 4)[0]
if nx & 0x7E000000 == 0x34000000 and nx & 31 == rs: struct.pack_into('<I', b, o + 4, 0xD503201F)
return bytes(b), n
orig, _ = deexcl(orig); pat, _ = deexcl(pat)
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
md.detail = True
sites = []; winend = {}; brinfo = {}; ngate = 0
for l in open(f'{DIR}/{MOD}.sites.tsv'):
f = l.split(); a = int(f[0], 16)
if f[1] == 'W': winend[a] = int(f[2], 16); sites.append(a)
elif f[1] == 'J': brinfo[a] = (int(f[2], 16), int(f[3]))
elif f[1] in ('svc', 'cntpct', 'cntvct'): ngate += 1 # 宿主门:语义由宿主定,只做结构核对 | Host gate: semantics are defined by the host, only a structural check is done
else: sites.append(a)
def btarget(b, o):
w = struct.unpack_from('<I', b, o)[0]; imm = w & 0x3FFFFFF
if imm & 0x2000000: imm -= 0x4000000
return o + 4 * imm
def plain_block(a):
"""普通改写块(stp; 键页间接读槽; 替换指令; 键页间接写槽; ...)→ 替换指令偏移。 | Ordinary rewrite block (stp; indirect slot read via key page; replaced instruction; indirect slot write via key page; ...) → offset of the replaced instruction."""
s = btarget(pat, a); w0 = struct.unpack_from('<I', pat, s)[0]
if w0 & 0xFFC003E0 != 0xA90003E0: return None # stp xS, xT, [sp, #off]
ins = list(md.disasm(bytes(pat[s:s + 36]), s))
if len(ins) < 8 or ins[1].mnemonic != 'mrs' or 'tpidrro_el0' not in ins[1].op_str:
return None
if ins[2].mnemonic != 'adrp' or ins[2].operands[1].imm != KEY_PAGE_OFF: return None
if ins[3].mnemonic != 'ldr' or ins[3].operands[1].mem.base != ins[2].operands[0].reg: return None
T = ins[1].operands[0].reg
if ins[4].mnemonic != 'add' or ins[4].operands[0].reg != T or ins[4].operands[1].reg != T: return None
if ins[5].mnemonic != 'ldr' or ins[5].operands[1].mem.base != T: return None # ldr xS,[xT]:读槽 | ldr xS,[xT]: read the slot
if ins[7].mnemonic != 'str' or ins[7].operands[1].mem.base != T: return None # str xS,[xT]:写回槽——只有普通块有,条件块没有(与旧版口径相同) | str xS,[xT]: write back to the slot - only ordinary blocks have it, conditional blocks do not (same convention as the old version)
return ins[6].address
mut_sites = []
if A.mutate:
cand = [a for a in sites if a not in winend and a not in brinfo and plain_block(a)]
mut_sites = sorted(random.Random(A.seed).sample(cand, min(A.mutate, len(cand))))
pat_mut = bytearray(pat)
def exit_b(a): # 改写块回 text 的那条 b(块内第一条目标落回 text 的无条件 b) | The b by which a rewrite block returns to text (the first unconditional b in the block whose target lands back in text)
w = struct.unpack_from('<I', pat, a)[0]; o = a + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000)
for k in range(o, o + 4 * 24, 4):
w = struct.unpack_from('<I', pat, k)[0]
if w & 0xFC000000 == 0x14000000 and k + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000) < PATCH_OFF: return k, w
return None
# 两类变异各一半:偶数位 = 替换后的那条指令改 nop;奇数位 = 跳板出口 b 的目标 +4(参数门跳板回跳越界那一类:越过一条原指令)
# Two kinds of mutation, half each: even index = the replaced instruction is changed to nop; odd index = target of the trampoline exit b +4 (the class where a parameter-gate trampoline jumps back out of bounds: skips one original instruction)
mut_kind = {}
for i, a in enumerate(mut_sites):
eb = exit_b(a) if i % 2 else None
if eb: k, w = eb; struct.pack_into('<I', pat_mut, k, (w & 0xFC000000) | ((w + 1) & 0x3FFFFFF)); mut_kind[a] = 'exit+4'
else: struct.pack_into('<I', pat_mut, plain_block(a), 0xD503201F); mut_kind[a] = 'nop'
pat_mut = bytes(pat_mut)
GP = [getattr(sys.modules['unicorn.arm64_const'], f'UC_ARM64_REG_X{i}') for i in range(29)] + [UC_ARM64_REG_X29, UC_ARM64_REG_X30]
VR = [getattr(sys.modules['unicorn.arm64_const'], f'UC_ARM64_REG_Q{i}') for i in range(32)]
def mk(image, arena0):
u = Uc(UC_ARCH_ARM64, UC_MODE_ARM)
sz = (len(image) + 0xFFFF) & ~0xFFFF
u.mem_map(IB, sz, UC_PROT_ALL); u.mem_write(IB, bytes(image))
u.mem_map(ARENA, ARENA_SZ); u.mem_write(ARENA, arena0)
u.mem_map(TSD, 0x10000)
u.reg_write(UC_ARM64_REG_TPIDRRO_EL0, TSD)
st = {'w': [], 'fault': None, 'arena': arena0}
def wr(uc, acc, addr, size, val, d): st['w'].append((addr, size, val & ((1 << (8 * size)) - 1)))
def bad(uc, acc, addr, size, val, d): st['fault'] = (acc, addr); return False
u.hook_add(UC_HOOK_MEM_WRITE, wr)
u.hook_add(UC_HOOK_MEM_INVALID, bad)
return u, st
def restore(u, st):
for a, s, v in st['w']:
if ARENA <= a < ARENA + ARENA_SZ: u.mem_write(a, st['arena'][a:a + s])
st['w'].clear(); st['fault'] = None
def state(u, st, patched):
g = [u.reg_read(r) for r in GP]
tp = u.reg_read(UC_ARM64_REG_TPIDR_EL0)
if patched: g[18] = struct.unpack('<Q', u.mem_read(TSD + 8 * SLOT18, 8))[0]; tp = struct.unpack('<Q', u.mem_read(TSD + 8 * SLOTTLS, 8))[0]
g = g + [tp]
w = [x for x in st['w'] if not (patched and TSD <= x[0] < TSD + 0x10000)]
return g, u.reg_read(UC_ARM64_REG_SP), u.reg_read(UC_ARM64_REG_NZCV), [u.reg_read(r) for r in VR], w, st['fault']
def run(u, st, start, patched, init):
restore(u, st)
for r, v in zip(GP, init['g']): u.reg_write(r, v)
for r, v in zip(VR, init['v']): u.reg_write(r, v)
u.reg_write(UC_ARM64_REG_SP, SP0); u.reg_write(UC_ARM64_REG_NZCV, init['nzcv'])
u.reg_write(UC_ARM64_REG_TPIDR_EL0, init['tls'])
if not patched: u.reg_write(UC_ARM64_REG_TPIDRRO_EL0, init['tlr'])
if patched:
for key, idx in KEY_IDX.items():
u.mem_write(IB + KEY_PAGE_OFF + 8 * idx, struct.pack('<Q', KEY_SLOT[key] * 8))
u.mem_write(TSD + 8 * SLOT18, struct.pack('<Q', init['g'][18]))
u.mem_write(TSD + 8 * SLOTTLS, struct.pack('<Q', init['tls']))
u.mem_write(TSD + 8 * SLOTTLR, struct.pack('<Q', init['tlr']))
u.reg_write(GP[18], 0xDEADBEEFDEADBEEF)
end = {'pc': None}
if patched:
seen = {'patch': False}
def hk(uc, addr, size, d):
if addr >= IB + PATCH_OFF: seen['patch'] = True
elif seen['patch']: end['pc'] = addr; uc.emu_stop()
h = u.hook_add(UC_HOOK_CODE, hk)
try: u.emu_start(start, IB + 0x7FFFFFFF, count=400)
except UcError: pass
u.hook_del(h)
if end['pc'] is None and st['fault'] is None: end['pc'] = 'NOEXIT'
elif start - IB in winend:
lo, hi = start, IB + winend[start - IB]
def hk2(uc, addr, size, d):
if not (lo <= addr < hi): end['pc'] = addr; uc.emu_stop()
h = u.hook_add(UC_HOOK_CODE, hk2)
try: u.emu_start(start, IB + 0x7FFFFFFF, count=400)
except UcError: pass
u.hook_del(h)
if end['pc'] is None and st['fault'] is None: end['pc'] = 'NOEXIT'
else:
try: u.emu_start(start, IB + 0x7FFFFFFF, count=1)
except UcError: pass
end['pc'] = u.reg_read(UC_ARM64_REG_PC) if st['fault'] is None else None
s = state(u, st, patched)
return s + (end['pc'],)
def init_state(rng, kind, site_br=None):
g = []
for i in range(31):
if kind == 0: g.append(rng.randrange(0, 0x10000) & ~7)
elif kind == 1: g.append(rng.randrange(0, ARENA_SZ - 0x10000))
else: g.append(rng.getrandbits(64))
if site_br: g[18] = IB + site_br[0] + 4 * rng.randrange(site_br[1])
return {'g': g, 'v': [rng.getrandbits(128) for _ in range(32)], 'nzcv': rng.randrange(16) << 28, 'tls': rng.randrange(0, 0x100000) & ~15, 'tlr': rng.randrange(0x100000, 0x200000) & ~15}
def trial(UO, SO, UP, SP, a, init):
so = run(UO, SO, IB + a, False, init)
sp_ = run(UP, SP, IB + a, True, init)
ow = {x[0] for x in so[4]}
sp_ = sp_[:4] + ([x for x in sp_[4] if not (SP0 - 128 <= x[0] < SP0 and x[0] not in ow)],) + sp_[5:]
both = bool(so[5] and sp_[5])
same = (so[5] == sp_[5]) if (so[5] or sp_[5]) else (so == sp_)
return same, both, [k for k, (x, y) in enumerate(zip(so, sp_)) if x != y]
def work(job):
idx, chunk, mutated = job
rng = random.Random(A.seed * 1000003 + idx * 2 + mutated)
arena0 = rng.randbytes(ARENA_SZ)
UO, SO = mk(orig, arena0); UP, SP = mk(pat_mut if mutated else pat, arena0)
out = []
for a in chunk:
n = eff = 0; diffs = []
kinds = [0, 1] + ([] if a in brinfo else [2])
extra = 0
while kinds or (eff < A.min_eff and extra < A.max_extra):
if kinds: kind = kinds.pop(0)
else: kind = (1, 0)[extra % 2]; extra += 1
same, both, fl = trial(UO, SO, UP, SP, a, init_state(rng, kind, brinfo.get(a)))
n += 1; eff += not both
if not same: diffs.append((kind, fl))
if mutated and diffs: break
out.append((a, n, eff, diffs))
return out
def runall(lst, mutated):
k = 64 # 切块数固定,结果只随 seed 变、不随 jobs 变 | Chunk count is fixed, so the result varies only with seed, not with jobs
jobs = [(i, lst[i::k], mutated) for i in range(k) if lst[i::k]]
with mp.get_context('fork').Pool(A.jobs) as p:
return [r for part in p.imap_unordered(work, jobs) for r in part]
def ins_of(a): return next(md.disasm(orig[a:a + 4], a))
if __name__ == '__main__':
res = sorted(runall(sites, 0))
T = sum(r[1] for r in res); E = sum(r[2] for r in res)
zero = [r for r in res if r[2] == 0]; low = [r for r in res if r[2] < A.min_eff]
bad = [r for r in res if r[3]]
for a, n, eff, diffs in bad:
i = ins_of(a)
for kind, fl in diffs: print(f'DIFF {a:#x} {i.mnemonic} {i.op_str} kind={kind} fields={fl}', flush=True)
for a, n, eff, _ in zero:
i = ins_of(a); print(f'NOEFF {a:#x} {i.mnemonic} {i.op_str} trials={n}')
caught = miss = 0; mut_by = '-'
if mut_sites:
mres = runall(mut_sites, 1)
caught = sum(1 for r in mres if r[3])
for a, n, eff, d in mres:
if not d: i = ins_of(a); print(f'MUTMISS {a:#x} {mut_kind[a]} {i.mnemonic} {i.op_str} trials={n} eff={eff}')
miss = len(mres) - caught
mk_ = {}
for a, n, eff, d in mres: c = mk_.setdefault(mut_kind[a], [0, 0]); c[0] += 1; c[1] += bool(d)
mut_by = ' '.join(f'{k}:{v[1]}/{v[0]}' for k, v in sorted(mk_.items()))
if A.tsv:
with open(A.tsv, 'w') as f:
f.write('site\ttrials\teff\tdiffs\n')
for a, n, eff, d in res: f.write(f'{a:#x}\t{n}\t{eff}\t{len(d)}\n')
ok = not bad and not zero and not miss # 变异漏抓 = 判据分不出坏改写,判红(早先漏抓只打印不判) | A missed mutation = the criterion cannot tell a bad rewrite apart, so fail (earlier a miss was only printed, not judged)
print(f'EQUIV {MOD} {"OK" if ok else "FAIL"} 站点={len(res)} 试验={T} 有效试验={E} 双异常={T - E} '
f'有效≥1站点={len(res) - len(zero)} 有效≥{A.min_eff}站点={len(res) - len(low)} 零有效={len(zero)} 分歧站点={len(bad)} '
f'门站点(结构核对)={ngate} 已登记剪口(结构核对)={ncut} 观测门(结构核对)={nobs} 变异={len(mut_sites)}({mut_by}) 抓到={caught} 漏抓={miss} seed={A.seed}', flush=True)
sys.exit(0 if ok else 1)
+250
View File
@@ -0,0 +1,250 @@
# 函数级差分模糊台:对每个含改写点的函数,Switch 原映像在 Unicorn 里整函数跑 = 真值,改写映像同输入整函数跑 = 被测,比终态。
# 用法:fnfuzz.py <改写产物目录> <模块> <NSO> [--seed 1] [--trials 6] [--budget 200000] [--jobs N] [--mutate 200] [--funcs a,b,..] [--tsv 文件]
# 装法:两份映像同址装载、同样应用 RELATIVE/ABS64/GLOB_DAT/JUMP_SLOT 重定位;导入符号指向陷阱页(每符号 16 字节)。
# 一次试验在以下事件停:返回哨兵(ret)、调导入(import:名)、宿主门(gate:原映像执行 svc / 读 cntpct 处,改写映像进 KGATE 哨兵)、访存异常、指令预算用完。
# 两边停在同一事件(ret / 同名 import / 同一 gate 原址)才算「有效」,此时比:x0–x30(x18 比槽值)、sp、nzcv、v0–v31、tpidr、
# 全部写过的地址的终值(不比当前 sp 以下的死栈与 TSD)。改写映像在门处多压的 x29/x30 按模板还原后再比。
# 不等价报 DIFF;有效试验为 0 的函数列 NOEFF(射程缺口,不算失败但要报)。任一边停下时 sp 出了栈区记「sp越界」不比较(输入不现实)。
# 变异自检:抽 mutate 个普通改写块把替换指令改成 nop,统计「被执行到的」里有几个被判出分歧。
# Function-level differential fuzzing bench: for each function containing a rewrite site, the original Switch image run as a whole function in Unicorn = ground truth, the rewritten image run as a whole function with the same input = under test; final states are compared.
# Usage: fnfuzz.py <rewrite build output dir> <module> <NSO> [--seed 1] [--trials 6] [--budget 200000] [--jobs N] [--mutate 200] [--funcs a,b,..] [--tsv file]
# Loading: both images are loaded at the same address with the same RELATIVE/ABS64/GLOB_DAT/JUMP_SLOT relocations applied; imported symbols point at a trap page (16 bytes per symbol).
# A trial stops on one of these events: return sentinel (ret), call to an import (import:name), host gate (gate: where the original image executes svc / reads cntpct, the rewritten image enters the KGATE sentinel), memory access fault, instruction budget exhausted.
# Only when both sides stop on the same event (ret / same-named import / same gate original address) is the trial "effective"; then compare: x0–x30 (x18 against the slot value), sp, nzcv, v0–v31, tpidr,
# the final values of all written addresses (dead stack below the current sp and the TSD are not compared). The extra x29/x30 the rewritten image pushes at a gate are restored per the template before comparing.
# Non-equivalence is reported as DIFF; functions with 0 effective trials are listed as NOEFF (a coverage gap, not a failure but must be reported). If sp is outside the stack area when either side stops, it is recorded as 「sp越界」(sp out of bounds) and not compared (unrealistic input).
# Mutation self-check: draw mutate ordinary rewrite blocks and change the replaced instruction to nop, then count how many of those "actually executed" are judged divergent.
import sys, os, struct, random, argparse, bisect, multiprocessing as mp
from unicorn import *
from unicorn.arm64_const import *
from capstone import *
sys.path.insert(0, os.path.dirname(__file__))
import nsoimg
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
md.detail = True
ap = argparse.ArgumentParser()
ap.add_argument('dir'); ap.add_argument('mod'); ap.add_argument('nso')
ap.add_argument('--seed', type=int, default=1); ap.add_argument('--trials', type=int, default=6)
ap.add_argument('--budget', type=int, default=200000); ap.add_argument('--jobs', type=int, default=os.cpu_count())
ap.add_argument('--mutate', type=int, default=200); ap.add_argument('--funcs'); ap.add_argument('--tsv')
A = ap.parse_args()
IB = 0x100000000
ARENA, ARENA_SZ = 0x10000000, 0x1000000 # 随机堆:一半的 8 字节字是指回堆内的指针 | Random heap: half of the 8-byte words are pointers back into the heap
STK, STK_SZ = 0x20000000, 0x100000; SP0 = STK + STK_SZ - 0x10000 # sp 以上留 64 KB 给栈传参 | 64 KB kept above sp for stack-passed arguments
TSD = 0x30000000
TRAP = 0x300000000; RET = 0x400000000; GATE = 0x500000000
hdr = nsoimg.header(A.dir, A.mod)
PO, TE = hdr['PATCH_OFF'], hdr['TEXT_END']
KEY_IDX = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')}
KEY_SLOT = {k: 300 + i for i, k in enumerate(sorted(KEY_IDX, key=KEY_IDX.get))}
K18, KTLS, KTLR, KGATE = (KEY_SLOT[k] for k in ('K18', 'KTLS', 'KTLR', 'KGATE'))
KEY_PAGE_OFF = hdr['KEY_PAGE_OFF']
orig = bytearray(nsoimg.load(A.nso))
pat = bytearray(open(f'{A.dir}/{A.mod}.patched.bin', 'rb').read())
# ---- 重定位(两份映像一样)----
# ---- Relocations (identical for both images) ----
imports = {}
for off, typ, name, val, add in nsoimg.relocs(bytes(orig)):
if typ == 1027: v = IB + add
elif val is not None: v = IB + val + (add if typ == 257 else 0)
else: v = TRAP + 16 * imports.setdefault(name, len(imports)) + (add if typ == 257 else 0)
for b in (orig, pat): struct.pack_into('<Q', b, off, v & (2**64 - 1))
iname = {i: n for n, i in imports.items()}
TRAP_SZ = (16 * len(imports) + 0xFFFF) & ~0xFFFF or 0x10000
# ---- 改写点与函数 ----
# ---- Rewrite sites and functions ----
sites = {}
for l in open(f'{A.dir}/{A.mod}.sites.tsv'):
f = l.split()
if f[1] != 'J': sites[int(f[0], 16)] = f[1]
gsites = {a for a, k in sites.items() if k in ('svc', 'cntpct', 'cntvct')}
starts = nsoimg.func_starts(bytes(orig), TE)
def func_of(a): return starts[bisect.bisect_right(starts, a) - 1]
funcs = sorted({func_of(a) for a in sites})
if A.funcs: funcs = [int(x, 16) for x in A.funcs.split(',')]
def btarget(b, o):
w = struct.unpack_from('<I', b, o)[0]; imm = w & 0x3FFFFFF
if imm & 0x2000000: imm -= 0x4000000
return o + 4 * imm
def plain_subst(a):
s = btarget(pat, a)
ins = list(md.disasm(bytes(pat[s:s + 24]), s))
if len(ins) < 5 or ins[0].mnemonic != 'stp' or ins[1].mnemonic != 'mrs' or 'tpidrro_el0' not in ins[1].op_str: return None
if ins[2].mnemonic != 'adrp' or ins[2].operands[1].imm != KEY_PAGE_OFF: return None
if ins[3].mnemonic != 'ldr' or ins[3].operands[1].mem.base != ins[2].operands[0].reg: return None
if ins[4].mnemonic != 'add' or ins[4].operands[0].reg != ins[1].operands[0].reg or ins[4].operands[1].reg != ins[1].operands[0].reg: return None
if ins[5].mnemonic in ('ldr', 'str') and ins[5].operands[1].mem.base == ins[4].operands[0].reg: return ins[5].address + 4
return ins[4].address
mut = {}
if A.mutate:
cand = [a for a, k in sites.items() if k == 'x18' and plain_subst(a)]
for a in random.Random(A.seed).sample(cand, min(A.mutate, len(cand))): mut[a] = plain_subst(a)
pat_mut = bytearray(pat)
for a, s in mut.items(): struct.pack_into('<I', pat_mut, s, 0xD503201F)
GP = [getattr(sys.modules['unicorn.arm64_const'], f'UC_ARM64_REG_X{i}') for i in range(29)] + [UC_ARM64_REG_X29, UC_ARM64_REG_X30]
VR = [getattr(sys.modules['unicorn.arm64_const'], f'UC_ARM64_REG_Q{i}') for i in range(32)]
PAGE = lambda n: (n + 0xFFFF) & ~0xFFFF
class Emu:
def __init__(self, image, patched, arena0):
self.patched, self.image, self.arena0 = patched, bytes(image), arena0
u = self.u = Uc(UC_ARCH_ARM64, UC_MODE_ARM)
u.mem_map(IB, PO); u.mem_write(IB, self.image[:PO])
u.mem_map(IB + PO, PAGE(len(pat)) - PO, UC_PROT_EXEC) # 补丁区:两边同址同权限(原映像这段全 0),数据读写都异常 | Patch area: same address and same permissions on both sides (all zeros in the original image), data reads and writes both fault
if patched: u.mem_write(IB + PO, self.image[PO:])
RW = UC_PROT_READ | UC_PROT_WRITE # 堆 / 栈 / TSD 不可执行:间接调用落进随机数据时两边同样取指异常 | Heap / stack / TSD are non-executable: when an indirect call lands in random data, both sides take the same instruction fetch fault
u.mem_map(ARENA, ARENA_SZ, RW); u.mem_write(ARENA, arena0)
u.mem_map(STK, STK_SZ, RW); u.mem_map(TSD, 0x10000, RW)
for base, sz in ((TRAP, TRAP_SZ), (RET, 0x10000), (GATE, 0x10000)): u.mem_map(base, sz, UC_PROT_EXEC | UC_PROT_READ)
self.w = []; self.fault = None; self.stop = None; self.hit = set()
u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, addr, size, val, d: self.w.append((addr, size)))
def bad(uc, acc, addr, size, val, d): self.fault = (acc, addr); return False
u.hook_add(UC_HOOK_MEM_INVALID, bad)
def at(reason):
def h(uc, addr, size, d): self.stop = reason(addr); uc.emu_stop()
return h
u.hook_add(UC_HOOK_CODE, at(lambda a: ('import', iname.get((a - TRAP) // 16))), begin=TRAP, end=TRAP + TRAP_SZ - 1)
u.hook_add(UC_HOOK_CODE, at(lambda a: ('ret',)), begin=RET, end=RET + 0xFFFF)
if patched:
u.hook_add(UC_HOOK_CODE, at(lambda a: ('gate', self.gate_site())), begin=GATE, end=GATE + 0xFFFF)
for a, s in mut.items(): # 变异块是否被执行 | Whether the mutated block was executed
u.hook_add(UC_HOOK_CODE, lambda uc, addr, size, d: self.hit.add(addr), begin=IB + s, end=IB + s)
else:
for g in gsites: u.hook_add(UC_HOOK_CODE, at(lambda a: ('gate', a - IB)), begin=IB + g, end=IB + g)
def gate_site(self):
# 门块:stp x29,x30,[sp,#-16]! ; 键页取 KGATE ; ldr x29,[sp] ; blr x30 ← 返回点,块尾 b 原址+4
# Gate block: stp x29,x30,[sp,#-16]! ; fetch KGATE via key page ; ldr x29,[sp] ; blr x30 ← return point, block ends with b original address+4
r = self.u.reg_read(UC_ARM64_REG_X30) - IB
return btarget(pat, r + 4) - 4
def restore(self):
for a, s in self.w:
if ARENA <= a < ARENA + ARENA_SZ: self.u.mem_write(a, self.arena0[a - ARENA:a - ARENA + s])
elif IB <= a < IB + PO: self.u.mem_write(a, self.image[a - IB:a - IB + s])
elif STK <= a < STK + STK_SZ: self.u.mem_write(a, bytes(s))
self.w.clear(); self.fault = None; self.stop = None
def run(self, fn, init, budget):
u = self.u; self.restore()
for r, v in zip(GP, init['g']): u.reg_write(r, v)
for r, v in zip(VR, init['v']): u.reg_write(r, v)
u.reg_write(UC_ARM64_REG_X30, RET)
u.reg_write(UC_ARM64_REG_SP, SP0); u.reg_write(UC_ARM64_REG_NZCV, init['nzcv'])
u.reg_write(UC_ARM64_REG_FPCR, 0); u.reg_write(UC_ARM64_REG_FPSR, 0) # 每次试验从同一浮点控制 / 状态起,不跨函数泄漏 | Every trial starts from the same floating-point control / status, no leakage across functions
u.mem_write(SP0, init['stk'])
if self.patched:
u.reg_write(UC_ARM64_REG_TPIDRRO_EL0, TSD)
for key, idx in KEY_IDX.items():
u.mem_write(IB + KEY_PAGE_OFF + 8 * idx, struct.pack('<Q', KEY_SLOT[key] * 8))
for k, v in ((K18, init['g'][18]), (KTLS, init['tls']), (KTLR, init['tlr']), (KGATE, GATE)): u.mem_write(TSD + 8 * k, struct.pack('<Q', v))
u.reg_write(UC_ARM64_REG_X18, 0xDEADBEEFDEADBEEF); u.reg_write(UC_ARM64_REG_TPIDR_EL0, 0)
else:
u.reg_write(UC_ARM64_REG_TPIDRRO_EL0, init['tlr']); u.reg_write(UC_ARM64_REG_TPIDR_EL0, init['tls'])
try: u.emu_start(IB + fn, 0, count=budget)
except UcError: pass
if self.stop is None: self.stop = ('fault', self.fault) if self.fault else ('budget',)
return self.state()
def state(self):
u = self.u
g = [u.reg_read(r) for r in GP]; sp = u.reg_read(UC_ARM64_REG_SP)
tp = u.reg_read(UC_ARM64_REG_TPIDR_EL0)
if self.patched:
rq = lambda a: struct.unpack('<Q', u.mem_read(a, 8))[0]
g[18] = rq(TSD + 8 * K18); tp = rq(TSD + 8 * KTLS)
if self.stop[0] == 'gate': sp += 16 # 门块 blr 前已还原 x29(r26),活寄存器直接比;x30 是门返回点,下面置空 | The gate block has already restored x29 before blr (r26), live registers are compared directly; x30 is the gate return point and is cleared below
if self.stop[0] in ('gate', 'import'): g[30] = None # 门 / 导入处的 x30 是各自的返回点,不可比 | x30 at a gate / import is each side's own return point, not comparable
if self.stop[0] == 'gate' and not self.patched: g[30] = None
return {'stop': self.stop, 'g': g, 'sp': sp, 'nzcv': u.reg_read(UC_ARM64_REG_NZCV), 'tp': tp,
'v': [u.reg_read(r) for r in VR]}
def mem_diff(eo, ep, sp):
addrs = set()
for a, s in eo.w + ep.w:
for x in range(a, a + s):
if not (STK <= x < sp) and not (TSD <= x < TSD + 0x10000): addrs.add(x)
for x in sorted(addrs):
if eo.u.mem_read(x, 1) != ep.u.mem_read(x, 1): return x
return None
def init_state(rng):
def val():
r = rng.random()
if r < 0.4: return ARENA + (rng.randrange(ARENA_SZ - 0x10000) & ~7)
if r < 0.7: return rng.randrange(0, 256)
if r < 0.85: return rng.randrange(0, 1 << 32)
return rng.getrandbits(64)
return {'g': [val() for _ in range(31)], 'v': [rng.getrandbits(128) for _ in range(32)], 'nzcv': rng.randrange(16) << 28,
'tls': ARENA + (rng.randrange(ARENA_SZ - 0x10000) & ~15), 'tlr': ARENA + (rng.randrange(ARENA_SZ - 0x10000) & ~15),
'stk': b''.join(struct.pack('<Q', val()) for _ in range(64))}
def make_arena(rng):
q = []
for _ in range(ARENA_SZ // 8):
q.append(ARENA + (rng.getrandbits(24) & ~7) if rng.getrandbits(1) else rng.getrandbits(rng.choice((8, 32, 64))))
return struct.pack(f'<{len(q)}Q', *q)
ARENA0 = make_arena(random.Random(A.seed))
def work(job):
idx, chunk, mutated = job
eo = Emu(orig, False, ARENA0); ep = Emu(pat_mut if mutated else pat, True, ARENA0)
out = []
for fn in chunk:
rng = random.Random(A.seed * 1000003 + fn)
st = {'n': 0, 'eff': 0, 'stops': {}, 'diffs': [], 'hit': set()}
for t in range(A.trials):
init = init_state(rng)
so = eo.run(fn, init, A.budget); ep.hit.clear()
sp_ = ep.run(fn, init, A.budget * 4) # 改写件每个改写点多跑几条指令 | The rewritten image runs a few more instructions per rewrite site
st['n'] += 1; st['hit'] |= ep.hit
k = so['stop'][0]; st['stops'][k] = st['stops'].get(k, 0) + 1
if so['stop'][0] in ('budget',) or sp_['stop'][0] == 'budget': continue
if not (STK <= so['sp'] <= STK + STK_SZ and STK <= sp_['sp'] <= STK + STK_SZ):
st['stops']['sp越界'] = st['stops'].get('sp越界', 0) + 1; continue # 随机长度的变长栈分配把 sp 推出栈区:真实运行不会发生,改写块用 sp 下方红区(苹果 ABI 128 字节)在此会先异常 | A variable-length stack allocation of random length pushes sp out of the stack area: cannot happen in a real run; the rewrite block uses the red zone below sp (Apple ABI, 128 bytes) and would fault first here
if so['stop'][0] == 'fault' and sp_['stop'][0] == 'fault':
if so['stop'][1][1] != sp_['stop'][1][1]: st['diffs'].append((t, 'fault地址', so['stop'], sp_['stop']))
continue
if so['stop'] != sp_['stop']: st['diffs'].append((t, '停点', so['stop'], sp_['stop'])); continue
st['eff'] += 1
fl = [k for k in ('g', 'sp', 'nzcv', 'tp', 'v') if so[k] != sp_[k]]
if 'g' in fl: fl[fl.index('g')] = 'x' + ','.join(str(i) for i in range(31) if so['g'][i] != sp_['g'][i])
m = mem_diff(eo, ep, so['sp'])
if m is not None: fl.append(f'mem@{m:#x}')
if fl: st['diffs'].append((t, '终态', so['stop'], fl))
out.append((fn, st))
return out
def runall(lst, mutated):
k = 64
jobs = [(i, lst[i::k], mutated) for i in range(k) if lst[i::k]]
with mp.get_context('fork').Pool(A.jobs) as p:
return sorted(r for part in p.imap_unordered(work, jobs) for r in part)
if __name__ == '__main__':
res = runall(funcs, 0)
n = sum(s['n'] for _, s in res); eff = sum(s['eff'] for _, s in res)
stops = {}
for _, s in res:
for k, v in s['stops'].items(): stops[k] = stops.get(k, 0) + v
bad = [(f, s) for f, s in res if s['diffs']]; noeff = [f for f, s in res if s['eff'] == 0]
for f, s in bad:
for d in s['diffs'][:3]: print(f'DIFF fn={f:#x} trial={d[0]} {d[1]} {d[2]} {d[3]}', flush=True)
if A.tsv:
with open(A.tsv, 'w') as fo:
fo.write('func\ttrials\teff\tdiffs\tstops\n')
for f, s in res: fo.write(f"{f:#x}\t{s['n']}\t{s['eff']}\t{len(s['diffs'])}\t{s['stops']}\n")
hit = caught = 0
if mut:
mf = sorted({func_of(a) for a in mut})
mres = dict(runall(mf, 1))
for a, sa in mut.items():
s = mres[func_of(a)]
if IB + sa in s['hit']:
hit += 1; caught += bool(s['diffs'])
ok = not bad
print(f'FNFUZZ {A.mod} {"OK" if ok else "FAIL"} 函数={len(res)} 试验={n} 有效={eff} 停点={stops} 有效≥1函数={len(res) - len(noeff)} '
f'零有效函数={len(noeff)} 分歧函数={len(bad)} 变异={len(mut)} 被执行={hit} 抓到={caught} seed={A.seed} trials={A.trials}', flush=True)
sys.exit(0 if ok else 1)
+70
View File
@@ -0,0 +1,70 @@
// 宿主门功能回归:逐个门执行宿主现行 _dm_gate(entry.S),核对寄存器回写契约。
// 用法:gate_test <gates.tsv>... 每行 {返回点, 种类, arg, 原址};退出码 0 = 全过
// 每个门:x0..x29(x18 除外)设成各不相同的图案 → blr _dm_gate → 桩 gate_dispatch 按门种类写标记值:
// cntpct / cntvct:regs[arg] = 标记(原指令 mrs x<arg>, cntpct_el0);svc:x0..x7 = 标记 + i(出参位);obs:不写
// 返回后核对:桩写过的寄存器 == 标记,其余 == 原图案(桩故意破坏 x9–x17 与 NZCV),NZCV == 调用前,x30 == 调用返回点。任何一项不符报红。
// Host gate functional regression: run the host's current _dm_gate (entry.S) for each gate and check the register write-back contract.
// Usage: gate_test <gates.tsv>... each line is {return point, kind, arg, original address}; exit code 0 = all pass
// For each gate: set x0..x29 (except x18) to mutually distinct patterns → blr _dm_gate → the stub gate_dispatch writes marker values according to the gate kind:
// cntpct / cntvct: regs[arg] = marker (original instruction mrs x<arg>, cntpct_el0); svc: x0..x7 = marker + i (output argument positions); obs: writes nothing
// After return, check: registers written by the stub == marker, the rest == original pattern (the stub deliberately clobbers x9–x17 and NZCV), NZCV == value before the call, x30 == the call's return point. Any mismatch reports a failure.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void dm_gate(void);
void gate_call(uint64_t *in, uint64_t *out); // gate_tramp.S:in[0..29] 装进 x0..x29(跳过 x18)→ blr dm_gate → 全部存进 out[0..30] | gate_tramp.S: load in[0..29] into x0..x29 (skipping x18) → blr dm_gate → store everything into out[0..30]
static int g_kind, g_arg; // 当前被测门 | The gate currently under test
enum { K_CNT = 1, K_SVC = 2, K_OBS = 3 };
static const uint64_t MARK = 0x5157000000000000ull;
static uint64_t g_ret_seen;
uint64_t gate_dispatch(uint64_t ret_addr, uint64_t *regs) {
g_ret_seen = ret_addr;
uint64_t r = 0;
if (g_kind == K_CNT) { regs[g_arg] = MARK | (uint64_t)g_arg; r = regs[g_arg]; }
if (g_kind == K_SVC) { for (int i = 0; i < 8; i++) regs[i] = MARK | 0x100 | (uint64_t)i; r = regs[0]; }
// 宿主 C 代码按 AAPCS 可随意破坏 x9–x17 与 NZCV:桩在返回前最后一步故意全破坏,核 _dm_gate 从帧里恢复(观测门 / 分支门可放在函数中间的前提)
// Under AAPCS, host C code may freely clobber x9–x17 and NZCV: the stub deliberately clobbers all of them as its last step before returning, to check that _dm_gate restores them from the frame (the precondition for placing observation gates / branch gates in the middle of a function)
__asm__ volatile("mov x9, #0xdead\n mov x10, x9\n mov x11, x9\n mov x12, x9\n mov x13, x9\n mov x14, x9\n mov x15, x9\n mov x16, x9\n mov x17, x9\n"
"mov x9, #0x90000000\n msr nzcv, x9\n mov x9, #0xdead" ::: "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "cc");
return r;
}
void dm_thread_returned(void) { abort(); }
void unimpl_c(void) { abort(); }
int main(int argc, char **argv) {
int n = 0, bad = 0, nc = 0, ns = 0, no = 0;
for (int f = 1; f < argc; f++) {
FILE *fp = fopen(argv[f], "r"); if (!fp) { perror(argv[f]); return 2; }
char kind[16]; unsigned long long ret, orig; int arg;
while (fscanf(fp, "%llx %15s %d %llx", &ret, kind, &arg, &orig) == 4) {
g_kind = !strcmp(kind, "svc") ? K_SVC : !strcmp(kind, "obs") ? K_OBS : (!strcmp(kind, "cntpct") || !strcmp(kind, "cntvct")) ? K_CNT : 0;
if (!g_kind) { printf("FAIL 未知门种类 %s @%llx\n", kind, orig); bad++; continue; }
g_arg = arg;
uint64_t in[30], out[32], want[30];
for (int i = 0; i < 30; i++) in[i] = 0xA000000000000000ull | ((uint64_t)i << 32) | (uint64_t)(n * 31 + i);
memcpy(want, in, sizeof want);
if (g_kind == K_CNT) want[arg] = MARK | (uint64_t)arg;
if (g_kind == K_SVC) for (int i = 0; i < 8; i++) want[i] = MARK | 0x100 | (uint64_t)i;
gate_call(in, out);
int ok = 1;
for (int i = 0; i < 30; i++) {
if (i == 18) continue;
if (out[i] != want[i]) {
if (ok) printf("FAIL %s 门 @%#llx arg=%d:", kind, orig, arg);
printf(" x%d=%#llx(应 %#llx)", i, (unsigned long long)out[i], (unsigned long long)want[i]); ok = 0;
}
}
if (out[31] != 0x60000000ull) { printf("%sNZCV=%#llx(应 0x60000000)", ok ? "FAIL NZCV " : " ", (unsigned long long)out[31]); ok = 0; } // 调用前 cmp xzr,xzr 置 Z/C | cmp xzr,xzr before the call sets Z/C
if (out[30] != g_ret_seen) { printf("%s x30=%#llx(应 %#llx)", ok ? "FAIL x30 " : "", (unsigned long long)out[30], (unsigned long long)g_ret_seen); ok = 0; }
if (!ok) { printf("\n"); bad++; }
n++; nc += g_kind == K_CNT; ns += g_kind == K_SVC; no += g_kind == K_OBS;
}
fclose(fp);
}
printf("GATEFN %s 门=%d(svc %d / 计时 %d / 观测 %d)失败=%d\n", bad ? "FAIL" : "OK", n, ns, nc, no, bad);
return bad ? 1 : 0;
}
+64
View File
@@ -0,0 +1,64 @@
// gate_call(in, out):保存宿主被调用者保存寄存器 → in[0..29] 装进 x0..x29(跳过 x18:苹果平台寄存器)→ blr _dm_gate
// → x0..x30 存进 out[0..30]、NZCV 存 out[31] → 恢复宿主寄存器返回。out 指针放在栈上(调用期间所有通用寄存器都被占用)。
// gate_call(in, out): save the host's callee-saved registers → load in[0..29] into x0..x29 (skipping x18: the Apple platform register) → blr _dm_gate
// → store x0..x30 into out[0..30] and NZCV into out[31] → restore the host registers and return. The out pointer is kept on the stack (all general-purpose registers are occupied during the call).
.text
.globl _gate_call
.p2align 2
_gate_call:
stp x29, x30, [sp, #-112]!
stp x19, x20, [sp, #16]
stp x21, x22, [sp, #32]
stp x23, x24, [sp, #48]
stp x25, x26, [sp, #64]
stp x27, x28, [sp, #80]
str x1, [sp, #96] // out
mov x16, x0 // in
ldp x0, x1, [x16, #0]
ldp x2, x3, [x16, #16]
ldp x4, x5, [x16, #32]
ldp x6, x7, [x16, #48]
ldp x8, x9, [x16, #64]
ldp x10, x11, [x16, #80]
ldp x12, x13, [x16, #96]
ldr x14, [x16, #112]
ldr x15, [x16, #120]
ldr x17, [x16, #136]
ldr x19, [x16, #152]
ldp x20, x21, [x16, #160]
ldp x22, x23, [x16, #176]
ldp x24, x25, [x16, #192]
ldp x26, x27, [x16, #208]
ldp x28, x29, [x16, #224]
ldr x16, [x16, #128] // 最后装 x16 本身 | Load x16 itself last
cmp xzr, xzr // NZCV = Z|C(0x60000000),返回后核门是否恢复 | NZCV = Z|C (0x60000000); after return, check whether the gate restored it
bl _dm_gate // x30 = 返回点(门标识) | x30 = return point (gate identifier)
str x16, [sp, #-16]! // 暂存 x16,拿 out 指针 | Stash x16, get the out pointer
ldr x16, [sp, #112]
stp x0, x1, [x16, #0]
stp x2, x3, [x16, #16]
stp x4, x5, [x16, #32]
stp x6, x7, [x16, #48]
stp x8, x9, [x16, #64]
stp x10, x11, [x16, #80]
stp x12, x13, [x16, #96]
stp x14, x15, [x16, #112]
ldr x0, [sp], #16 // 原 x16 | Original x16
str x0, [x16, #128]
str x17, [x16, #136]
str x19, [x16, #152]
stp x20, x21, [x16, #160]
stp x22, x23, [x16, #176]
stp x24, x25, [x16, #192]
stp x26, x27, [x16, #208]
stp x28, x29, [x16, #224]
str x30, [x16, #240]
mrs x0, nzcv // 存取指令不改标志位,此处仍是门返回时的 NZCV | Load/store instructions do not change the flags; here it is still the NZCV as of gate return
str x0, [x16, #248]
ldp x19, x20, [sp, #16]
ldp x21, x22, [sp, #32]
ldp x23, x24, [sp, #48]
ldp x25, x26, [sp, #64]
ldp x27, x28, [sp, #80]
ldp x29, x30, [sp], #112
ret
+20
View File
@@ -0,0 +1,20 @@
01 automap shotgate_pages/automap.json
02 camp_e shotgate_pages/camp_e.json
03 char_stats shotgate_pages/char_stats.json
04 charselect shotgate_pages/charselect.json
05 cube shotgate_pages/cube.json
06 inventory shotgate_pages/inventory.json
07 newchar shotgate_pages/newchar.json
08 npc shotgate_pages/npc.json
09 options shotgate_pages/options.json
10 quest_log shotgate_pages/quest_log.json
11 skilltree shotgate_pages/skilltree.json
12 stash shotgate_pages/stash.json
13 warlock_camp shotgate_pages/warlock_camp.json
14 warlock_skilltree shotgate_pages/warlock_skilltree.json
15 waypoint shotgate_pages/waypoint.json
16 wild shotgate_pages/wild.json
17 combat_548 run_page.sh:combat:548
18 combat_615 run_page.sh:combat:615
19 combat_632 run_page.sh:combat:632
20 combat_712 run_page.sh:combat:712
1 01 automap shotgate_pages/automap.json
2 02 camp_e shotgate_pages/camp_e.json
3 03 char_stats shotgate_pages/char_stats.json
4 04 charselect shotgate_pages/charselect.json
5 05 cube shotgate_pages/cube.json
6 06 inventory shotgate_pages/inventory.json
7 07 newchar shotgate_pages/newchar.json
8 08 npc shotgate_pages/npc.json
9 09 options shotgate_pages/options.json
10 10 quest_log shotgate_pages/quest_log.json
11 11 skilltree shotgate_pages/skilltree.json
12 12 stash shotgate_pages/stash.json
13 13 warlock_camp shotgate_pages/warlock_camp.json
14 14 warlock_skilltree shotgate_pages/warlock_skilltree.json
15 15 waypoint shotgate_pages/waypoint.json
16 16 wild shotgate_pages/wild.json
17 17 combat_548 run_page.sh:combat:548
18 18 combat_615 run_page.sh:combat:615
19 19 combat_632 run_page.sh:combat:632
20 20 combat_712 run_page.sh:combat:712
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""用 NVIDIA FLIP 对同名 PNG 做 G1 逐帧对比。 | Use NVIDIA FLIP to do the G1 frame-by-frame comparison of PNGs with the same name."""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from PIL import Image
RED = "\033[31m"
RESET = "\033[0m"
MEAN_RE = re.compile(r"^\s*Mean:\s*([0-9]+(?:\.[0-9]+)?)\s*$", re.MULTILINE)
def pngs(directory: Path) -> dict[str, Path]:
return {
path.relative_to(directory).as_posix(): path
for path in directory.rglob("*")
if path.is_file() and path.suffix.lower() == ".png"
}
def flip_one(job: tuple[str, str, str, str]) -> tuple[str, float]:
name, flip, reference, test = job
result = subprocess.run(
[flip, "-r", reference, "-t", test, "-ppd", "95", "-v", "1", "-nerm"],
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
raise RuntimeError(f"FLIP 失败:{name}\n{result.stdout}{result.stderr}")
match = MEAN_RE.search(result.stdout + result.stderr)
if not match:
raise RuntimeError(f"FLIP 输出没有 Mean:{name}\n{result.stdout}{result.stderr}")
return name, float(match.group(1))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("reference", type=Path)
parser.add_argument("test", type=Path)
parser.add_argument(
"--flip",
type=Path,
default=Path(__file__).resolve().parents[3] / "dm/third_party/flip/flip",
)
args = parser.parse_args()
reference = pngs(args.reference)
test = pngs(args.test)
missing = sorted(set(reference) - set(test))
if missing:
for name in missing:
print(f"{RED}缺帧:{name}{RESET}", file=sys.stderr)
common = sorted(set(reference) & set(test))
jobs: list[tuple[str, str, str, str]] = []
invalid = bool(missing)
for name in common:
with Image.open(reference[name]) as reference_image, Image.open(test[name]) as test_image:
if reference_image.size != test_image.size:
print(
f"{RED}尺寸不同:{name} 真值={reference_image.size} 被测={test_image.size}{RESET}",
file=sys.stderr,
)
invalid = True
continue
jobs.append((name, str(args.flip), str(reference[name]), str(test[name])))
if invalid:
return 1
if not args.flip.is_file() or not os.access(args.flip, os.X_OK):
print(f"{RED}FLIP 不可执行:{args.flip}{RESET}", file=sys.stderr)
return 1
# PPD 推导:iPhone 17 Pro Max ≈460 ppi、观看 30 cm,
# 0.30·tan(1°)/0.0254·460 ≈ 95。
# PPD derivation: iPhone 17 Pro Max ≈460 ppi, viewed at 30 cm,
# 0.30·tan(1°)/0.0254·460 ≈ 95.
with ProcessPoolExecutor(max_workers=8) as pool:
results = list(pool.map(flip_one, jobs))
values = sorted(results)
for name, mean in values:
print(f"{name} {mean:.6f}")
overall = sum(mean for _, mean in values) / len(values) if values else 0.0
worst = sorted(values, key=lambda item: item[1], reverse=True)[:3]
worst_text = ", ".join(f"{name} {mean:.6f}" for name, mean in worst) or "无"
print(f"G1 均值 {overall:.6f} 最差 3 帧 {worst_text}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+86
View File
@@ -0,0 +1,86 @@
# Image Quality Metric
中文:[image_quality.zh-CN.md](image_quality.zh-CN.md)
This directory holds two rulers for measuring the picture, both measured on a Mac from offline screenshots taken with the host (`dmhost` from `dm/host`):
- **G1** (`shoot.sh` + `g1.py`): how far the picture at a given internal resolution is from "the best picture achievable on this phone screen". Used to choose the internal resolution.
- **Visual-equivalence ruler** (`ruler.sh`): whether, after a given rendering optimization is turned on, the picture is equivalent to the picture without it. Used to gate optimizations in the graphics layer.
Both use NVIDIA FLIP to measure the difference between two images. FLIP is an image difference metric that models human viewing, 0 = no visible difference; the source is in `dm/third_party/flip/` (BSD-3); first run `make -C dm/third_party/flip` to build `dm/third_party/flip/flip`.
## G1: how far from native resolution
### Definitions
- **Reference frame**: the same frozen frame, drawn at the screen's native resolution 2868x1320, without upscaling.
- **Frame under test**: the same frame drawn at some internal resolution (`DM_GAME_RES`), then upscaled to 2868x1320 through the real presentation path (the graphics layer's `present_encode`). The screenshot size is fixed by `DM_NVN_SHOT_OUT=2868x1320`, which `shoot.sh` already sets.
- **Switch baseline**: 900 high, bilinear upscaling. The width is taken as 1952 by the screen's aspect ratio (1952x900), not the 16:9 1600x900 — 16:9 output would be centered with black bars and the UI layout would differ as well, so it could not be matched pixel for pixel with the reference frame.
- **G1** = the FLIP (LDR) mean, `-ppd 95`, averaged over all frames. `ppd` is the number of pixels per degree of visual angle: the iPhone 17 Pro Max is about 460 ppi at a viewing distance of 30 cm, 0.30 × tan 1° ÷ 0.0254 × 460 ≈ 95.
- **Target**: the phone configuration's G1 ≤ half of the Switch baseline's G1.
What is measured is sharpness: the internal resolution changes only sharpness, not the field of view or the layout.
### Frame list
`frames.tsv` lists 20 frames, each line being "number, name, source":
- 01–16 take the trigger, key sequence and environment variables directly from the [screenshot gate](../screenshot_gate.md) page specs (`shotgate_pages/*.json`).
- 17–20 are four combat frames: they replay the command packets recorded from a ground-truth run (ground truth = reference data obtained by running the original game in a patched Ryujinx emulator) and use `DM_TICK_HOLD=<tick>:SHOT` to stop at the specified tick and take the screenshot.
Prerequisites:
- The standard save `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001` (`DM_GATE_SAVE` overrides it).
- The ground-truth replay files referenced in the page specs; the replay file path for the combat frames is hard-coded in `shoot.sh` and `ruler.sh`, pointing to a ground-truth run directory under `$DM_ROOT/run/verify/ryu/`. None of these are in the repository, and the emulator driver scripts used to record them are not shipped either, so the frames that rely on ground-truth replay cannot be run with this repository alone; see [../README.md](../README.md).
### Commands
```
make -C dm/third_party/flip
bash dm/verify/gfxq/shoot.sh dm/host/dmhost <build output dir> <WxH> <output dir> [parallel jobs=4] [number or name…]
python3 dm/verify/gfxq/g1.py <reference dir> <test dir> [--flip <flip path>]
```
- `shoot.sh` starts one host per frame and outputs `<output dir>/<number>.png` and `<number>.log`; with no numbers given it runs all 20 frames. When frames fail it lists the failed frames, exit code 1.
- `g1.py` compares the PNGs with the same name in the two directories: it prints the FLIP mean frame by frame, and the last line gives the G1 mean and the 3 worst frames. When the test directory is missing frames or the sizes on the two sides differ it reports red, exit code 1. `--flip` defaults to `dm/third_party/flip/flip`.
One complete measurement: first produce the reference directory at `2868x1320`, then produce one test directory for each candidate resolution, and compute G1 for each against the reference directory.
### About the video memory budget
The game's own video memory allocator has a budget constant (`main + 0x8524c4`), which is 260 MB in the original. Under this budget, as soon as the internal resolution is high the render targets no longer fit and the game crashes at startup, so a reference frame at native resolution cannot be drawn.
The rewriter has already registered this constant as a cut (`CUTS` in `dm/tools/patch_nso.py`), and it is 512 MB in all build outputs, so reference frames can simply be produced with an ordinary build output. `truth_out.sh` is the approach from before this cut went into the rewriter: it copies a build output that is still at 260 MB to `<source>-truth` and changes this one instruction. It first checks whether the source build output still has the original instruction at that location; for current build outputs it reports red and exits, and it no longer needs to be used.
### Rules
- **The reference frames and the frames under test must be produced with the same host binary.** Once the host's replay pacing changes, the two binaries are not drawing the same instant, and the difference that comes out is a systematic offset rather than a change in image quality. So every time readings are produced, first reproduce the reference frames with the current host, then produce the frames under test.
- **Run the frames at product pacing; do not set `DM_DETCLOCK`.** (`DM_DETCLOCK` is the deterministic clock for logic-type tests.) With it set, game ticks run ahead of asynchronous loading and the UI, and the behavior of panels and the loading screen is neither like the product nor deterministic.
- **Measure the noise floor every time.** Frozen frames cannot be made byte-for-byte reproducible: things the client itself animates, such as flames and animations, will not stop at the same instant in two runs. Run the same binary with the same configuration twice, and the FLIP between the two runs is the noise floor (record both the per-frame values and the mean); only more than 2 times the noise floor counts as a difference. The noise floor is not carried over from old numbers.
- **The width of the native setting must be exactly equal to the screen width.** If it is off by even a few columns, the output still has to be resampled across the whole screen, and every pixel gets interpolated once.
## Visual-equivalence ruler: `ruler.sh`
G1 has to be compared across runs, its noise floor is on the high side, and it cannot measure small differences. To judge "whether the picture is still the same one after a given optimization is turned on", use this ruler: it takes three shots in a row within **the same process and the same frozen tick**.
```
bash dm/verify/gfxq/ruler.sh <dmhost> <build output dir> <WxH> <output dir> [frame number…]
```
- One host is started per frame. `DM_NVN_RULER=1` makes the host first take the two shots A and B with the "reference settings" (the batch of rendering optimizations the graphics layer makes for Apple GPUs all turned off), then switch to the settings under test (everything on by default, plus the environment variables passed through by the caller) and take C. The three shots are 8 frames apart.
- **Noise** = FLIP(A, B), **difference** = FLIP(B, C), both with `-ppd 95`.
- With no frame numbers given it runs 4 frames: `02` camp, `16` wilderness, `18` combat, `06` inventory.
- Output is `<output dir>/<frame number>_{A,B,C}.png` and `<frame number>.log`; each frame prints one line of readings and the verdict, and the last line is 「汇总:n/m 帧等价」 (summary: n/m frames equivalent); if any frame is not equivalent the exit code is 1.
There are two modes of judgment, selected with the environment variable `RULER_MODE`:
| Mode | Applies to | Condition for judging equivalent |
|---|---|---|
| `exact` (default) | Optimizations such as merging and skipping, which ought to produce the same image | FLIP difference ≤ 0.01 and ≤ 2 × noise + 0.002; and the count of "large-difference pixels" (any channel differing by > 30/255): B–C ≤ 2 × A–B + 0.005% of the picture's pixels |
| `approx` | Approximations such as lowering resolution or changing the filter | FLIP difference ≤ 0.02; and the number of pixels differing by > 60/255: B–C ≤ 2 × A–B + 0.05% of the picture's pixels |
Why count large-difference pixels: the FLIP mean is insensitive to local defects; when a small patch is not drawn, the mean hardly moves.
Negative control: `DM_NVN_RULER_NEG=<fragment shader key>` makes the settings under test drop the draws that use that shader, and the ruler must report non-equivalent. After adding a new criterion or changing the switching timing, run a negative control once first to confirm the ruler is not running idle.
Limitation: this ruler can only measure settings that can be switched at run time.
+86
View File
@@ -0,0 +1,86 @@
# 画质度量
English: [image_quality.md](image_quality.md)
这个目录里是两把量画面的尺子,都在 Mac 上用宿主(`dm/host` 的 `dmhost`)离线截图来量:
- **G1**(`shoot.sh` + `g1.py`):某个内部分辨率下的画面,离「这块手机屏幕上能达到的最好画面」有多远。用来选内部分辨率。
- **视觉等价尺子**(`ruler.sh`):打开某项渲染优化之后,画面是否与不开时等价。用来给图形层的优化把关。
两者都用 NVIDIA FLIP 度量两张图的差异。FLIP 是一种模拟人眼观看的图像差异指标,0 = 看不出差别;源码在 `dm/third_party/flip/`(BSD-3),先 `make -C dm/third_party/flip` 编出 `dm/third_party/flip/flip`。
## G1:离原生分辨率有多远
### 口径
- **参照帧**:同一冻结帧,按屏幕原生分辨率 2868x1320 画出,不经放大。
- **被测帧**:同一帧按某个内部分辨率(`DM_GAME_RES`)画,再经真实的出图路径(图形层的 `present_encode`)放大到 2868x1320。截图尺寸由 `DM_NVN_SHOT_OUT=2868x1320` 固定,`shoot.sh` 已经带上。
- **Switch 基线**:900 高、双线性放大。宽度按屏幕比例取 1952(1952x900),不用 16:9 的 1600x900——16:9 出图会居中加黑边、界面布局也不同,没法与参照帧逐像素对上。
- **G1** = FLIP(LDR)均值,`-ppd 95`,对全部帧取平均。`ppd` 是每度视角的像素数:iPhone 17 Pro Max 约 460 ppi、观看距离 30 cm,0.30 × tan 1° ÷ 0.0254 × 460 ≈ 95。
- **目标**:手机方案的 G1 ≤ Switch 基线 G1 的一半。
量的是清晰度:内部分辨率只改清晰度,不改视野与布局。
### 帧清单
`frames.tsv` 列了 20 帧,每行「编号、名字、来源」:
- 01–16 直接取[画面闸门](../screenshot_gate.zh-CN.md)页规格(`shotgate_pages/*.json`)里的触发、键序与环境变量。
- 17–20 是四个战斗帧:回放一份真值局录下的命令包(真值 = 用打了补丁的 Ryujinx 模拟器跑原版游戏得到的参照数据),用 `DM_TICK_HOLD=<拍>:SHOT` 停在指定的拍截图。
前提:
- 标准存档 `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001`(`DM_GATE_SAVE` 可换)。
- 页规格里引用的真值回放文件;战斗帧的回放文件路径写死在 `shoot.sh` 与 `ruler.sh` 里,指向 `$DM_ROOT/run/verify/ryu/` 下的一个真值局目录。这些仓库里没有;录制用的模拟器驱动脚本也不随仓库提供,所以用到真值回放的帧在仓库外跑不了,见 [../README.zh-CN.md](../README.zh-CN.md)。
### 命令
```
make -C dm/third_party/flip
bash dm/verify/gfxq/shoot.sh dm/host/dmhost <产物目录> <宽x高> <输出目录> [并行数=4] [编号或名字…]
python3 dm/verify/gfxq/g1.py <参照目录> <被测目录> [--flip <flip 路径>]
```
- `shoot.sh` 每帧起一个宿主,输出 `<输出目录>/<编号>.png` 与 `<编号>.log`;不给编号就跑全部 20 帧。有帧失败时列出失败帧,退出码 1。
- `g1.py` 比两个目录里同名的 PNG:逐帧打印 FLIP 均值,末行给出 G1 均值与最差的 3 帧。被测目录缺帧或两边尺寸不同时报红,退出码 1。`--flip` 缺省就是 `dm/third_party/flip/flip`。
一次完整的量法:先用 `2868x1320` 出参照目录,再用各个候选分辨率各出一个被测目录,分别与参照目录算 G1。
### 关于显存预算
游戏自己的显存分配器有一个预算常数(`main + 0x8524c4`),原版是 260 MB。这个预算下内部分辨率一高,渲染目标就放不下、游戏启动即崩,画不出原生分辨率的参照帧。
改写器已经把这个常数登记为剪口(`dm/tools/patch_nso.py` 的 `CUTS`),所有产物里都是 512 MB,所以参照帧直接用普通产物出即可。`truth_out.sh` 是这条剪口进改写器之前的做法:把一份仍是 260 MB 的产物复制成 `<源>-truth` 并改这一条指令。它会先核对源产物该处是不是原来的指令,对现行产物会报红退出,不需要再用。
### 规矩
- **参照帧与被测帧必须用同一个宿主二进制出。** 宿主的回放节拍一变,两个二进制画的就不是同一刻,差出来的是系统偏差而不是画质变化。所以每次出读数都先用当前宿主重出参照帧,再出被测帧。
- **跑帧用产品节奏,不设 `DM_DETCLOCK`。**(`DM_DETCLOCK` 是给逻辑类测试用的确定性时钟。)设了它,游戏拍会跑在异步加载与界面前面,面板与读取画面的行为既不像产品也不确定。
- **噪声底每次实测。** 冻结帧做不到逐字节可复现:火焰、动画这类客户端自己在动的东西,两次运行不会停在同一刻。同一个二进制、同一个配置跑两遍,两遍之间的 FLIP 就是噪声底(逐帧与均值都记);超过噪声底 2 倍才算差异。噪声底不沿用旧数。
- **原生档的宽必须恰好等于屏幕宽。** 只差几列,出图也要整屏重采样,每个像素都被插值一遍。
## 视觉等价尺子:`ruler.sh`
G1 要跨运行比,噪声底偏高,量不出小差异。判断「开了某项优化之后画面还是不是同一张」用这把尺子:它在**同一个进程、同一冻结拍**里连截三张。
```
bash dm/verify/gfxq/ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…]
```
- 每帧起一个宿主。`DM_NVN_RULER=1` 让宿主先用「参照设置」(图形层针对苹果显卡做的那批渲染优化全部关掉)截 A、B 两张,然后切到被测设置(缺省全开,加上调用方透传的环境变量)截 C。三张各隔 8 帧。
- **噪声** = FLIP(A, B),**差异** = FLIP(B, C),都用 `-ppd 95`。
- 不给帧号时跑 4 帧:`02` 营地、`16` 野外、`18` 战斗、`06` 物品栏。
- 输出 `<输出目录>/<帧号>_{A,B,C}.png` 与 `<帧号>.log`;每帧打一行读数与判定,末行「汇总:n/m 帧等价」;有不等价的帧则退出码 1。
判定分两种口径,用环境变量 `RULER_MODE` 选:
| 口径 | 适用 | 判等价的条件 |
|---|---|---|
| `exact`(缺省) | 合并、跳过这类应当出同一张图的优化 | FLIP 差异 ≤ 0.01 且 ≤ 2 × 噪声 + 0.002;并且「大差像素」(任一通道差 > 30/255)的个数:B–C ≤ 2 × A–B + 画面像素的 0.005% |
| `approx` | 降分辨率、换滤波这类近似 | FLIP 差异 ≤ 0.02;并且差 > 60/255 的像素数:B–C ≤ 2 × A–B + 画面像素的 0.05% |
为什么要数大差像素:FLIP 均值对局部缺损不敏感,一小块没画出来,均值几乎不动。
负对照:`DM_NVN_RULER_NEG=<片元着色器键>` 让被测设置丢掉用该着色器的绘制,尺子必须报不等价。新加判据或改了切换时机之后,先跑一次负对照,确认尺子没有空转。
限制:这把尺子只能量运行中可以切换的设置。
+112
View File
@@ -0,0 +1,112 @@
#!/bin/bash
# 视觉等价尺子(同进程 A/B/C):每帧一个宿主、同一冻结拍连截三张——A、B 用真值设置(DM_NVN_RULER=1:TBDR 优化全关),
# 提交边界切到被测设置(缺省全开 + 调用方透传的环境)截 C。噪声 = FLIP(A,B),差异 = FLIP(B,C),-ppd 95;判「FLIP 差异 ≤ 0.01 且 ≤ 2×噪声 + 0.002」并且「大差像素(任一通道差 > 30/255)数:差异 ≤ 2×噪声 + 画面像素的 0.005%」。
# 跨运行比不可用:两次同设置独立运行的噪声底营地单帧 0.0108。只能测运行中可切换的设置。
# 用法:ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…,缺省 02 营地 16 野外 18 战斗 06 菜单] 产物:<输出目录>/<帧号>_{A,B,C}.png、<帧号>.log
# 口径(RULER_MODE):exact(缺省)= 合并 / 跳过类,应与真值同图,按 2×噪声线判;
# approx = 降分辨率 / 换滤波 / 近似类,按「FLIP(B,C) ≤ 0.02」判(实机上 3D 内部 0.75–0.80 倍、FLIP 0.017–0.023 肉眼无差别),
# 局部缺损判据放宽为「差 > 60/255 的像素数 B–C ≤ 2×A–B + 画面 0.05%」(边缘本来就会动;阈值待用 X1 的图校准,行里把两档像素数都打出来)。
# 负对照:DM_NVN_RULER_NEG=<片元键> 被测设置下丢掉该着色器的绘制,尺子必须报不等价。
# Visual-equivalence ruler (same process A/B/C): one host per frame, three consecutive shots of the same frozen tick - A and B use the ground-truth settings (DM_NVN_RULER=1: all TBDR optimizations off),
# at a commit boundary switch to the settings under test (default all on + the environment passed through by the caller) and shoot C. Noise = FLIP(A,B), difference = FLIP(B,C), -ppd 95; the verdict is "FLIP difference ≤ 0.01 and ≤ 2×noise + 0.002" and "count of large-difference pixels (any channel difference > 30/255): difference ≤ 2×noise + 0.005% of the frame's pixels".
# Cross-run comparison is unusable: the noise floor between two independent runs with the same settings is 0.0108 for a single camp frame. Only settings that can be switched at run time can be tested.
# Usage: ruler.sh <dmhost> <build output dir> <WxH> <output dir> [frame ids..., default 02 camp 16 wilderness 18 combat 06 menu] Build output: <output dir>/<frame id>_{A,B,C}.png, <frame id>.log
# Mode (RULER_MODE): exact (default) = merge / skip class, should produce the same image as ground truth, judged by the 2×noise line;
# approx = lower-resolution / filter-change / approximation class, judged by "FLIP(B,C) ≤ 0.02" (on a real device, with the 3D internal scale at 0.75–0.80×, FLIP 0.017–0.023 shows no difference to the naked eye),
# the local-defect criterion is relaxed to "count of pixels with difference > 60/255: B–C ≤ 2×A–B + 0.05% of the frame" (edges move anyway; the threshold is pending calibration with X1 images, and the line prints the pixel counts for both tiers).
# Negative control: DM_NVN_RULER_NEG=<fragment key> drops the draws of that shader under the settings under test; the ruler must report non-equivalence.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
FRAMES="$HERE/frames.tsv"
BIN=${1:?用法:ruler.sh <dmhost> <产物目录> <宽x高> <输出目录> [帧号…]}
PRODUCTS=${2:?缺少产物目录}
GAME_RES=${3:?缺少宽x高}
OUTPUT=${4:?缺少输出目录}
shift 4 || true
mkdir -p "$OUTPUT/tmp" || exit 2
selected=''
if [ "$#" -gt 0 ]; then
for wanted in "$@"; do
row=$(awk -F '\t' -v w="$wanted" '$1 == w || $2 == w { print; exit }' "$FRAMES")
[ -n "$row" ] || { echo "失败:未知帧编号或名称 $wanted" >&2; exit 2; }
selected="$selected$row"$'\n'
done
else
selected=$(printf '%s\n' 02 16 18 06 | while IFS= read -r wanted; do awk -F '\t' -v w="$wanted" '$1 == w { print; exit }' "$FRAMES"; done)
fi
run_frame() {
local row id name source frame_tmp log page trigger keys env_json key value trig_base shot_ui pid
row=$1
local -a env_args
id=$(printf '%s\n' "$row" | cut -f1); name=$(printf '%s\n' "$row" | cut -f2); source=$(printf '%s\n' "$row" | cut -f3)
frame_tmp="$OUTPUT/tmp/$id"; mkdir -p "$frame_tmp"; log="$OUTPUT/$id.log"
env_args=(DM_NVN_RULER=1 DM_NVN_SHOT_OUT="$GAME_RES" DM_GAME_RES="$GAME_RES" DM_TEMP="$frame_tmp")
if [[ "$source" == shotgate_pages/*.json ]]; then
page="$HERE/../$source"
IFS=$'\t' read -r trigger keys env_json < <(python3 -c 'import json,sys; h=json.load(open(sys.argv[1]))["host"]; print("\t".join((h["trigger"],h.get("keys") or "-",json.dumps(h.get("env",{}),separators=(",",":")))))' "$page")
[ "$keys" = - ] || env_args+=("DM_KEYS=$keys")
while IFS=$'\t' read -r key value; do [ -n "$key" ] && env_args+=("$key=$value"); done < <(python3 -c 'import json,os,sys; [print(k+"\t"+os.path.expanduser(v)) for k,v in json.loads(sys.argv[1]).items()]' "$env_json")
else
IFS=: read -r _ combat tick <<<"$source"
trigger="DM:Tick:${tick}#+20"
env_args+=(DM_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame' DM_C2S_REPLAY=${DM_ROOT:-$HOME/dm-work}/run/verify/ryu/war_summon13_1002_takeover/c2s.jsonl DM_GAME_SEED=305419896 DM_FIXED_TIME=1790895128 "DM_TICK_HOLD=${tick}:SHOT")
fi
trig_base=$(printf '%s' "$trigger" | sed -E 's/\+[0-9]+$//')
# 三张等间隔(各隔 8 帧):切换在 B 写盘后的下一次提交才生效,C 紧跟 B 一帧会赶在切换之前出图(负对照实测:尺子变成空转)
# Three shots at equal spacing (8 frames apart each): the switch only takes effect at the next commit after B is written to disk; a C that follows B by one frame would be rendered before the switch (negative control, measured: the ruler becomes a no-op)
shot_ui="$trig_base+20:$frame_tmp/A.png,$trig_base+28:$frame_tmp/B.png,$trig_base+36:$frame_tmp/C.png"
env_args+=("DM_NVN_SHOT_UI=$shot_ui")
SV=${DM_GATE_SAVE:-${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001}
W=$(mktemp -d "$frame_tmp/save.XXXX")
cp -R "$SV/0" "$W/save" && chmod -R u+w "$W/save" || { echo "失败 ${id}:拷存档失败" >&2; return 1; }
mkdir -p "$W/temp"
timeout 45s env "${env_args[@]}" DM_SAVE="$W/save" DM_TEMP="$W/temp" DM_WATCH_STALL=15 DM_WATCH=225 "$BIN" "$PRODUCTS" main sdk >"$frame_tmp/host.log" 2>&1 & pid=$!
while [ ! -s "$frame_tmp/A.png" ] || [ ! -s "$frame_tmp/B.png" ] || [ ! -s "$frame_tmp/C.png" ]; do
kill -0 "$pid" 2>/dev/null || { echo "失败 ${id}:宿主提前退出" >&2; cp "$frame_tmp/host.log" "$log"; rm -rf "$W"; return 1; }
sleep 1
done
kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null; cp "$frame_tmp/host.log" "$log"; rm -rf "$W"
for x in A B C; do cp "$frame_tmp/$x.png" "$OUTPUT/${id}_$x.png"; done # 留图:报红时要能看差在哪 | Keep the images: when it reports a failure, one must be able to see where the difference is
flip="$HERE/../../third_party/flip/flip"
noise=$(timeout 20s "$flip" -r "$frame_tmp/A.png" -t "$frame_tmp/B.png" -ppd 95 -v 1 -nerm 2>&1 | awk '/Mean:/{print $2; exit}')
diff=$(timeout 20s "$flip" -r "$frame_tmp/B.png" -t "$frame_tmp/C.png" -ppd 95 -v 1 -nerm 2>&1 | awk '/Mean:/{print $2; exit}')
[ -n "$noise" ] && [ -n "$diff" ] || { echo "失败 ${id}:FLIP 无 Mean" >&2; return 1; }
# 局部判据:FLIP 均值对局部缺损不敏感(负对照:战斗帧丢 FXAA 有 4051 个像素差 > 30,均值只有 0.0016)——再数「大差像素」(任一通道差 > 30/255)
# Local criterion: the FLIP mean is insensitive to local defects (negative control: a combat frame that drops FXAA has 4051 pixels with difference > 30, yet the mean is only 0.0016) - so also count "large-difference pixels" (any channel difference > 30/255)
read -r big_ab big_bc npx big60_ab big60_bc < <(python3 - "$frame_tmp/A.png" "$frame_tmp/B.png" "$frame_tmp/C.png" <<'PY2'
import sys
import numpy as np
from PIL import Image
a, b, c = (np.asarray(Image.open(p).convert('RGB')).astype(np.int16) for p in sys.argv[1:4])
big = lambda x, y, th: int((np.abs(x - y).max(axis=2) > th).sum())
print(big(a, b, 30), big(b, c, 30), a.shape[0] * a.shape[1], big(a, b, 60), big(b, c, 60))
PY2
)
[ -n "${npx:-}" ] || { echo "失败 ${id}:大差像素统计失败" >&2; return 1; }
if [ "${RULER_MODE:-exact}" = approx ]; then
verdict=$(awk -v d="$diff" -v ab="$big60_ab" -v bc="$big60_bc" -v px="$npx" 'BEGIN { print (d <= 0.02 && bc <= 2*ab + px*0.0005) ? "等价" : "不等价" }')
else
verdict=$(awk -v d="$diff" -v n="$noise" -v ab="$big_ab" -v bc="$big_bc" -v px="$npx" 'BEGIN { print (d <= 0.01 && d <= 2*n + 0.002 && bc <= 2*ab + px*0.00005) ? "等价" : "不等价" }')
fi
printf '%s 噪声 %.6f 差异 %.6f 大差像素(>30) 噪声 %d 差异 %d (>60) 噪声 %d 差异 %d 判定[%s] %s\n' "$id" "$noise" "$diff" "$big_ab" "$big_bc" "$big60_ab" "$big60_bc" "${RULER_MODE:-exact}" "$verdict"
[ "$verdict" = 等价 ]
}
fail=0; total=0; equivalent=0
sem="$OUTPUT/tmp/sem.$$"
mkfifo "$sem" || exit 2
exec 9<>"$sem"; rm -f "$sem"
for _ in 1 2 3 4; do printf '\n' >&9; done
result_dir="$OUTPUT/tmp/results"; mkdir -p "$result_dir"
while IFS= read -r row; do
[ -n "$row" ] || continue
total=$((total + 1)); id=$(printf '%s\n' "$row" | cut -f1)
read -u 9
{ if run_frame "$row"; then printf '1\n' >"$result_dir/$id"; else printf '0\n' >"$result_dir/$id"; fi; printf '\n' >&9; } &
done <<< "$selected"
wait
exec 9>&-
for result in "$result_dir"/*; do [ -f "$result" ] || continue; read -r ok <"$result"; [ "$ok" = 1 ] && equivalent=$((equivalent + 1)) || fail=1; done
echo "汇总:$equivalent/$total 帧等价"
rm -rf "$OUTPUT/tmp"
exit "$fail"
+119
View File
@@ -0,0 +1,119 @@
#!/bin/bash
# 批量截取画质度量帧;输出目录由调用方提供,不向工作树写产物。
# Batch-capture the image-quality metric frames; the output directory is provided by the caller, and no build output is written to the working tree.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
FRAMES="$HERE/frames.tsv"
HOSTSHOT="$HERE/../hostshot.sh"
BIN=${1:?用法:shoot.sh <dmhost> <产物目录> <DM_GAME_RES> <输出目录> [并行数=4(本机自起宿主上限)] [编号…]}
PRODUCTS=${2:?缺少产物目录}
GAME_RES=${3:?缺少 DM_GAME_RES}
OUTPUT=${4:?缺少输出目录}
JOBS=${5:-4}
shift 5 || true
case "$JOBS" in ''|*[!0-9]*|0) echo "失败:并行数必须是正整数" >&2; exit 2 ;; esac
mkdir -p "$OUTPUT/tmp" || exit 2
# 统一从 frames.tsv 读取,支持传编号或名称;未指定时跑全部 20 帧。
# Always read from frames.tsv; accepts ids or names; when unspecified, runs all 20 frames.
selected=''
if [ "$#" -gt 0 ]; then
for wanted in "$@"; do
row=$(awk -F '\t' -v w="$wanted" '$1 == w || $2 == w { print; exit }' "$FRAMES")
[ -n "$row" ] || { echo "失败:未知帧编号或名称 $wanted" >&2; exit 2; }
selected="$selected$row
"
done
else
selected=$(cat "$FRAMES")
fi
start=$SECONDS
fail_file="$OUTPUT/tmp/failed.$$"
: > "$fail_file"
run_frame() {
local row=$1 id name source png log frame_tmp trigger keys env_json page key value
local -a env_args
id=$(printf '%s\n' "$row" | cut -f1)
name=$(printf '%s\n' "$row" | cut -f2)
source=$(printf '%s\n' "$row" | cut -f3)
png="$OUTPUT/$id.png"
log="$OUTPUT/$id.log"
frame_tmp="$OUTPUT/tmp/$id"
mkdir -p "$frame_tmp"
: > "$frame_tmp/run.log"
env_args=(DM_NVN_SHOT_OUT=2868x1320 DM_GAME_RES="$GAME_RES" DM_TEMP="$frame_tmp")
if [[ "$source" == shotgate_pages/*.json ]]; then
page="$HERE/../$source"
IFS=$'\t' read -r trigger keys env_json <<EOF2
$(python3 - "$page" <<'PY'
import json, sys
page = json.load(open(sys.argv[1]))
host = page['host']
print('\t'.join((host['trigger'], host.get('keys') or '-', json.dumps(host.get('env', {}), separators=(',', ':')))))
PY
)
EOF2
[ "$keys" = - ] || env_args+=("DM_KEYS=$keys")
while IFS=$'\t' read -r key value; do
[ -n "$key" ] && env_args+=("$key=$value")
done < <(python3 - "$env_json" <<'PY'
import json, os, sys
for key, value in json.loads(sys.argv[1]).items():
print(key + '\t' + os.path.expanduser(value))
PY
)
else
IFS=: read -r _ combat tick <<EOF2
$source
EOF2
trigger="DM:Tick:${tick}#+20"
env_args+=(
'DM_KEYS=X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame'
"DM_C2S_REPLAY=${DM_ROOT:-$HOME/dm-work}/run/verify/ryu/war_summon13_1002_takeover/c2s.jsonl"
DM_GAME_SEED=305419896
DM_FIXED_TIME=1790895128
"DM_TICK_HOLD=${tick}:SHOT"
)
fi
if env "${env_args[@]}" "$HOSTSHOT" "$BIN" "$PRODUCTS" "$trigger" "$png" 180 >"$frame_tmp/run.log" 2>&1; then
if [ -f "$log" ]; then cat "$frame_tmp/run.log" >> "$log"; else cp "$frame_tmp/run.log" "$log"; fi
echo "完成 $id $name"
else
if [ -f "$log" ]; then cat "$frame_tmp/run.log" >> "$log"; else cp "$frame_tmp/run.log" "$log"; fi
printf '%s\t%s\n' "$id" "$name" >> "$fail_file"
echo "失败 $id $name(见 $log)" >&2
fi
}
# Bash 3.2 无 wait -n,用 FIFO 令牌池维持并行上限。
# Bash 3.2 has no wait -n; use a FIFO token pool to keep the parallelism cap.
sem="$OUTPUT/tmp/sem.$$"
mkfifo "$sem" || exit 2
exec 9<>"$sem"
rm -f "$sem"
for _ in $(seq 1 "$JOBS"); do printf '\n' >&9; done
while IFS= read -r row; do
[ -n "$row" ] || continue
read -u 9
{ run_frame "$row"; printf '\n' >&9; } &
done <<EOF2
$selected
EOF2
wait
exec 9>&-
rc=0
if [ -s "$fail_file" ]; then
rc=1
echo "失败帧:"
cat "$fail_file"
fi
rm -rf "$OUTPUT/tmp"
elapsed=$((SECONDS - start))
echo "总墙钟:${elapsed}s"
exit "$rc"
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# 画质真值专用产物(只给离线画真值帧用,产品构建绝不带):复制产物目录到 <源>-truth,
# 把游戏显存分配器预算常数 main+0x8524c4 `mov x8,#0x10400000`(260 MB)改成 `mov x8,#0x20000000`(512 MB)。
# 依据:内部分辨率 > 约 345 万像素时该分配器放不下渲染目标、游戏启动即崩;真值要按屏幕原生 2868x1320 画。
# 该常数只是显存池预算,不进游戏逻辑——由 V1 逐拍对拍核(见 image_quality.md)。
# 用法:truth_out.sh [源产物目录=$DM_ROOT/build/cache/dm/out/<当前代号>-keypage] 输出:<源>-truth,打印其路径
# Build output dedicated to image-quality ground truth (only for rendering ground-truth frames offline; product builds never carry it): copy the build output directory to <source>-truth,
# and change the game's video memory allocator budget constant at main+0x8524c4 from `mov x8,#0x10400000` (260 MB) to `mov x8,#0x20000000` (512 MB).
# Rationale: when the internal resolution is > about 3.45 million pixels, this allocator cannot fit the render targets and the game crashes at startup; ground truth must be rendered at the screen's native 2868x1320.
# This constant is only the video memory pool budget and does not enter game logic - checked by the V1 per-tick comparison (see image_quality.md).
# Usage: truth_out.sh [source build output dir=$DM_ROOT/build/cache/dm/out/<current codename>-keypage] Output: <source>-truth, prints its path
set -eu
SRC=${1:-$(bash "$(dirname "$0")/../../tools/product.sh" path keypage)}; DST=$SRC-truth
OFF=$((0x8524c4)); OLD=d2a20808; NEW=d2a40008 # MOVZ X8,#0x1040,LSL#16 → MOVZ X8,#0x2000,LSL#16(小端存放) | MOVZ X8,#0x1040,LSL#16 → MOVZ X8,#0x2000,LSL#16 (stored little-endian)
le() { echo "$1" | sed -E 's/(..)(..)(..)(..)/\4\3\2\1/'; }
cur=$(xxd -s $OFF -l 4 -p "$SRC/main.patched.bin")
[ "$cur" = "$(le $OLD)" ] || { echo "【红】源产物 main+0x8524c4 不是预期指令 $OLD(读到小端 $cur),构建号变了?不改" >&2; exit 2; }
rm -rf "$DST"; cp -R "$SRC" "$DST"
printf "$(le $NEW | sed 's/../\\x&/g')" | dd of="$DST/main.patched.bin" bs=1 seek=$OFF conv=notrunc 2>/dev/null
[ "$(xxd -s $OFF -l 4 -p "$DST/main.patched.bin")" = "$(le $NEW)" ] || { echo "【红】写入核对失败" >&2; exit 1; }
cmp -l "$SRC/main.patched.bin" "$DST/main.patched.bin" | wc -l | awk '{ if ($1 > 4) { print "【红】改动字节数 " $1 " > 4" > "/dev/stderr"; exit 1 } }'
echo "$DST"
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# 宿主截图(画面闸门用):标准存档新副本起 dmhost,第 N 帧 DM_NVN_SHOT 截图,截到即按自记 pid 停。
# 用法:hostshot.sh <dmhost> <产物目录> <帧号 | 触发子串+帧偏移> <输出.png> [超时秒=120] 其余环境变量(DM_KEYS、DM_AOC_OWNED 等)原样透传
# HOSTSHOT_WRAP:宿主命令前缀(如 taskpolicy -c background 让宿主跑慢,量随墙钟走的动画)
# 第 3 参含「+」= 按 UI 消息截图(DM_NVN_SHOT_UI),否则按帧号(DM_NVN_SHOT)。存档:DM_GATE_SAVE(缺省现行标准存档 save_ref_warlock),起跑前打印其指纹
# Host screenshot (for the screenshot gate): start dmhost on a fresh copy of the standard save, take the DM_NVN_SHOT screenshot at frame N, and stop by the self-recorded pid as soon as it is captured.
# Usage: hostshot.sh <dmhost> <build output dir> <frame number | trigger substring+frame offset> <output.png> [timeout seconds=120] other environment variables (DM_KEYS, DM_AOC_OWNED, etc.) are passed through unchanged
# HOSTSHOT_WRAP: host command prefix (e.g. taskpolicy -c background to make the host run slowly, for measuring animations that follow the wall clock)
# 3rd argument containing "+" = screenshot by UI message (DM_NVN_SHOT_UI), otherwise by frame number (DM_NVN_SHOT). Save: DM_GATE_SAVE (default: the current standard save save_ref_warlock), its fingerprint is printed before the run starts
set -u
BIN=$1; OUT=$2; N=$3; PNG=$4; TO=${5:-600}
SV=${DM_GATE_SAVE:-${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001}
echo "SAVE_SHA $("$(dirname "$0")/savesha.sh" "$SV") $SV"
W=$(mktemp -d "${PNG%.png}.XXXX"); cp -R "$SV/0" "$W/save" && chmod -R u+w "$W/save" || { echo "拷存档失败" >&2; exit 2; }
case "$N" in *+*) SHOTENV="DM_NVN_SHOT_UI=$N:$PNG" ;; *) SHOTENV="DM_NVN_SHOT=$N:$PNG" ;; esac
mkdir -p "$W/temp"
${HOSTSHOT_WRAP:-} env DM_SAVE="$W/save" DM_TEMP="$W/temp" "$SHOTENV" DM_WATCH_STALL=15 DM_WATCH=$((TO * 5 / 4)) "$BIN" "$OUT" main sdk > "$W/host.log" 2>&1 & pid=$!
printf '%s\n' "$pid" > "${PNG%.png}.pid"
s=$SECONDS
# 只认图形侧写盘完成行「截图 宽x高 格式 n → 路径 成功」:DM_NVN_SHOT_UI 的「命中 → 第 +N 帧截图 路径」行也含路径,按它判会在截图前停宿主(假「截到」)
# Only accept the graphics-side write-complete line 「截图 宽x高 格式 n → 路径 成功」(screenshot WxH format n → path succeeded): the DM_NVN_SHOT_UI line 「命中 → 第 +N 帧截图 路径」(hit → screenshot at frame +N path) also contains the path, and judging by it would stop the host before the screenshot (a false "captured")
until grep -q "→ $PNG 成功" "$W/host.log" 2>/dev/null; do
grep -q "→ $PNG 失败" "$W/host.log" 2>/dev/null && { kill $pid; echo "截图写盘失败" >&2; rm -rf "$W"; exit 1; }
grep -q "读取画面未撤(等待" "$W/host.log" 2>/dev/null && { kill $pid; wait $pid 2>/dev/null; cp "$W/host.log" "${PNG%.png}.log"; echo "读取画面未撤(等待 15 秒)" >&2; rm -rf "$W"; exit 1; }
grep -q "坐标核对不一致" "$W/host.log" 2>/dev/null && { kill $pid; wait $pid 2>/dev/null; cp "$W/host.log" "${PNG%.png}.log"; echo "站位核对不一致,宿主已撤掉截图" >&2; rm -rf "$W"; exit 1; } # 不等超时:宿主不会再截图 | Do not wait for the timeout: the host will not take a screenshot any more
kill -0 $pid 2>/dev/null || { echo "宿主在第 $N 帧前退出(日志 ${PNG%.png}.log)" >&2; cp "$W/host.log" "${PNG%.png}.log"; tail -3 "$W/host.log" >&2; rm -rf "$W"; exit 1; }
[ $((SECONDS - s)) -gt "$TO" ] && { kill $pid; echo "$TO 秒未到第 $N 帧" >&2; grep '【红】看门狗' "$W/host.log" | tail -1 >&2 || true; rm -rf "$W"; exit 1; }
sleep 1
done
kill $pid 2>/dev/null; wait $pid 2>/dev/null; cp "$W/host.log" "${PNG%.png}.log"; rm -rf "$W" # 完整宿主日志留在截图旁(闸门按它判 GPU 错误) | The full host log is kept next to the screenshot (the gate check judges GPU errors from it)
[ -s "$PNG" ] || { echo "日志说截到但 $PNG 不存在" >&2; exit 1; }
echo "截到 ${PNG}($((SECONDS - s)) 秒)"
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""检查键页间接访问、旧槽访问计数和 text 差异。用法:keypage_check.py NEW OLD。 | Check key-page indirect accesses, the old-slot access count, and text differences. Usage: keypage_check.py NEW OLD."""
import collections
import re
import struct
import sys
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
KEYS = ('K18', 'KTLS', 'KTLR', 'KGATE', 'KRES0', 'KRES1', 'KASPECT', 'KASPECTUI')
KEY_OFF = {504: 'KASPECTUI', 505: 'KASPECT', 506: 'KRES0', 507: 'KRES1', 508: 'K18', 509: 'KTLS', 510: 'KTLR', 511: 'KGATE'}
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
md.detail = True
def meta(path):
out = {}
for line in open(path):
if line.startswith('# '):
k, v = line[2:].rstrip().split('\t', 1)
out[k] = int(v, 0) if v.startswith('0x') else v
return out
def old_counts(directory):
counts = collections.Counter()
for line in open(f'{directory}/main.sites.tsv'):
if line.startswith('#'):
continue
fields = line.rstrip().split('\t')
if fields[1] == 'x18' or fields[1] == 'W':
counts['K18'] += 1
elif fields[1] == 'tpidr_r' or fields[1] == 'tpidr_w':
counts['KTLS'] += 1
elif fields[1] == 'tpidrro_r':
counts['KTLR'] += 1
for line in open(f'{directory}/main.gates.tsv'):
if line.strip():
counts['KGATE'] += 1
for line in open(f'{directory}/main.params.tsv'):
if line.startswith('#'):
continue
key = line.rstrip().split('\t')[3]
counts[key] += 1
return counts
def new_counts(directory, key_page_off, patch_off):
counts = collections.Counter()
data = open(f'{directory}/main.patched.bin', 'rb').read()
ins = list(md.disasm(data[patch_off:], patch_off))
for prev, cur in zip(ins, ins[1:]):
if prev.mnemonic != 'adrp' or cur.mnemonic != 'ldr':
continue
if prev.operands[0].reg != cur.operands[1].mem.base or prev.operands[1].imm != key_page_off:
continue
index = cur.operands[1].mem.disp // 8
if 0 <= index < len(KEYS) and cur.operands[1].mem.disp % 8 == 0:
counts[KEYS[index]] += 1
return counts
def differences(new_dir, old_dir, text_end):
"""原 text 区新旧逐字节比:改写站点处新旧都须是 b(补丁区后移,只允许跳转目标不同);参数位 / 剪口 / 规则剪口放行;其余不许变。 | Byte-by-byte comparison of the original text area, new vs old: at rewrite sites both new and old must be b (the patch area moved back, only the jump target may differ); parameter sites / cuts / rule cuts are let through; nothing else may change."""
new = open(f'{new_dir}/main.patched.bin', 'rb').read()[:text_end]
old = open(f'{old_dir}/main.patched.bin', 'rb').read()[:text_end]
allowed, sites = set(), set()
for base in (new_dir, old_dir):
for name in ('main.params.tsv', 'main.cuts.tsv', 'main.rules.tsv'):
try: lines = open(f'{base}/{name}')
except FileNotFoundError: continue
for line in lines:
if line.startswith('#') or not line.strip(): continue
f = line.split('\t'); a = int(f[0], 0)
if name == 'main.params.tsv': allowed.update(range(a, a + 8)); allowed.update(range(int(f[1], 0), int(f[1], 0) + 8))
else: allowed.update(range(a, a + len(bytes.fromhex(f[1]))))
for line in open(f'{base}/main.obs.tsv'): # 观测门入口同样换成跳补丁区的 b | Observation gate entries are likewise replaced with a b into the patch area
if line.startswith('#') or not line.strip(): continue
sites.add(int(line.split('\t')[0], 0))
for line in open(f'{base}/main.sites.tsv'):
if line.startswith('#') or not line.strip(): continue
f = line.split('\t'); a = int(f[0], 0); sites.add(a)
if f[1] == 'W': allowed.update(range(a, int(f[2], 0)))
isb = lambda w: (w & 0xFC000000) == 0x14000000
bad = []
for a in range(0, min(len(new), len(old)) & ~3, 4):
if new[a:a + 4] == old[a:a + 4] or a in allowed: continue
if a in sites and isb(struct.unpack('<I', new[a:a + 4])[0]) and isb(struct.unpack('<I', old[a:a + 4])[0]): continue
bad.append(a)
return bad, len(sites)
def main():
if len(sys.argv) != 3:
raise SystemExit('用法:keypage_check.py NEW_DIR OLD_DIR')
new_dir, old_dir = sys.argv[1:]
m = meta(f'{new_dir}/main.fixups.tsv')
assert m['KEY_PAGE_SIZE'] == 0x4000
assert m['KEY_PAGE_OFF'] % 0x4000 == 0
assert m['PATCH_OFF'] % 0x10000 == 0 and m['KEY_PAGE_OFF'] < m['PATCH_OFF']
raw = open(f'{new_dir}/main.patched.bin', 'rb').read()
assert raw[m['KEY_PAGE_OFF']:m['KEY_PAGE_OFF'] + 0x4000] == bytes(0x4000)
bad = []
for ins in md.disasm(raw[m['PATCH_OFF']:], m['PATCH_OFF']):
if ins.mnemonic == 'mrs' and ins.op_str.endswith('tpidrro_el0'):
nxt = list(md.disasm(raw[ins.address + 4:ins.address + 12], ins.address + 4))
if nxt and nxt[0].mnemonic in ('ldr', 'str') and re.search(r'\[x(\d+), #([0-9]+)\]', nxt[0].op_str):
if int(nxt[0].op_str.rsplit('#', 1)[1].rstrip(']')) in tuple(x * 8 for x in KEY_OFF):
bad.append(ins.address)
assert not bad, f'仍有直取槽序列: {[hex(x) for x in bad]}'
new = new_counts(new_dir, m['KEY_PAGE_OFF'], m['PATCH_OFF'])
old = old_counts(old_dir)
assert all(new[k] == old[k] for k in KEYS), f'计数不等: new={new} old={old}'
diff, nsites = differences(new_dir, old_dir, m['TEXT_END'])
assert not diff, f'text 非站点跳转 / 参数 / 剪口差异: {[hex(x) for x in diff[:20]]}'
print('键页布局与初值:期望 → 真结果:0x4000 对齐、补丁区前、全零 → 通过')
print(f'各下标引用计数:期望 → 真结果:{dict(old)} → {dict(new)}')
print(f'原 text 差异:期望 → 真结果:仅 {nsites} 个站点的 b 目标、参数位与既有剪口 → 通过')
if __name__ == '__main__':
main()
+110
View File
@@ -0,0 +1,110 @@
#!/bin/bash
# 产物自身确定性闸门:同一 cvd5 回放逐拍比较 n/h 摘要。
# 用法:logicself.sh [产物=out/<当前代号>-touch] [拍数=230]
# Determinism gate check of the build output itself: compare n/h digests tick by tick over the same cvd5 replay.
# Usage: logicself.sh [build output=out/<current codename>-touch] [ticks=230]
set -u
export LC_ALL=C
HERE=$(cd "$(dirname "$0")" && pwd)
X=${DM_WORK_ROOT:-${DM_ROOT:-$HOME/dm-work}}
PY=${DM_PY:-$X/build/cache/dm/venv/bin/python3}
TR=${DM_LOGICSELF_TRUTH:-$X/data/switch/truth_runs/cvd5}
OUT_ARG=${1:-out/$(bash "$(dirname "$0")/../tools/product.sh" name touch)}
N=${2:-230}
case "$N" in ''|*[!0-9]*) echo "LOGICSELF RED 拍数非法:$N"; exit 2;; esac
case "$OUT_ARG" in /*) OUT=$OUT_ARG;; *) OUT=$X/build/cache/dm/$OUT_ARG;; esac
BASELINE=${LOGICSELF_BASELINE:-$HERE/logicself/touch.json} # 基线不带产物代号:换代不用改名(规则没变时逐拍结果不变,变了就该重录) | The baseline carries no build output codename: no rename needed on a generation change (per-tick results stay the same when the rules have not changed; if they changed, it should be re-recorded)
[ -f "$TR/meta.json" ] && [ -f "$TR/c2s.jsonl" ] || { echo "LOGICSELF RED 真值文件不全:$TR"; exit 2; }
[ -f "$OUT/main.patched.bin" ] || { echo "LOGICSELF RED 产物缺 main.patched.bin:$OUT"; exit 2; }
if [ "${LOGICSELF_REBASE:-0}" != 1 ] && [ ! -f "$BASELINE" ]; then
echo "LOGICSELF RED 没有基线文件:$BASELINE"
exit 1
fi
mkdir -p "$HERE/logicself" || exit 2
RUNROOT=${DM_LOGICSELF_RUNROOT:-$X/run/verify/dm/logicself}
mkdir -p "$RUNROOT" || exit 2
STAMP=$(date +%Y%m%d_%H%M%S)_$$
run_once() {
local tag=$1 run
run="$RUNROOT/${STAMP}_${tag}"
mkdir -p "$run/user" || return 2
save=$($PY - "$TR/meta.json" <<'PY'
import json, sys
m=json.load(open(sys.argv[1])); s=m['save']; print(s[1] if isinstance(s, list) else s)
PY
) || return 2
[ -d "$save/0" ] || { echo "LOGICSELF RED 起档缺 0/:$save" >&2; return 2; }
cp -R "$save/0" "$run/user/0" && chmod -R u+w "$run/user/0" || return 2
seed=$($PY - "$TR/meta.json" <<'PY'
import json, sys
print(json.load(open(sys.argv[1]))['game_seed'])
PY
) || return 2
ft=$($PY - "$TR/meta.json" <<'PY'
import json, sys
m=json.load(open(sys.argv[1])); print(m.get('fix_time') if m.get('fix_time') is not None else m['wall_start'])
PY
) || return 2
( cd "$HERE/../host" && timeout 100s make -s ) >"$run/make.log" 2>&1 || { echo "LOGICSELF RED 宿主编译失败;局目录 $run" >&2; return 1; }
K=${KEYS_FRONT:-A@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterDifficultyModal,A@OpenPanel:CharacterDifficultyModal>FrontEndNavigation:ToGame}
# run_once 的标准输出被调用方 $(...) 当成摘要路径收走,失败原因一律打 stderr,否则 accept 里只见退出码、不见红因
# 步长 33.3 ms(30 帧/秒)与产品 60 帧/秒不同构,但逐拍逻辑与每拍出图帧数无关:实测同一回放 DM_DETCLOCK=16666667
# 下 231 拍摘要与本基线(33333333 录)逐拍全同;A 道 host_savecmp 不设 DETCLOCK、按墙钟出图也与真值逐拍一致。所以逻辑闸门不改步长
# The caller captures run_once's stdout via $(...) as the digest path, so all failure reasons go to stderr; otherwise accept shows only the exit code and not the cause of the fail
# The 33.3 ms step (30 fps) is not isomorphic to the product's 60 fps, but per-tick logic is independent of the number of presented frames per tick: measured, the same replay with DM_DETCLOCK=16666667
# gives 231 tick digests identical tick by tick to this baseline (recorded at 33333333); track A host_savecmp does not set DETCLOCK, renders by wall clock, and also matches the ground truth tick by tick. So the logic gate check does not change the step
env DM_SAVE="$run/user/0" DM_GAME_SEED="$seed" DM_FIXED_TIME="$ft" DM_DETCLOCK=33333333 \
DM_KEYS="$K" DM_C2S_REPLAY="$TR/c2s.jsonl" DM_TICKS="$run/ticks.jsonl" DM_TICKS_N="$((N + 1))" \
DM_C2S_LOG="$run/c2s.out" DM_UIMSG=1 DM_PRESENT_HZ=60 DM_WATCH_STALL=15 DM_WATCH=90 \
timeout 100s "$HERE/../host/dmhost" "$OUT" main sdk >"$run/host.log" 2>&1
local rc=$?
[ "$rc" -eq 0 ] || { echo "LOGICSELF RED 宿主回放失败;局目录 $run" >&2; grep '【红】看门狗' "$run/host.log" | tail -1 >&2 || true; return 1; }
"$PY" - "$run/ticks.jsonl" "$run/summary.json" "$N" <<'PY'
import json, sys
src, dst, limit = sys.argv[1], sys.argv[2], int(sys.argv[3]); rows=[]
for line in open(src):
x=json.loads(line)
if x.get('tick', -1) <= limit:
rows.append({'tick':x['tick'], 'n':x['n'], 'h':x['h']})
json.dump(rows, open(dst, 'w'), ensure_ascii=False, separators=(',', ':'))
PY
echo "$run/summary.json"
}
compare() {
"$PY" - "$1" "$2" "$N" <<'PY'
import json, sys
a=json.load(open(sys.argv[1])); b=json.load(open(sys.argv[2])); n=int(sys.argv[3])
for i,(x,y) in enumerate(zip(a,b)):
if x != y:
print(f'LOGICSELF RED 逻辑与自身基线不一致,首个不同拍 {x.get("tick", i)}')
print('LOGICSELF 首个差异:' + json.dumps({'actual':x,'baseline':y}, ensure_ascii=False, separators=(',', ':')))
raise SystemExit(1)
if len(a) != len(b):
print(f'LOGICSELF RED 逻辑与自身基线不一致,首个不同拍 {a[len(b)].get("tick", len(b)) if len(a)>len(b) else b[len(a)].get("tick", len(a))}')
raise SystemExit(1)
if len(a) != n + 1:
print(f'LOGICSELF RED 射程不足:{len(a)} 条,期望 {n + 1} 条')
raise SystemExit(1)
print(f'LOGICSELF OK 拍数 {n} 射程 {len(a)}')
PY
}
if [ "${LOGICSELF_REBASE:-0}" = 1 ]; then
A=$(run_once a) || exit $?
B=$(run_once b) || exit $?
compare "$A" "$B" || exit $?
"$PY" - "$A" "$BASELINE" "$HERE" "$OUT" <<'PY'
import json, sys, subprocess, datetime, os
rows=json.load(open(sys.argv[1])); out={'commit':subprocess.check_output(['git','-C',sys.argv[3], 'rev-parse','HEAD'], text=True).strip(), 'artifact':os.path.basename(sys.argv[4]), 'created_at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'ticks':rows}
json.dump(out, open(sys.argv[2], 'w'), ensure_ascii=False, indent=2); print('LOGICSELF 基线已写入 ' + sys.argv[2])
PY
exit 0
fi
ACTUAL=$(run_once actual) || exit $?
"$PY" - "$BASELINE" "$RUNROOT/${STAMP}_baseline.json" <<'PY'
import json, sys
x=json.load(open(sys.argv[1])); rows=x['ticks'] if isinstance(x,dict) else x; json.dump(rows, open(sys.argv[2],'w'), ensure_ascii=False, separators=(',', ':'))
PY
compare "$ACTUAL" "$RUNROOT/${STAMP}_baseline.json"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
# 宿主日志红线判据(shotgate 与 accept ② 共用一份关键字表:截图 / 存档绿而宿主日志有错也要红)
# 用法:logred.sh <宿主日志> 打印「行数<TAB>首条」;退出码 0 = 无红线,1 = 有红线,2 = 日志不存在
# 关键字:【红】行、FATAL、看门狗、命令缓冲错误(MTLCommandBufferStatus Error/Fault、CommandBufferCallbackError、Discarded victim)、GPU hang/error/fault/recovery、管线失败
# 不单配 Fault:会命中 nnosGetDefaultUserExceptionStack…
# Host log a failure line-line criterion (shotgate and accept ② share one keyword table: green screenshots / saves with errors in the host log must still fail)
# Usage: logred.sh <host log> prints "<line count><TAB><first match>"; exit code 0 = no failure line, 1 = failure line found, 2 = log does not exist
# Keywords: 【红】(red) lines, FATAL, watchdog, command buffer errors (MTLCommandBufferStatus Error/Fault, CommandBufferCallbackError, Discarded victim), GPU hang/error/fault/recovery, pipeline failure
# Fault is not matched on its own: it would hit nnosGetDefaultUserExceptionStack...
LOGRED='【红】|FATAL|看门狗|MTLCommandBufferStatus(Error|Fault)|CommandBufferCallbackError|Discarded \(victim|GPU (hang|error|fault|recovery)|管线.*失败|[Pp]ipeline.*fail'
[ -f "$1" ] || { printf '0\t(日志不存在 %s)\n' "$1"; exit 2; }
n=$(grep -cE "$LOGRED" "$1"); n=${n:-0}
printf '%s\t%s\n' "$n" "$(grep -m1 -E "$LOGRED" "$1" | cut -c1-140)"
[ "$n" = 0 ]
+77
View File
@@ -0,0 +1,77 @@
# NSO → 内存映像(与 patch_nso.py 同一解法);验证工具共用。
# NSO → memory image (same decoding as patch_nso.py); shared by the verification tools.
import struct
import lz4.block
def load(path):
d = open(path, 'rb').read()
assert d[:4] == b'NSO0', path
flags = struct.unpack_from('<I', d, 0xc)[0]
segs = [struct.unpack_from('<III', d, 0x10 + i * 0x10) for i in range(3)]
bss = struct.unpack_from('<I', d, 0x3c)[0]
csz = struct.unpack_from('<III', d, 0x60)
img = bytearray(segs[2][1] + segs[2][2] + bss)
for i, (fo, mo, sz) in enumerate(segs):
raw = d[fo:fo + csz[i]]
if flags >> i & 1: raw = lz4.block.decompress(raw, uncompressed_size=sz)
img[mo:mo + sz] = raw
return bytes(img)
def header(out_dir, mod):
h = {}
for line in open(f'{out_dir}/{mod}.fixups.tsv'):
if not line.startswith('#'): break
k, v = line[1:].split(); h[k] = int(v, 0) # 0x 开头为偏移,十进制为槽号 | A 0x prefix means an offset, decimal means a slot number
return h
def mod0(img):
m0 = struct.unpack_from('<I', img, 4)[0]
assert img[m0:m0 + 4] == b'MOD0'
return m0
def func_starts(img, text_end):
"""eh_frame_hdr 里的函数起点(与 patch_nso.py 同法)。 | Function start addresses from eh_frame_hdr (same method as patch_nso.py)."""
m0 = mod0(img)
ehs = m0 + struct.unpack_from('<i', img, m0 + 16)[0]
def rd(o, enc):
fmt, app = enc & 0xF, enc & 0x70
v, sz = {0x3: (struct.unpack_from('<I', img, o)[0], 4), 0xB: (struct.unpack_from('<i', img, o)[0], 4),
0x4: (struct.unpack_from('<Q', img, o)[0], 8)}[fmt]
if app == 0x10: v += o
if app == 0x30: v += ehs
return v, sz
_, penc, cenc, tenc = img[ehs:ehs + 4]
o = ehs + 4
_, s = rd(o, penc); o += s
nfde, s = rd(o, cenc); o += s
starts = set()
for _ in range(nfde):
a, s = rd(o, tenc); o += s
_, s = rd(o, tenc); o += s
starts.add(a)
return sorted(x for x in starts if x < text_end)
def relocs(img):
"""[(偏移, 类型, 符号名或 None, 符号值或 None, addend)]:RELA + JMPREL 全部条目。符号值 None = 未定义(导入)。 | [(offset, type, symbol name or None, symbol value or None, addend)]: all RELA + JMPREL entries. Symbol value None = undefined (import)."""
m0 = mod0(img)
dyn = m0 + struct.unpack_from('<i', img, m0 + 4)[0]
d = {}
o = dyn
while True:
tag, val = struct.unpack_from('<qQ', img, o); o += 16
if tag == 0: break
d[tag] = val
def cstr(p):
e = img.index(b'\0', p); return img[p:e].decode('latin1')
out = []
for tab, sz in ((d.get(7), d.get(8, 0)), (d.get(23), d.get(2, 0))):
if not tab: continue
for i in range(sz // 24):
off, info, add = struct.unpack_from('<QQq', img, tab + 24 * i)
typ, si = info & 0xFFFFFFFF, info >> 32
name = val = None
if si:
nm, _, _, shn, sv, _ = struct.unpack_from('<IBBHQQ', img, d[6] + 24 * si)
name = cstr(d[5] + nm); val = sv if shn else None
out.append((off, typ, name, val, add))
return out
+59
View File
@@ -0,0 +1,59 @@
#!/bin/bash
# 局内切运行模式(真机过热切掌机即崩:参数门跳板越过原指令,只有收到通知 30/31 才走到):产品节奏回放 cvd5 营地进局,
# DM_OE_SCRIPT 在进局(读取画面首次撤下)后第 AT 秒把运行模式 1 → 0(主机 → 掌机,等同前端过热降级),再跑到 DUR 秒由 timeout 收。
# 用法:opmode.sh [产物目录=out/<当前代号>-keypage] [AT=3] [DUR=32]
# 判据(全满足才绿):切换前已进局(ToGame 之后读取画面撤下);切换后游戏取走通知 30 与 31;进程活到 timeout(rc 124)、无 CRASH;
# 切换后至少再出 300 帧(宿主 [slowframe] 分母行);宿主日志无红线(logred.sh)。反例:r24-keypage 在切换瞬间 SIGSEGV(pc main+0xe10de8)
# In-game operation mode switch (a real device overheating and switching to handheld crashed at once: the parameter-gate trampoline skipped an original instruction, reached only when notification 30/31 arrives): replay cvd5 at product pacing, entering the game in camp,
# DM_OE_SCRIPT switches the operation mode 1 → 0 (docked → handheld, equivalent to the front end's overheat downgrade) at second AT after game entry (the loading screen first dismissed), then runs to second DUR and is reaped by timeout.
# Usage: opmode.sh [build output dir=out/<current codename>-keypage] [AT=3] [DUR=32]
# Criteria (green only if all hold): already in the game before the switch (loading screen dismissed after ToGame); after the switch the game fetches notifications 30 and 31; the process lives until timeout (rc 124) with no CRASH;
# at least 300 more frames are rendered after the switch (host [slowframe] denominator line); no failure line in the host log (logred.sh). Counterexample: r24-keypage took a SIGSEGV at the moment of the switch (pc main+0xe10de8)
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
OUT=${1:-$(bash "$(dirname "$0")/../tools/product.sh" path keypage)}; AT=${2:-3}; DUR=${3:-32}
TR=${TRUTH_RUN:-${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/cvd5}
ROOT=${DM_OPMODE_RUNROOT:-${DM_ROOT:-$HOME/dm-work}/run/verify/dm/opmode}; mkdir -p "$ROOT"
T=$(mktemp -d "$ROOT/$(date +%m%d_%H%M%S)_$$.XXXX")
cp -R "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001/0" "$T/user0" && chmod -R u+w "$T/user0"
make -s -C "$HERE/../host" > "$T/build.log" 2>&1 || { echo "OPMODE RED 宿主构建失败($T/build.log)"; exit 1; }
(cd "$HERE/../host" && timeout "$DUR" env DM_SAVE="$T/user0" DM_GAME_SEED=305419896 DM_FIXED_TIME=1790000000 \
"DM_KEYS=A@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterDifficultyModal,A@OpenPanel:CharacterDifficultyModal>FrontEndNavigation:ToGame" \
DM_C2S_REPLAY="$TR/c2s.jsonl" DM_PRESENT_HZ=60 DM_PRESENT_INTERVAL=display DM_UIMSG=1 DM_SLOWFRAME=1 "DM_OE_SCRIPT=opmode=0@ingame+$AT" DM_GAME_RES=1952x900 \
./dmhost "$OUT" main sdk > "$T/host.log" 2>&1); rc=$?
echo "局目录 $T"
python3 - "$T/host.log" "$rc" <<'PY'
import sys, re
log, rc = sys.argv[1], int(sys.argv[2])
L = open(log, errors='replace').read().splitlines()
def first(pat, start=0):
for i in range(start, len(L)):
if re.search(pat, L[i]): return i
return None
tg = first(r'FrontEndNavigation ToGame')
ul = first(r'UnloadPanel LoadScreenPanel', tg + 1) if tg is not None else None
dm = first(r'oe 运行模式 1 → 0')
n30 = first(r'oe 通知被游戏取走:30', dm or 0) if dm is not None else None
n31 = first(r'oe 通知被游戏取走:31', dm or 0) if dm is not None else None
crash = first(r'CRASH sig=')
den = [(i, int(m.group(1))) for i, l in enumerate(L) for m in [re.search(r'\[slowframe\]\t#\t至帧 \d+\tjudged=(\d+)', l)] if m]
before = max((j for i, j in den if dm is not None and i < dm), default=0)
after = max((j for i, j in den), default=0) - before
ok = []
ok.append(('切换前已进局', ul is not None and dm is not None and ul < dm))
ok.append(('切换后取走通知 30 / 31', n30 is not None and n31 is not None))
ok.append(('进程活到 timeout、无 CRASH', rc == 124 and crash is None))
ok.append(('切换后再出 ≥ 300 帧', dm is not None and after >= 300))
# 切换后游戏设的窗口尺寸须是宿主给的掌机档(1952x900 的 720/900 同比 = 1564x720)。用非原版宽度跑才看得出:通知处理把宽度 & 0x740
# (原版 1280|1600 推出的掩码)时 1564 → 1536(r26 及以前;r27 剪口改为取低 32 位)。原版宽度下这个缺陷不显形
wc = [m.group(1) for i, l in enumerate(L) if dm is not None and i > dm for m in [re.search(r'WindowCrop 0,0 (\d+x\d+)', l)] if m]
ok.append((f'切换后窗口尺寸 = 1564x720(实得 {wc[-1] if wc else "无"})', bool(wc) and wc[-1] == '1564x720'))
for k, v in ok: print(f"OPMODE {'✓' if v else '✗'} {k}")
if crash is not None: print('OPMODE 崩溃行:' + L[crash][:160])
print(f"OPMODE {'OK' if all(v for _, v in ok) else 'RED'} 切换后帧 {after},rc {rc}")
sys.exit(0 if all(v for _, v in ok) else 1)
PY
prc=$?
r=$("$HERE/logred.sh" "$T/host.log"); lrc=$?
echo "OPMODE 宿主日志红线 $(echo "$r" | cut -f1) 行"
[ $prc = 0 ] && [ $lrc = 0 ]
+161
View File
@@ -0,0 +1,161 @@
# Ryujinx GDB stub 最小客户端(读写内存、读寄存器、软件断点、继续 / 冻结)。
# 协议细节来自实测:stub 一次只服务一个客户端;
# 0x03 冻结全部客体线程、回停止包;c 先回 OK,命中断点时再异步来停止包。
# Minimal client for the Ryujinx GDB stub (read/write memory, read registers, software breakpoints, continue / freeze).
# Protocol details come from measurement: the stub serves only one client at a time;
# 0x03 freezes all guest threads and replies with a stop packet; c replies OK first, then a stop packet arrives asynchronously when a breakpoint is hit.
import socket, re
class Gdb:
def __init__(self, host='127.0.0.1', port=55571, timeout=30):
self.sock = socket.create_connection((host, port), timeout=timeout)
self.sock.settimeout(timeout)
self.buf = b''
self.pending = []
def close(self):
try: self.sock.close()
except OSError: pass
def _send(self, payload):
self.sock.sendall(b'$' + payload + b'#' + b'%02x' % (sum(payload) & 0xFF))
def _recv_packet(self):
while True:
while b'#' not in self.buf or len(self.buf.split(b'#', 1)[1]) < 2:
chunk = self.sock.recv(1 << 16)
if not chunk: raise IOError('gdb stub 断开了连接')
self.buf += chunk
if self.buf[:1] in (b'+', b'-'): self.buf = self.buf[1:]; continue
if not self.buf.startswith(b'$'):
i = self.buf.find(b'$')
if i < 0: self.buf = b''; continue
self.buf = self.buf[i:]
body, rest = self.buf[1:].split(b'#', 1)
self.buf = rest[2:]
self.sock.sendall(b'+')
return body
def cmd(self, payload):
self._send(payload)
expect_stop = payload[:1] in (b'?', b's', b'c') or payload.startswith(b'vCont')
while True:
body = self._recv_packet()
if body.startswith(b'O') and len(body) > 1 and not body.startswith(b'OK'): continue # 控制台输出包 | Console output packet
if not expect_stop and body[:1] in (b'T', b'S') and b'thread:' in body:
self._stash(body); continue # 别的线程撞断点的异步停止包:暂存给 wait_stop | Asynchronous stop packet from another thread hitting a breakpoint: stash it for wait_stop
return body
def monitor(self, text):
r = self.cmd(b'qRcmd,' + text.encode().hex().encode())
if r in (b'OK', b''): return ''
try: return bytes.fromhex(r.decode()).decode('utf-8', 'replace')
except ValueError: return r.decode('utf-8', 'replace')
def read(self, addr, n):
r = self.cmd(b'm%x,%x' % (addr, n))
if r.startswith(b'E'): raise IOError(f'读 {addr:#x}+{n:#x} 失败:{r.decode()}')
return bytes.fromhex(r.decode())
def write(self, addr, data):
return self.cmd(b'M%x,%x:%s' % (addr, len(data), data.hex().encode())) == b'OK'
def reg(self, n):
"""读通用寄存器 xN(GDB aarch64 编号:0–30 = x0–x30,31 = sp,32 = pc)。 | Read general-purpose register xN (GDB aarch64 numbering: 0–30 = x0–x30, 31 = sp, 32 = pc)."""
r = self.cmd(b'p%x' % n)
try: return int.from_bytes(bytes.fromhex(r.decode()), 'little')
except ValueError: raise IOError(f'读寄存器 {n} 回包不是十六进制:{r[:40]!r}')
def set_reg(self, n, v):
return self.cmd(b'P%x=%s' % (n, (v & 0xFFFFFFFFFFFFFFFF).to_bytes(8, 'little').hex().encode())) == b'OK'
def set_watch(self, addr, n=8):
"""写入断点(Z2);Ryujinx 在 macOS hypervisor 下由 HvDebugState 实现。 | Write breakpoint (Z2); under the macOS hypervisor Ryujinx implements it with HvDebugState."""
return self.cmd(b'Z2,%x,%x' % (addr, n)) == b'OK'
def clear_watch(self, addr, n=8): return self.cmd(b'z2,%x,%x' % (addr, n)) == b'OK'
def set_bp(self, addr): return self.cmd(b'Z0,%x,4' % addr) == b'OK'
def clear_bp(self, addr): return self.cmd(b'z0,%x,4' % addr) == b'OK'
def interrupt(self):
self.sock.sendall(b'\x03')
while True:
b = self._recv_packet()
if b[:1] in (b'T', b'S'): return b
def cont(self):
"""继续运行;读到 c 的即时回包 OK 为止(Ryujinx 先回 OK,多线程时别的线程的停止包可能抢在 OK 前到:暂存给 wait_stop)。 | Continue execution; read until the immediate OK reply to c (Ryujinx replies OK first; with multiple threads, another thread's stop packet may arrive before the OK: stash it for wait_stop)."""
self._send(b'c')
while True:
b = self._recv_packet()
if b[:1] in (b'T', b'S') and b'thread:' in b: self._stash(b); continue
return b
@staticmethod
def _tid(stop):
import re as _re
m = _re.search(rb'thread:([0-9a-f]+);', stop or b'')
return m.group(1) if m else None
def _stash(self, b):
"""暂存别的线程的停止包,按线程去重:线程停在断点上、还没被处理,它每次随全体继续都会在同一断点再停一次
(定根:游玩段拍号断档 / 命令包重复记录都是这个),同一线程只留第一条。
Stash stop packets from other threads, deduplicated by thread: a thread that is stopped at a breakpoint and not yet handled stops again at the same breakpoint every time everything is continued
(root cause found: the tick-number gaps in the gameplay segment and the duplicated command-packet records were both this); keep only the first one per thread."""
t = self._tid(b)
if t is None or all(self._tid(p) != t for p in self.pending): self.pending.append(b)
def select(self, stop):
"""把寄存器读写的目标线程(Hg)切到该停止包的线程。Ryujinx 每收到一次断点就把 Hg 设成最新撞断点的线程,
先到的停止包若不切线程,读到的是后到那个线程的寄存器。
Switch the target thread for register reads/writes (Hg) to the thread of this stop packet. Every time Ryujinx receives a breakpoint it sets Hg to the thread that most recently hit a breakpoint;
if the thread is not switched for a stop packet that arrived earlier, what gets read are the registers of the thread that arrived later."""
t = self._tid(stop)
if t: self.cmd(b'Hg' + t)
def wait_stop(self, timeout=None, select=True):
if self.pending:
b = self.pending.pop(0)
else:
old = self.sock.gettimeout()
if timeout is not None: self.sock.settimeout(timeout)
try:
while True:
b = self._recv_packet()
if b[:1] in (b'T', b'S'): break
finally: self.sock.settimeout(old)
if select: self.select(b)
return b
def _wait_raw(self, timeout):
old = self.sock.gettimeout(); self.sock.settimeout(timeout)
try:
while True:
b = self._recv_packet()
if b[:1] in (b'T', b'S'): return b
finally: self.sock.settimeout(old)
def step_over(self, addr, stop_packet):
"""越过函数入口断点(不用单步:hypervisor 模式下 Ryujinx 的单步会超时,实测 E01 + "Failed to step")。
入口第一条须不是跳转(两处入口都是 sub sp):撤入口断点 → 入口+4 下临时断点 → 继续 → 停在 +4 → 撤临时、重下入口。
别的线程在此期间的停止包暂存(按线程去重)给 wait_stop。返回 True = 本线程停在 +4;False = 200 次内没等到。
Step over a function-entry breakpoint (without single-stepping: in hypervisor mode Ryujinx's single step times out; measured: E01 + "Failed to step").
The first instruction at the entry must not be a branch (both entries are sub sp): remove the entry breakpoint → set a temporary breakpoint at entry+4 → continue → stop at +4 → remove the temporary one and re-set the entry one.
Stop packets from other threads during this time are stashed (deduplicated by thread) for wait_stop. Returns True = this thread stopped at +4; False = not seen within 200 tries."""
tid = self._tid(stop_packet)
self.clear_bp(addr); self.set_bp(addr + 4); self.cont()
same = False
for _ in range(200): # 别的线程先停:暂存(按线程去重),再继续,直到本线程停在 +4 | Another thread stopped first: stash it (deduplicated by thread) and continue, until this thread stops at +4
st = self._wait_raw(10)
if tid is not None and self._tid(st) == tid:
self.select(st)
if self.reg(32) == addr + 4: same = True; break
self.cont(); continue # 本线程的陈旧停止包(越过前那次继续里在原断点又停了一次):丢掉,再继续 | A stale stop packet for this thread (it stopped once more at the original breakpoint during the continue before the step-over): discard it and continue again
self._stash(st); self.cont()
self.clear_bp(addr + 4); self.set_bp(addr)
return same
def modules(self):
"""monitor get info 的模块表 → {名字: (起, 止)}。 | Module table from monitor get info → {name: (start, end)}."""
info = self.monitor('get info')
return {n: (int(a, 16), int(b, 16)) for a, b, n in re.findall(r'0x([0-9a-fA-F]+)\s*-\s*0x([0-9a-fA-F]+)\s+(\S+)', info)}, info
+129
View File
@@ -0,0 +1,129 @@
# Switch 版游戏状态 oracle 提取器(真值侧:Ryujinx GDB)。口径对齐 PC M0 插件 v7(src/tools/m0/oracle_plugin.c):
# 每个服务端拍开始前(拍入口 Game.nss+0x5d3bc0,x0 = pGame;= PC 0x1402c8860,rcx = pGame)取一次:
# 5 类单位表 pGame+{0x2230,0x2630,0x2a30,0x3230,0x2e30},每类 128 桶、桶内链 next=+0x158;
# 单位 type/cls/id/mode/act(u8 +0x18)/坐标(玩家/怪/飞弹 path+0..+6 含小数)/种子 +0x28/+0x2c;
# statlist(玩家/怪/物品)unit+0x88 → +0x30 数组、+0x38 项数;物品 ItemData(+0x10) 品质/种子/初始种子/flags;
# 全局种子 pGame+0x1a8/+0x1ac。按(类型, id)排序,各类 FNV-1a 64,输出与插件同格式的 JSONL。
# 偏移出自 PC v7;Switch 94012 静态证据:拍入口结构逐项同、单位表 5 个偏移各 ~260 处立即数、LCG 附近 +0x28 最多。活体复核见 --check。
# 用法:swtick.py [--port 55571] [--ticks N] [--out 文件] [--full]
# Game-state oracle extractor for the Switch version (ground-truth side: Ryujinx GDB). Conventions aligned with the PC M0 plugin v7 (src/tools/m0/oracle_plugin.c):
# sampled once before each server tick begins (tick entry Game.nss+0x5d3bc0, x0 = pGame; = PC 0x1402c8860, rcx = pGame):
# 5 unit-class tables pGame+{0x2230,0x2630,0x2a30,0x3230,0x2e30}, 128 buckets per class, in-bucket chain next=+0x158;
# unit type/cls/id/mode/act(u8 +0x18)/coordinates (player/monster/missile path+0..+6 including the fraction)/seeds +0x28/+0x2c;
# statlist (player/monster/item) unit+0x88 → array at +0x30, entry count at +0x38; item ItemData(+0x10) quality/seed/initial seed/flags;
# global seeds pGame+0x1a8/+0x1ac. Sorted by (type, id), FNV-1a 64 per class, output as JSONL in the same format as the plugin.
# Offsets come from PC v7; Switch 94012 static evidence: the tick entry structure matches item by item, each of the 5 unit-table offsets appears as an immediate ~260 times, and +0x28 is the most frequent near the LCG. For the live re-check see --check.
# Usage: swtick.py [--port 55571] [--ticks N] [--out file] [--full]
import sys, os, struct, json, argparse, time
sys.path.insert(0, os.path.dirname(__file__))
from swgdb import Gdb
TICK_ENTRY = 0x5d3bc0
TBASE = (0x2230, 0x2630, 0x2a30, 0x3230, 0x2e30)
NB, NEXT, MAXS = 128, 0x158, 96
def fnv(h, b):
for c in b: h = ((h ^ c) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF
return h
class Reader:
def __init__(self, g): self.g = g; self.n = 0
def rd(self, a, n):
if not a: return None
self.n += 1
try: return self.g.read(a, n)
except IOError: return None
def units(r, game):
tab = r.rd(game + TBASE[0], 0x1400) # 0x2230..0x3630 连续:5 类 × 128 桶 × 8 字节 | 0x2230..0x3630 contiguous: 5 classes × 128 buckets × 8 bytes
out = []; bad = 0
for t, base in enumerate(TBASE):
for b in range(NB):
u = struct.unpack_from('<Q', tab, base - TBASE[0] + 8 * b)[0]
k = 0
while u and k < 4096:
hd = r.rd(u, NEXT + 8)
if hd is None: bad += 1; break
ty, cls, uid, mode = struct.unpack_from('<IIII', hd, 0)
x = {'type': ty, 'cls': cls, 'id': uid, 'mode': mode, 'act': hd[0x18], 'seed': struct.unpack_from('<I', hd, 0x30)[0],
'rlo': struct.unpack_from('<I', hd, 0x28)[0], 'rhi': struct.unpack_from('<I', hd, 0x2c)[0],
'x': 0, 'y': 0, 'xf': 0, 'yf': 0, 'it': None, 'st': [], 'ptr': u, 'path': struct.unpack_from('<Q', hd, 0x38)[0]}
if t == 4:
d = struct.unpack_from('<Q', hd, 0x10)[0]; idt = r.rd(d, 0x1c)
if idt: x['it'] = struct.unpack_from('<IIIII', idt, 0)[0:3] + (struct.unpack_from('<I', idt, 0x18)[0], struct.unpack_from('<I', idt, 0x10)[0])
if t in (0, 1, 3):
p = r.rd(struct.unpack_from('<Q', hd, 0x38)[0], 8)
if p: x['xf'], x['x'], x['yf'], x['y'] = struct.unpack('<HHHH', p)
sl = struct.unpack_from('<Q', hd, 0x88)[0]
slh = r.rd(sl, 0x40)
if slh:
sb, sc = struct.unpack_from('<Q', slh, 0x30)[0], struct.unpack_from('<I', slh, 0x38)[0]
arr = r.rd(sb, 8 * min(sc, MAXS)) if sb and sc else None
if arr: x['st'] = [struct.unpack_from('<II', arr, 8 * j) for j in range(len(arr) // 8)]
if ty != t: bad += 1
out.append(x); k += 1
u = struct.unpack_from('<Q', hd, NEXT)[0]
return out, bad
def tick_line(r, game):
tick = struct.unpack('<I', r.rd(game + 0x170, 4))[0]
us, bad = units(r, game)
us.sort(key=lambda u: (u['type'], u['id']))
h = [0xcbf29ce484222325] * 6
gs = r.rd(game + 0x1a8, 8) or bytes(8); h[5] = fnv(h[5], gs)
cnt = [0] * 5
for u in us:
t = u['type']
if t >= 5: continue
cnt[t] += 1
hh = fnv(h[t], struct.pack('<9I', t, u['cls'], u['id'], u['mode'], u['act'], u['x'], u['y'], u['xf'], u['yf']))
hh = fnv(hh, struct.pack('<II', u['rlo'], u['rhi']))
if t == 4: hh = fnv(hh, struct.pack('<5I', *(u['it'] or (0,) * 5)))
if t <= 1 or t == 4:
hh = fnv(hh, struct.pack('<I', len(u['st'])))
for a, b in u['st']: hh = fnv(hh, struct.pack('<II', a, b))
h[t] = hh
return {'tick': tick, 'n': cnt, 'h': ['%016x' % x for x in h], 'bad': bad, 'reads': r.n}, us
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('--port', type=int, default=55571); ap.add_argument('--ticks', type=int, default=25)
ap.add_argument('--out', default='-'); ap.add_argument('--full', action='store_true')
A = ap.parse_args()
g = Gdb(port=A.port)
mods, info = g.modules()
game_mod = next((v for k, v in mods.items() if k.startswith('Game')), None)
if not game_mod: sys.exit('模块表里没有 Game.nss:\n' + info)
bp = game_mod[0] + TICK_ENTRY
g.interrupt()
if not g.set_bp(bp): sys.exit(f'下断失败 {bp:#x}')
f = sys.stdout if A.out == '-' else open(A.out, 'w')
t0 = time.time()
try:
last = None; dup = 0; gaps = []
while True:
g.cont(); stop = g.wait_stop(timeout=60)
k = 0
while g.reg(32) != bp: # 不在拍入口的停止:继续等真命中 | A stop that is not at the tick entry: keep waiting for a real hit
k += 1
if k > 50: sys.exit(f'连续 50 次停在非拍入口 {g.reg(32):#x}')
g.cont(); stop = g.wait_stop(timeout=60)
game = g.reg(0)
tick = int.from_bytes(g.read(game + 0x170, 4), 'little')
if tick == last: # 同一次命中被重复报告(Ryujinx):不重复取 | The same hit reported twice (Ryujinx): do not sample it again
dup += 1; g.step_over(bp, stop); continue
if last is not None and tick != last + 1: gaps.append((last, tick))
r = Reader(g)
line, us = tick_line(r, game)
line['game'] = hex(game); line['dt'] = round(time.time() - t0, 3)
f.write(json.dumps(line) + '\n'); f.flush()
if A.full:
for u in us: f.write(json.dumps({'t': line['tick'], 'u': u}) + '\n')
last = tick
g.step_over(bp, stop) # 越过入口断点,否则继续后又停在同一拍 | Step over the entry breakpoint, otherwise after continuing it stops at the same tick again
A.ticks -= 1
if A.ticks <= 0: break
print(json.dumps({'重复报告': dup, '断档': gaps}), file=sys.stderr)
if gaps: sys.exit(f'拍号不连续:{gaps[:5]}')
finally:
g.clear_bp(bp); g.cont(); g.close()
+123
View File
@@ -0,0 +1,123 @@
{
"schema": "overlay-accept-v1",
"status": "等待独立布局规格与首次原生截图;不是已通过的UI验收",
"producer": "DmTouchOverlay.controlMetadata + DM_TOUCH_SHOT + DM_SCREEN_SHOT",
"scope": "只准备合成层控件验收;原17页NVN帧、逐拍6格与存档不改豁免、不加遮罩",
"metadata_required": [
"coordinate_space",
"view_size_pt",
"scale",
"pixel_size",
"navigation",
"controls"
],
"control_required": [
"id",
"rect_pt",
"npad_button",
"visible"
],
"known_control_ids": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map"
],
"producer_additions_requested": [
"摇杆外圈/拇指/方向弧实际绘制rect与活动状态",
"截图状态与同一份metadata关联",
"截图来源:原生预览或真机,不混报"
],
"independent_expectation": {
"source": "单独冻结的布局规格,不能使用实际导出rect自证位置正确",
"bottom_order": [
"血球",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"蓝球"
],
"skill_cluster": [
"main",
"skill1",
"skill2",
"skill3",
"skill4"
],
"state_visible_controls": "以明确状态下的独立规格为准,预留portal/腰带不自动视为已实现",
"protected_hud_regions": "由布局规格给出;不凭实现输出推定,不全局遮掉游戏差异"
},
"levels": [
{
"id": "overlay_pixels",
"checks": [
"PNG像素尺寸与point_size×scale一致",
"landscape方向",
"可见控件alpha像素存在",
"隐藏控件未漏画",
"控件位置/底栏顺序与独立规格一致",
"摇杆与控件无越界",
"受保护HUD区域无遮挡"
],
"proof": "透明overlay PNG+同快照metadata+独立布局规格;只证明此层,未证明真机合成"
},
{
"id": "actual_composition",
"checks": [
"真实整窗图中控件确实存在",
"方向/全屏/不拉伸",
"未遮关键HUD"
],
"proof": "实际原生/真机整窗PNG;自动像素合成对拍须同一帧game/overlay/composite证据,否则只报告未核,不拿不同动画帧硬比或用离线黑底冒充"
},
{
"id": "input_equivalence",
"checks": [
"同规则域/原像/起始档/种子",
"触屏与手柄的原版UI消息序列一致",
"完整真值拍区间的6格/5类数量/bad完全一致",
"保存文件逐字节一致"
],
"proof": "真实触摸流程和手柄流程的输入/日志/保存副本;纯C单测不是终点"
}
],
"negative_controls": [
"漏掉一个可见控件",
"只在overlay PNG存在但真实window没画出",
"错误PNG尺寸/scale/方向",
"控件错位/底栏错序",
"隐藏控件仍画出",
"摇杆或控件越界",
"遮挡受保护HUD",
"旧metadata与新截图串用",
"漏拍/重复拍/bad读失败/单位数漂移",
"新规则偷用旧真值或遮位置/精力/全局哈希"
],
"separate_unverified": [
"portal_binding_verified",
"game_hud_relayout_verified",
"强制跑步/无限精力新玩法规则",
"持续施放与交换手势没有冲突"
],
"ruleset_boundary": "新跑步/无限精力用明确新版本参照与独立预期;旧war13原件保持冻结且完整对拍",
"current_evidence": {
"original_truth_run": "~/dm-work/run/verify/ryu/war_summon13_1002_takeover",
"truth_ticks": 2978,
"truth_first": 36,
"truth_last": 3013,
"host_replay_first": "~/dm-work/run/platform/hsc_war_summon13_1002_takeover_1002_071540_86459",
"host_replay_first_result": "完整2978拍6格/数量/bad一致,但唯一缺Warlock.ctl,整体退出1,KEEP",
"host_replay_bound_pending": "平台在原始缺CTL局之外,按真实客户端绑定后另跑完整回放;不复制/豁免CTL"
}
}
+58
View File
@@ -0,0 +1,58 @@
#!/bin/bash
# 改写等价常驻回归:结构核对(structck)+ Unicorn 逐处等价(equiv)+ 宿主门功能(gatefn),三模块一条命令,秒级。
# 用法:dm/verify/regress.sh [改写产物目录] [模块…]
# 默认目录 = product.sh path keypage,默认模块 main sdk subsdk0
# --struct-only:只跑 structck + gatefn(不跑 equiv),给出包产物用
# --fresh:先用本工作树的 patch_nso.py 重出到 run/verify/dm/fresh/,验它,并与给定目录逐文件比对(查共用产物是否过期)
# 环境:DM_PY(默认 build/cache/dm/venv/bin/python)、DM_NSO_DIR、SEED、JOBS、LLVM_BIN
# 末尾汇总表:每模块 结构 / 等价 两行带分母与射程;任何一项 FAIL 退出码 1。
# Standing rewrite-equivalence regression: structural check (structck) + per-site Unicorn equivalence (equiv) + host gate function (gatefn), three modules in one command, in seconds.
# Usage: dm/verify/regress.sh [rewrite build output dir] [module...]
# default dir = product.sh path keypage, default modules main sdk subsdk0
# --struct-only: run only structck + gatefn (no equiv), for release build outputs
# --fresh: first regenerate with this worktree's patch_nso.py into run/verify/dm/fresh/, verify it, and compare it file by file with the given dir (checks whether the shared build output is stale)
# Environment: DM_PY (default build/cache/dm/venv/bin/python), DM_NSO_DIR, SEED, JOBS, LLVM_BIN
# Final summary table: per module, two rows (structure / equivalence) with denominator and coverage; any FAIL gives exit code 1.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
PY=${DM_PY:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python}
NSO_DIR=${DM_NSO_DIR:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/ExeFS}
RUN=${DM_ROOT:-$HOME/dm-work}/run/verify/dm
FRESH=0; STRUCT_ONLY=0
[ "${1:-}" = --fresh ] && { FRESH=1; shift; }
[ "${1:-}" = --struct-only ] && { STRUCT_ONLY=1; shift; } # 只做结构核对 + 门功能(出包产物 touch 用:等价试验与 keypage 共用改写路径,不重复跑) | Structural check + gate function only (for the release build output touch: the equivalence trials share the rewrite path with keypage and are not rerun)
OUT=${1:-$(bash "$(dirname "$0")/../tools/product.sh" path keypage)}; [ $# -gt 0 ] && shift
MODS=${*:-main sdk subsdk0}
mkdir -p "$RUN"
TS=$(date +%m%d_%H%M%S)_$$
LOG=$RUN/regress_$TS.log
echo "# regress $TS out=$OUT mods=$MODS fresh=$FRESH struct_only=$STRUCT_ONLY seed=${SEED:-1} git=$(git -C "$HERE" rev-parse --short HEAD) $(git -C "$HERE" status --porcelain -- . ../tools | wc -l | tr -d ' ')处未提交" | tee "$LOG"
if [ $FRESH = 1 ]; then
F=$RUN/fresh; rm -rf "$F"; mkdir -p "$F"
for m in $MODS; do
"$PY" "$HERE/../tools/patch_nso.py" "$NSO_DIR/$m" "$F" "$m" >> "$LOG" 2>&1 || { echo "FAIL patch_nso $m" | tee -a "$LOG"; exit 1; }
for e in patched.bin fixups.tsv gates.tsv sites.tsv; do
if [ ! -e "$OUT/$m.$e" ]; then r=缺; elif cmp -s "$F/$m.$e" "$OUT/$m.$e"; then r=同; else r=不同; fi
echo "FRESH $m.$e 与 $OUT $r" | tee -a "$LOG"
done
done
OUT=$F
fi
rc=0
for m in $MODS; do
"$PY" "$HERE/structck.py" "$OUT" "$m" "$NSO_DIR/$m" >> "$LOG" 2>&1 || rc=1
[ $STRUCT_ONLY = 1 ] || "$PY" "$HERE/equiv.py" "$OUT" "$m" "$NSO_DIR/$m" --seed "${SEED:-1}" ${JOBS:+--jobs $JOBS} --tsv "$RUN/eq_${m}_$TS.tsv" >> "$LOG" 2>&1 || rc=1
done
# 门功能回归:用宿主现行 entry.S 现编测试台,逐个门执行 _dm_gate 核对回写契约(dm/verify/gatefn)
# Gate function regression: build a test bench on the spot from the host's current entry.S and execute _dm_gate gate by gate to check the write-back contract (dm/verify/gatefn)
GT=$RUN/gate_test_$TS
if cc -O1 -o "$GT" "$HERE/gatefn/gate_test.c" "$HERE/gatefn/gate_tramp.S" "$HERE/../host/entry.S" >> "$LOG" 2>&1; then
G=(); for m in $MODS; do [ -s "$OUT/$m.gates.tsv" ] && G+=("$OUT/$m.gates.tsv"); done
"$GT" "${G[@]}" >> "$LOG" 2>&1 || rc=1; rm -f "$GT"
else echo "FAIL 门功能测试台编译失败" >> "$LOG"; rc=1; fi
echo "---- 汇总(${LOG})"
grep -E '^(FRESH|STRUCT|EQUIV|GATEFN|FAIL|DIFF|NOEFF|MUTMISS)' "$LOG" | grep -v '^FRESH.* 同$'
[ $rc = 0 ] && echo "REGRESS OK $(basename "$OUT")" || echo "REGRESS FAIL $(basename "$OUT")"
exit $rc
+85
View File
@@ -0,0 +1,85 @@
#!/bin/bash
# 纯规则域宿主闸门:回放 V4 真值到指定拍号,逐拍六组状态对拍。
# 逐拍逻辑与每拍出图帧数无关(实测见 logicself.sh 注释),所以回放步长与产品 60 帧/秒不同不影响本闸门
# 用法:rulegate.sh [拍数=400] [产物=out/<当前代号>-rules]
# Pure rule-domain host gate check: replay the V4 ground truth up to the given tick number and compare six groups of state tick by tick.
# Per-tick logic is independent of the number of presented frames per tick (measurements in the logicself.sh comments), so a replay step different from the product's 60 fps does not affect this gate check
# Usage: rulegate.sh [ticks=400] [build output=out/<current codename>-rules]
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
X=${DM_ROOT:-$HOME/dm-work}
PY=${DM_PY:-$X/build/cache/dm/venv/bin/python3}
TR=${DM_RULE_TRUTH:-$X/run/verify/dm/v4_truth_bootstrap_1002/war13_v4}
N=${1:-400}
OUT_ARG=${2:-out/$(bash "$(dirname "$0")/../tools/product.sh" name rules)}
case "$N" in ''|*[!0-9]*) echo "RULEGATE RED 拍数非法:$N"; exit 2;; esac
case "$OUT_ARG" in /*) OUT=$OUT_ARG;; *) OUT=$X/build/cache/dm/$OUT_ARG;; esac
[ -d "$TR" ] || { echo "RULEGATE RED 真值目录不存在:$TR"; exit 2; }
[ -f "$TR/meta.json" ] && [ -f "$TR/c2s.jsonl" ] && [ -f "$TR/ticks.jsonl" ] || { echo "RULEGATE RED 真值文件不全"; exit 2; }
[ -f "$OUT/main.patched.bin" ] || { echo "RULEGATE RED 产物缺 main.patched.bin:$OUT"; exit 2; }
PATCH_SHA=$(shasum -a 256 "$HERE/../tools/patch_nso.py" | awk '{print $1}')
REC_SHA=$(sed -n '1s/^[[:space:]]*\([0-9a-fA-F]\{64\}\).*/\1/p' "$OUT/build_src.sha256" 2>/dev/null)
[ -n "$REC_SHA" ] && [ "$REC_SHA" = "$PATCH_SHA" ] || {
echo "RULEGATE RED 产物过期,先重出当前代号的 rules 产物(dm/PRODUCT)"
echo "重出命令:python3 $HERE/../tools/patch_nso.py <main.nso> $OUT main"
exit 1
}
ROOT=${DM_RULE_RUNROOT:-$X/run/verify/dm/rulegate}
mkdir -p "$ROOT" || exit 2
T=$ROOT/$(date +%Y%m%d_%H%M%S)_$$
mkdir -p "$T/user" || exit 2
START=$($PY - "$TR/meta.json" <<'PY'
import json, sys
m = json.load(open(sys.argv[1]))
save = m['save'][1] if isinstance(m['save'], list) else m['save']
print(save)
PY
) || { echo "RULEGATE RED 起档路径解析失败"; exit 2; }
[ -d "$START/0" ] || { echo "RULEGATE RED 起档缺 0/:$START"; exit 2; }
cp -R "$START/0" "$T/user/0" || { echo "RULEGATE RED 起档复制失败"; exit 2; }
chmod -R u+w "$T/user/0" || exit 2
cleanup_red() { echo "RULEGATE RED 拍数 $N 用时 $SECONDS 秒;局目录 $T"; exit 1; }
P=
trap 'if [ -n "${P:-}" ]; then kill "$P" 2>/dev/null || true; wait "$P" 2>/dev/null || true; fi' EXIT INT TERM
SECONDS=0
( cd "$HERE/../host" && timeout 4500s make -s ) >"$T/make.log" 2>&1 || { echo "RULEGATE RED 宿主编译失败;局目录 $T"; exit 1; }
K=${KEYS_FRONT:-X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame}
SEED=$($PY - "$TR/meta.json" <<'PY'
import json, sys
print(json.load(open(sys.argv[1]))['game_seed'])
PY
) || cleanup_red
FT=$($PY - "$TR/meta.json" <<'PY'
import json, sys
m = json.load(open(sys.argv[1]))
print(m.get('fix_time') if m.get('fix_time') is not None else m['wall_start'])
PY
) || cleanup_red
env DM_SAVE="$T/user/0" DM_GAME_SEED="$SEED" DM_FIXED_TIME="$FT" DM_KEYS="$K" \
DM_C2S_REPLAY="$TR/c2s.jsonl" DM_TICKS="$T/ticks.jsonl" DM_TICKS_N="$((N + 1))" \
DM_C2S_LOG="$T/c2s.out" DM_UIMSG=1 DM_PRESENT_HZ=60 DM_WATCH_STALL=15 DM_WATCH=4500 \
"$HERE/../host/dmhost" "$OUT" main sdk >"$T/host.log" 2>&1 &
P=$!
DEADLINE=$((SECONDS + 4530))
while kill -0 "$P" 2>/dev/null; do
[ "$SECONDS" -lt "$DEADLINE" ] || cleanup_red
sleep 1
done
wait "$P"; RC=$?
[ "$RC" -eq 0 ] || { grep '【红】看门狗' "$T/host.log" | tail -1; cleanup_red; }
"$PY" - "$TR/ticks.jsonl" "$T/truth.ticks.jsonl" "$N" <<'PY'
import json, sys
src, dst, limit = sys.argv[1], sys.argv[2], int(sys.argv[3])
with open(dst, 'w') as out:
for line in open(src):
x = json.loads(line)
if x['tick'] <= limit:
out.write(line)
PY
cmp_out=$($PY "$HERE/ryu/selfcmp.py" "$T/truth.ticks.jsonl" "$T/ticks.jsonl" 2>&1)
cmp_rc=$?
echo "$cmp_out" | tee "$T/selfcmp.log"
if [ "$cmp_rc" -ne 0 ]; then cleanup_red; fi
echo "RULEGATE OK 拍数 $N 用时 $SECONDS 秒"
rm -rf "$T"
trap - EXIT INT TERM
+71
View File
@@ -0,0 +1,71 @@
# 存档逐字节对拍:两份用户存档目录(各含 0/ 1/ ExtraData*)比 0/ 下全部文件。判据:校验和各自自洽、两处墙钟时间核来源、其余逐字节全同。
# 用法:savecmp.py <A 存档目录> <B 存档目录> [--a-meta=<A 局目录 meta.json>] [--b-meta=…] [--a-time=<秒>] [--b-time=<秒>]
# 退出码 0 = 一致;1 = 不一致;3 = 射程不足(一侧没有 .d2s)
# 墙钟字段不互比,改为「核来源」:给了 --x-meta(真值局目录 meta.json 的 wall_start / wall_end)⇒ 该侧时间须落在开跑—结束区间内;
# 给了 --x-time(宿主 DM_FIXED_TIME)⇒ 该侧时间须恰等于该值;两样都没给 ⇒ 该侧时间字段报「未核」并判红(不许静默放过)
# 不逐字节互比的字段(只这些,改动须经评审):
# .d2s 0x0c–0x0f 全文件校验和(任何字节变它都变;改核两边各自「校验和自洽」)
# .d2s 0x20–0x23(版本 0x69)最后游玩时间、<角色>.d2s.meta 的 last_modified_time(纳秒):系统时间输入。真值同起点同种子同 --fix-time 两局
# (cvd4 / cvd4b)只差这两处(差 32 秒 = 两局开跑间隔;--fix-time 只定住建局那一次 time())。两边值不同时按上面的「核来源」各自核
# Byte-by-byte save comparison: for two user save directories (each containing 0/ 1/ ExtraData*), compare all files under 0/. Criterion: each checksum self-consistent, the source of the two wall-clock times verified, everything else identical byte for byte.
# Usage: savecmp.py <save dir A> <save dir B> [--a-meta=<meta.json of run dir A>] [--b-meta=...] [--a-time=<seconds>] [--b-time=<seconds>]
# exit code 0 = match; 1 = mismatch; 3 = insufficient coverage (one side has no .d2s)
# wall-clock fields are not compared with each other but "source-verified": with --x-meta (wall_start / wall_end in the ground-truth run dir's meta.json) ⇒ that side's time must fall within the start-to-end interval;
# with --x-time (the host's DM_FIXED_TIME) ⇒ that side's time must equal that value exactly; with neither ⇒ that side's time field is reported as 「未核」(unverified) and fails (no silent pass)
# Fields not compared byte for byte (only these; changes require review):
# .d2s 0x0c–0x0f whole-file checksum (changes when any byte changes; instead check that each side's "checksum is self-consistent")
# .d2s 0x20–0x23 (version 0x69) last played time, and last_modified_time (nanoseconds) in <character>.d2s.meta: system time inputs. Two ground-truth runs with the same start, same seed, and same --fix-time
# (cvd4 / cvd4b) differ only in these two places (by 32 seconds = the interval between the two run starts; --fix-time pins only the single time() at game creation). When the two sides differ, each is checked by the "source verification" above
import re
import sys, os, struct
def files(d):
d = os.path.join(d, '0')
return {os.path.relpath(os.path.join(r, f), d) for r, _, fs in os.walk(d) for f in fs}
def d2s_sum(b):
"""D2 存档校验和:校验和字段置 0 后逐字节 sum = (sum << 1 | sum >> 31) + byte(32 位)。 | D2 save checksum: with the checksum field set to 0, per byte sum = (sum << 1 | sum >> 31) + byte (32-bit)."""
z = bytearray(b); z[0x0c:0x10] = b'\0\0\0\0'; s = 0
for c in z: s = (((s << 1) | (s >> 31)) + c) & 0xFFFFFFFF
return s
import json
A, B = sys.argv[1], sys.argv[2]
opt = dict(x.split('=', 1) for x in sys.argv[3:] if x.startswith('--'))
def tsrc(side):
if f'--{side}-time' in opt: v = int(opt[f'--{side}-time']); return (v, v, f'固定值 {v}')
if f'--{side}-meta' in opt: m = json.load(open(opt[f'--{side}-meta'])); return (m['wall_start'], m['wall_end'], f'墙钟区间 [{m["wall_start"]}, {m["wall_end"]}]')
return None
TS = {'A': tsrc('a'), 'B': tsrc('b')}
def check_time(lab, f, v):
t = TS[lab]
if t is None: print(f' {f} {lab} 时间 {v} 未核(缺 --{lab.lower()}-meta / --{lab.lower()}-time)'); return 1
if not t[0] <= v <= t[1]: print(f' {f} {lab} 时间 {v} 不在{t[2]}内'); return 1
return 0
fa, fb = files(A), files(B)
print(f'射程:A {len(fa)} 个文件,B {len(fb)} 个;.d2s A {sum(f.endswith(".d2s") for f in fa)} / B {sum(f.endswith(".d2s") for f in fb)}')
if not any(f.endswith('.d2s') for f in fa) or not any(f.endswith('.d2s') for f in fb): print('SAVECMP 射程不足'); sys.exit(3)
bad = 0
for f in sorted(fa ^ fb): print(f' 只在 {"A" if f in fa else "B"}:{f}'); bad += 1
for f in sorted(fa & fb):
a = open(os.path.join(A, '0', f), 'rb').read(); b = open(os.path.join(B, '0', f), 'rb').read()
if f.endswith('.d2s'):
for lab, x in (('A', a), ('B', b)):
if len(x) >= 16 and struct.unpack_from('<I', x, 0x0c)[0] != d2s_sum(x): print(f' {f} {lab} 校验和不自洽'); bad += 1
a2, b2 = bytearray(a), bytearray(b); a2[0x0c:0x10] = b2[0x0c:0x10] = b'\0\0\0\0'
if a[4] == 0x69 and b[4] == 0x69 and a[0x20:0x24] != b[0x20:0x24]: # 两边相同(本局没玩这个角色)不必核 | Identical on both sides (this character was not played in this run), no need to check
for lab, x in (('A', a), ('B', b)): bad += check_time(lab, f, struct.unpack_from('<I', x, 0x20)[0])
if a[4] == 0x69 and b[4] == 0x69: a2[0x20:0x24] = b2[0x20:0x24] = b'\0\0\0\0'
a, b = bytes(a2), bytes(b2)
if f.endswith('.d2s.meta'):
if a != b:
for lab, x in (('A', a), ('B', b)):
mt = re.search(rb'"last_modified_time":(\d+)', x)
if mt: bad += check_time(lab, f, int(mt.group(1)) // 10**9) # 纳秒 | Nanoseconds
a, b = (re.sub(rb'"last_modified_time":\d+', b'"last_modified_time":0', x) for x in (a, b))
if a != b:
bad += 1
offs = [i for i in range(min(len(a), len(b))) if a[i] != b[i]]
print(f' 不同:{f} 长 {len(a)}/{len(b)},差 {len(offs) + abs(len(a) - len(b))} 字节,首处 {hex(offs[0]) if offs else hex(min(len(a), len(b)))}'
+ (f'(A {a[offs[0]:offs[0] + 8].hex()} / B {b[offs[0]:offs[0] + 8].hex()})' if offs else ''))
print('SAVECMP 一致(校验和各自自洽、墙钟时间核过来源、其余逐字节全同)' if not bad else f'SAVECMP 不一致:{bad} 处'); sys.exit(1 if bad else 0)
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# 存档内容指纹:对一个用户存档目录(含 0/ 1/ ExtraData*)按 MANIFEST.sha256 同一格式(「sha 0000000000000001/相对路径」逐行、按路径排序)出清单,
# 打印清单本身的 sha256。与 data/switch/<存档>/MANIFEST.sha256 的 sha 可直接比(同内容 ⇒ 同值)。.lock 不计。
# 用法:savesha.sh <用户存档目录> → 打印 64 位十六进制
# Save content fingerprint: for a user save directory (containing 0/ 1/ ExtraData*), produce a manifest in the same format as MANIFEST.sha256 ("sha 0000000000000001/<relative path>" per line, sorted by path),
# and print the sha256 of the manifest itself. Directly comparable with the sha of data/switch/<save>/MANIFEST.sha256 (same content ⇒ same value). .lock is excluded.
# Usage: savesha.sh <user save dir> → prints 64 hex digits
set -eu
D=${1%/}
( cd "$D" && find . -type f ! -name .lock | sed 's|^\./||' | LC_ALL=C sort | while read -r f; do printf '%s 0000000000000001/%s\n' "$(shasum -a 256 "$f" | cut -c1-64)" "$f"; done ) | shasum -a 256 | cut -c1-64
+144
View File
@@ -0,0 +1,144 @@
# Screenshot Gate
中文:[screenshot_gate.zh-CN.md](screenshot_gate.zh-CN.md)
The screenshot gate compares the key screens drawn by the **host** (`dmhost` from `dm/host`, which executes the rewritten game program on a Mac) page by page with the **ground truth** (reference images captured by running the original game in a patched Ryujinx emulator), to judge whether whole blocks are missing, lighting is missing, or the structure is distorted.
Why compare against the ground truth: if you only compare the host's new image with the host's old image, it will report "identical" even when both are black.
The GPUs and shader chains on the two sides are both different, so pixel-for-pixel identity is not required; the criteria below are used instead.
## One command
```
dm/verify/shotgate.sh [build output dir] [page name…]
```
- The build output directory defaults to the current codename's `keypage` build output (`dm/tools/product.sh path keypage`); the page names default to everything under `shotgate_pages/`.
- It starts by running `make` on the host. Each page starts one host (`hostshot.sh`), which starts a game from a fresh copy of the standard save, follows the key sequence in the page spec to that screen, and takes a screenshot at the trigger point; `shotgate.py` then compares it with the ground-truth reference image. The pages are independent of each other and run in parallel.
- Each page prints one line `SHOTGATE <page> OK|RED …`, and the last line is `SHOTGATE_ALL OK|RED → <report path>`; exit code 0 = all green.
Reports and run artifacts:
- When anything is red, the whole set of run artifacts is kept in `$DM_ROOT/run/verify/dm/shotgate/<timestamp>_<worktree name>_<pid>…/`: `index.html` is the summary, each page has a `report.html` (ground-truth image / host image / difference heat map side by side, plus the criterion readings and the expected-elements table), and each page's full host log is `<page>_host.log`.
- When everything is green the run artifacts are deleted, leaving only a short summary `shotgate/green/<directory name>.html`.
- When a host screenshot fails (a crash or the watchdog), the run artifact directory gets an extra `KEEP` file, with a copy of the system's crash report attached.
- `shotgate_gc.sh` cleans up old run artifacts more than 3 days old at the end of every run; those with `KEEP` are not deleted, and for a directory you want to keep long term, put an empty file `PIN` in it.
| Environment variable | Effect |
|---|---|
| `SHOTGATE_JOBS` | How many pages run at once, default 6 |
| `SHOTGATE_KEEP_IMG=1` | Keep the whole set of run artifacts even when all green |
| `SHOTGATE_KEEP_DAYS` | Number of days old run artifacts are kept, default 3 |
| `DM_GATE_SAVE` | The save directory the host uses, default `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001` |
| `DM_HOST` | The host executable, default this worktree's `dm/host/dmhost` |
| `DM_PY` | The Python interpreter, default `$DM_ROOT/build/cache/dm/venv/bin/python` |
## Prerequisites
The repository contains only the page specs and the comparison program; the following you have to prepare yourself (for where the ground truth comes from see [README.md](README.md); the emulator driver scripts used to obtain it are not shipped with the repository, so this gate cannot be run with this repository alone):
- **Ground-truth reference images**: one `<page>.png` per page, with a `<page>.meta.json` beside it. The location is written in the page spec's `truth` field; the existing page specs point to the three directories `truth_shots_v7`, `truth_shots_v8` and `truth_shots_v9` under `$DM_ROOT/data/switch/` (the directory names are written in the page specs; reference images re-made after a save change go into a new directory, hence the numbers).
- **Standard save**: the host and the ground truth must start from the same save. The first entry of the `save` field in `meta.json` is the content fingerprint of the ground-truth run's starting save (computed by `savesha.sh`); when the fingerprint of the save the host uses differs from it, that page is reported red immediately, without comparing.
- **Replay files**: pages whose standing position has to be aligned (see below) reference, in the page spec's `host.env`, command packet files recorded from a ground-truth run, located at `$DM_ROOT/data/switch/truth_runs/<run name>/`.
- **Animation masks**: two pages (`camp_e`, `wild`) reference mask images in `shotgate_masks_v2` and `shotgate_masks_v3` under `$DM_ROOT/data/switch/` (likewise directory names written in the page specs).
## Criteria
`shotgate.py <page spec.json> <ground truth.png> <host.png> <report dir>`. The two images are first scaled down to 320×180 and then compared; if any one criterion is red, the page is red. The default thresholds are in `DEF` in `shotgate.py`, and the page spec's `thresholds` can change them per page.
| # | Criterion | Default threshold | What it catches |
|---|---|---|---|
| ① | Structural similarity (SSIM): grayscale, 7×7 box window, masked areas not counted | ≥ 0.60 | Overall distortion of the picture |
| ② | Proportion of non-black pixels (luminance > 0.06) in the 3D viewport | host ≥ ground truth × 0.90 | Whole blocks missing |
| ③ | 8×8 grid, cell by cell: mean luminance difference, mean color distance | ≤ 0.10, ≤ 0.16 | Local omissions and color casts; red cells are drawn into the heat map |
| ④ | Named regions (character, campfire, menu…): region luminance ratio host/ground truth, region structural similarity | luminance ratio ∈ [0.75, 1/0.75], structure ≥ 0.45 | Missing lighting, located to a specific region |
| ⑤ | Fine grid (enabled only when the page spec has `fine_grid`): 640×360 grayscale divided into cells by "columns × rows", mean structural similarity per cell, looking only inside the viewport | The page spec gives the lower bound; number of red cells ≤ `fine_red_max` (default 0) | One small element not drawn |
A few more:
- **Expected-elements table** (the page spec's `elements`): each entry points to a named region and is ticked according to that region's verdict under ④; those pointing to `viewport` go by ②. An element written as 「无」 (none) means that this position must match the ground truth (there is nothing there in the ground truth to begin with).
- **Named regions can have their own thresholds**: `{"rect": […], "ratio_min": …, "ssim_min": …}`. A `ratio_min` of 0 means only structure is compared, not luminance; this is for animated regions.
- **Animation mask** (the page spec's `dynmask`): a mask image in which white marks pixels the client itself animates (flames, flags, etc.); it is merged into the mask and takes no part in the comparison. When the mask covers more than 30% of the viewport, the report marks it 「弱判」 (weak verdict). For fine-grid cells more than half covered by the mask, the structure lower bound becomes `thresholds.dyn_ssim_min` (default 0.5).
- **Host log**: if the screenshot is green but the log contains errors, it is still judged red. The keyword table is in `logred.sh` (lines carrying 【红】 (red), FATAL, the watchdog, Metal command buffer errors, GPU hang or fault, pipeline creation failure).
- **`host.require_log`**: the lines listed in the page spec must appear in the host log; one missing line means red.
- **Screenshot precondition verdict**: every time the host takes a screenshot it writes a line 「SHOT 前置:读取画面已撤 / 本局无读取画面 / 不适用」 (SHOT precondition: loading screen dismissed / no loading screen in this run / not applicable); if this line is missing, it is red.
Why ⑤ is needed: the average over a large region hides "one small element not drawn". The static pages of the UI layer (skill tree, options, stash, character stats, inventory, quest log, etc.) all carry a fine grid.
When the gate runs the host it always sets `DM_BRIGHT_K=1`, turning off "3D scene brightening", a post-processing effect that deliberately deviates from the original, so that only the picture translation itself is checked.
## Page spec
`shotgate_pages/<page>.json`:
| Field | Meaning |
|---|---|
| `page` | The page's Chinese name |
| `truth` | Path of the ground-truth reference image |
| `host.trigger` | When the host takes the screenshot: `<UI message substring>+<frame offset>`, i.e. how many frames after that message appears |
| `host.keys` | The host's key script (`DM_KEYS`); empty string = no key presses |
| `host.env` | Extra environment variables passed to the host (replay file, seed, fixed time, frozen tick, standing-position check, etc.) |
| `host.require_log` | Lines that must appear in the host log |
| `viewport` | The 3D viewport rectangle |
| `mask` | List of rectangles that take no part in the comparison |
| `regions` / `elements` | Named regions and the expected-elements table |
| `thresholds`, `fine_grid`, `fine_red_max`, `dynmask` | See the previous section |
| `note`, `trigger` | Explanatory text, not read by the program |
Rectangles are always written as `[x0, y0, x1, y1]`, with values 0–1, relative to the whole picture.
The syntax of `DM_KEYS` (defined in `dm/host/hle_hid.c`): `key@precondition message[%delay seconds][+hold seconds][>confirmation message]`, with multiple steps separated by commas — the key is pressed after the precondition message appears, and it counts as successful only when the confirmation message is seen. The precondition message can be written as `DM:Tick:<tick number>#`, meaning press when the server reaches that tick.
## Existing pages
| Page | Screen | Screenshot timing |
|---|---|---|
| `charselect` | Character select page | UI message + frame offset |
| `newchar` | Class selection page for a new character | UI message + frame offset |
| `loading` | Game-entry loading screen | UI message + frame offset |
| `warlock_camp` | The camp after a Warlock character enters the game | UI message + frame offset |
| `inventory` | Inventory | UI message + frame offset |
| `char_stats` | Character stats panel | UI message + frame offset |
| `skilltree` | Skill tree | UI message + frame offset |
| `warlock_skilltree` | Warlock skill tree | UI message + frame offset |
| `quest_log` | Quest log | UI message + frame offset |
| `automap` | Automap overlay | UI message + frame offset |
| `options` | Options page (pause menu) | UI message + frame offset |
| `cube` | Horadric Cube | UI message + frame offset |
| `stash` | Stash | Replay walks up to the chest and checks standing position, UI message + frame offset |
| `waypoint` | Waypoint panel | Replay walks to the waypoint and checks standing position, UI message + frame offset |
| `camp_e` | First screen of the camp | Replay + standing-position check + frozen tick |
| `npc` | NPC dialogue menu | Replay + standing-position check + frozen tick |
| `wild` | First screen of the wilderness after teleporting | Replay + standing-position check + frozen tick |
There are currently no pages for combat and death screens.
## How the two sides stop on the same screen
What has to be shown is: the two sides produce the same frame under "the same tick, the same server state, the same client UI".
**Static UI pages** are easy: the ground truth and the host both take the screenshot the same number of frames after the same UI message. On the ground-truth side the driver script captures by `<trigger substring>+<frame offset>:<name>`, on the host side it is `DM_NVN_SHOT_UI`, with the same syntax (the ground truth converts the frame count to wall clock at 30 frames per second).
**Pages with a 3D scene that require walking** (stash, waypoint, NPC, camp, wilderness) are hard because of standing position: if each side pushes the stick and walks on its own, the stopping positions do not line up, and NPCs wander too. The approach is to have the host not walk on its own, and instead replay the ground truth's input:
1. **Ground-truth walking**: the driver script pushes the left stick in a closed loop by "target coordinates − player coordinates", and the movement command packets and system-class messages the client emits while walking are recorded into `c2s.jsonl` as usual. The coordinates are taken from the player table at the server tick entry (read the same way as in [tick_state_format.md](tick_state_format.md)).
2. **Host replay**: `DM_C2S_REPLAY` replays the ground truth's command packets up to the tick of arrival (called tick E below). The server logic is equivalent tick by tick, so the positions of the player, monsters and NPCs are the same on both sides at tick E.
3. **Standing-position check**: `DM_POSCHK=E:x:y:xf:yf` makes the host read the player coordinates at the entry of tick E and compare them with the ground truth's coordinates at that tick. If they differ, the screenshot is withdrawn and the page reports 「站位不一致」 (standing position mismatch); if they are the same, it writes a line 「一致」 (match), and the page spec uses `require_log` to require that this line appear.
4. **Opening the panel**: injecting an interaction packet into the server does not make the client open a panel, so after arrival both sides have the client press the key itself (the ground truth sends an input command, the host uses `DM_KEYS` to press by tick number), and a UI message confirms that the panel is open.
5. **Frozen-tick screenshot**: for pages whose picture changes with the tick, both sides stop at the same tick before capturing. On the host, `DM_TICK_HOLD=E:SHOT` freezes the game clock on entering tick E and unfreezes it after the screenshot is written to disk, with the trigger written as `DM:Tick:E#+N`; on the ground-truth side the screenshot is taken on the first frame after tick E begins. This way, which tick gets captured is independent of frame rate and the machine's load.
Things the client itself animates (flames, ambient critters) are not in the server state and cannot be lined up even with a frozen tick; they are handled by animation masks or by loosening the thresholds of individual regions. How a mask is made: the ground-truth side captures two shots in a row at the same frozen tick, and then `dynmask.py <a.png> <b.png> <output mask.png> [threshold=8] [dilation pixels=3]` takes the difference of the two.
## How to produce ground-truth reference images
Ground-truth reference images are produced by the ground-truth emulator and are not included in the repository; the emulator driver scripts that produce them are not shipped with the repository either.
- Static UI pages are captured a number of frames after the trigger message; pages that require walking are captured at the arrival tick (see the previous section). Each page is one `.png` plus one `.meta.json`.
- Put the finished images together with `meta.json` into the directory the page spec's `truth` field points to. If the standard save is changed, all reference images have to be produced again, put into a new directory with the page specs updated, without overwriting the old directory.
## Adding a page
1. On the ground-truth side, settle the trigger message and frame offset (or the arrival tick), and produce the reference image.
2. Write `shotgate_pages/<page>.json`: following the reference image, mark out the viewport, the named regions and the expected elements; for static UI-layer pages add `fine_grid`.
3. Do a negative control: erase some element from the reference image and compare again; the gate must report red. An omission the criteria fail to catch means the regions or thresholds are not set correctly.
+144
View File
@@ -0,0 +1,144 @@
# 画面闸门
English: [screenshot_gate.md](screenshot_gate.md)
画面闸门把**宿主**(`dm/host` 的 `dmhost`,在 Mac 上执行改写后的游戏程序)画出的关键画面,与**真值**(用打了补丁的 Ryujinx 模拟器跑原版游戏截下的参照图)逐页比较,判断有没有整块缺失、缺光照或结构走样。
为什么要对真值比:只拿宿主的新图比宿主的旧图,两边都黑也会报「一致」。
两边的显卡与着色器链都不同,所以不要求逐像素相同,用下面几条判据。
## 一条命令
```
dm/verify/shotgate.sh [产物目录] [页名…]
```
- 产物目录缺省是当前代号的 `keypage` 产物(`dm/tools/product.sh path keypage`);页名缺省是 `shotgate_pages/` 下全部。
- 开跑先 `make` 宿主。每页起一个宿主(`hostshot.sh`),用标准存档的新副本开局,按页规格里的键序走到那个画面,到触发点截图,再由 `shotgate.py` 与真值参照图比。各页互相独立,并行跑。
- 每页打一行 `SHOTGATE <页> OK|RED …`,末行 `SHOTGATE_ALL OK|RED → <报告路径>`;退出码 0 = 全绿。
报告与现场:
- 有红时,整份现场留在 `$DM_ROOT/run/verify/dm/shotgate/<时刻>_<工作树名>_<进程号>…/`:`index.html` 是汇总,每页一份 `report.html`(真值图 / 宿主图 / 差异热图并排,加判据读数与应有元素表),以及每页的宿主完整日志 `<页>_host.log`。
- 全绿时现场删掉,只留一份小结 `shotgate/green/<目录名>.html`。
- 宿主截图失败(崩溃或看门狗)时,现场目录里会多一个 `KEEP` 文件,并附上系统的崩溃报告副本。
- `shotgate_gc.sh` 在每次结束时清掉超过 3 天的旧现场;带 `KEEP` 的不删,想长期保留的目录里放一个空文件 `PIN`。
| 环境变量 | 作用 |
|---|---|
| `SHOTGATE_JOBS` | 同时跑几页,缺省 6 |
| `SHOTGATE_KEEP_IMG=1` | 全绿也保留整份现场 |
| `SHOTGATE_KEEP_DAYS` | 旧现场保留天数,缺省 3 |
| `DM_GATE_SAVE` | 宿主用的存档目录,缺省 `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001` |
| `DM_HOST` | 宿主可执行文件,缺省本工作树的 `dm/host/dmhost` |
| `DM_PY` | Python 解释器,缺省 `$DM_ROOT/build/cache/dm/venv/bin/python` |
## 前提
仓库里只有页规格与比对程序,下面这些要自己准备(真值从哪来见 [README.zh-CN.md](README.zh-CN.md);取真值用的模拟器驱动脚本不随仓库提供,所以这道闸门在仓库外跑不了):
- **真值参照图**:每页一张 `<页>.png`,旁边一份 `<页>.meta.json`。位置写在页规格的 `truth` 字段里,现有页规格指向 `$DM_ROOT/data/switch/` 下的 `truth_shots_v7`、`truth_shots_v8`、`truth_shots_v9` 三个目录(目录名写在页规格里;换存档重出参照图时另起新目录,所以带着序号)。
- **标准存档**:宿主与真值必须从同一份存档开局。`meta.json` 的 `save` 字段第一项是真值局起始存档的内容指纹(`savesha.sh` 算),宿主所用存档的指纹与它不同时,该页直接报红、不比。
- **回放文件**:站位要对齐的页(见下文)在页规格 `host.env` 里引用真值局录下的命令包文件,位于 `$DM_ROOT/data/switch/truth_runs/<局名>/`。
- **动画遮罩**:两页(`camp_e`、`wild`)引用 `$DM_ROOT/data/switch/` 下 `shotgate_masks_v2`、`shotgate_masks_v3` 里的遮罩图(同样是页规格里写的目录名)。
## 判据
`shotgate.py <页规格.json> <真值.png> <宿主.png> <报告目录>`。两张图先缩到 320×180 再比;任一条红即该页红。阈值的缺省值在 `shotgate.py` 的 `DEF` 里,页规格的 `thresholds` 可以逐页改。
| # | 判据 | 缺省阈值 | 抓什么 |
|---|---|---|---|
| ① | 结构相似度(SSIM):灰度、7×7 盒窗,遮罩区不计 | ≥ 0.60 | 画面整体走样 |
| ② | 3D 视口里非黑像素(亮度 > 0.06)的比例 | 宿主 ≥ 真值 × 0.90 | 整块缺失 |
| ③ | 8×8 网格逐格:平均亮度差、平均颜色距离 | ≤ 0.10、≤ 0.16 | 局部缺失与偏色;红格画进热图 |
| ④ | 命名区域(角色、篝火、菜单……):区域亮度比 宿主/真值、区域结构相似度 | 亮度比 ∈ [0.75, 1/0.75],结构 ≥ 0.45 | 缺光照,并定位到具体区域 |
| ⑤ | 细网格(页规格有 `fine_grid` 才启用):640×360 灰度按「列 × 行」分格,逐格平均结构相似度,只看视口内 | 页规格给下限;红格数 ≤ `fine_red_max`(缺省 0) | 一个小元素没画出来 |
另外几条:
- **应有元素表**(页规格的 `elements`):每项指向一个命名区域,按该区域 ④ 的结论打勾;指向 `viewport` 的按 ②。写「无」的元素,意思是该位置要与真值一致(真值里本来就没有)。
- **命名区域可以单设阈值**:`{"rect": […], "ratio_min": …, "ssim_min": …}`。`ratio_min` 为 0 表示只比结构、不比亮度,给动画区用。
- **动画遮罩**(页规格的 `dynmask`):一张遮罩图,白色是客户端自己在动的像素(火焰、旗帜等),并入遮罩不参与比较。遮罩占视口超过 30% 时,报告里标「弱判」。细网格里被遮罩盖住过半的格,结构下限改用 `thresholds.dyn_ssim_min`(缺省 0.5)。
- **宿主日志**:截图是绿的、日志里有错也判红。关键字表在 `logred.sh`(带【红】的行、FATAL、看门狗、Metal 命令缓冲错误、GPU 挂起或故障、建管线失败)。
- **`host.require_log`**:页规格列出的行必须在宿主日志里出现,缺一行即红。
- **截图前置结论**:宿主每次截图都写一行「SHOT 前置:读取画面已撤 / 本局无读取画面 / 不适用」,缺这一行即红。
为什么要有 ⑤:大区域的平均值会掩盖「一个小元素没画出来」。界面层的静态页(技能树、选项、仓库、角色属性、物品栏、任务日志等)都带细网格。
闸门跑宿主时固定设 `DM_BRIGHT_K=1`,关掉「3D 画面加亮」这个有意偏离原版的后期效果,只核画面翻译本身。
## 页规格
`shotgate_pages/<页>.json`:
| 字段 | 含义 |
|---|---|
| `page` | 页的中文名 |
| `truth` | 真值参照图路径 |
| `host.trigger` | 宿主截图时机:`<UI 消息子串>+<帧偏移>`,即该消息出现后第几帧截 |
| `host.keys` | 宿主的按键脚本(`DM_KEYS`),空串 = 不按键 |
| `host.env` | 额外传给宿主的环境变量(回放文件、种子、固定时刻、冻结拍、站位核对等) |
| `host.require_log` | 宿主日志里必须出现的行 |
| `viewport` | 3D 视口矩形 |
| `mask` | 不参与比较的矩形列表 |
| `regions` / `elements` | 命名区域与应有元素表 |
| `thresholds`、`fine_grid`、`fine_red_max`、`dynmask` | 见上节 |
| `note`、`trigger` | 说明文字,程序不读 |
矩形一律写成 `[x0, y0, x1, y1]`,取值 0–1,相对整幅画面。
`DM_KEYS` 的写法(定义在 `dm/host/hle_hid.c`):`键@前置消息[%延时秒][+按住秒][>确认消息]`,多步用逗号隔开——等前置消息出现后按键,见到确认消息才算成功。前置消息可以写成 `DM:Tick:<拍号>#`,表示服务端走到该拍时按。
## 现有的页
| 页 | 画面 | 截图时机 |
|---|---|---|
| `charselect` | 选角页 | UI 消息 + 帧偏移 |
| `newchar` | 新建角色的职业选择页 | UI 消息 + 帧偏移 |
| `loading` | 进局装载画面 | UI 消息 + 帧偏移 |
| `warlock_camp` | 术士角色进局后的营地 | UI 消息 + 帧偏移 |
| `inventory` | 物品栏 | UI 消息 + 帧偏移 |
| `char_stats` | 角色属性面板 | UI 消息 + 帧偏移 |
| `skilltree` | 技能树 | UI 消息 + 帧偏移 |
| `warlock_skilltree` | 术士技能树 | UI 消息 + 帧偏移 |
| `quest_log` | 任务日志 | UI 消息 + 帧偏移 |
| `automap` | 自动地图叠加 | UI 消息 + 帧偏移 |
| `options` | 选项页(暂停菜单) | UI 消息 + 帧偏移 |
| `cube` | 赫拉迪克方块 | UI 消息 + 帧偏移 |
| `stash` | 仓库 | 回放走到箱子旁并核站位,UI 消息 + 帧偏移 |
| `waypoint` | 传送点面板 | 回放走到传送点并核站位,UI 消息 + 帧偏移 |
| `camp_e` | 营地第一屏 | 回放 + 核站位 + 冻结拍 |
| `npc` | NPC 对话菜单 | 回放 + 核站位 + 冻结拍 |
| `wild` | 传送后的野外第一屏 | 回放 + 核站位 + 冻结拍 |
战斗与死亡画面目前没有页。
## 两边怎么停在同一个画面
要证的是:两边在「同一拍、同一服务端状态、同一客户端界面」下出同一帧。
**静态界面页**好办:真值与宿主都在同一条 UI 消息之后隔同样多帧截图。真值侧由驱动脚本按 `<触发子串>+<帧偏移>:<名>` 截,宿主侧是 `DM_NVN_SHOT_UI`,写法相同(真值按 30 帧/秒把帧数折成墙钟)。
**带 3D 场景、要走位的页**(仓库、传送点、NPC、营地、野外)难在站位:两边各自推摇杆走,停的位置对不齐,NPC 也会游荡。做法是让宿主不自己走,改为回放真值的输入:
1. **真值走位**:驱动脚本按「目标坐标 − 玩家坐标」闭环推左摇杆,走的过程中客户端发出的移动命令包与系统类消息照常录进 `c2s.jsonl`。坐标取自服务端拍入口处的玩家表(读法同 [tick_state_format.zh-CN.md](tick_state_format.zh-CN.md))。
2. **宿主回放**:`DM_C2S_REPLAY` 回放真值的命令包到到达那一拍(下称 E 拍)。服务端逻辑逐拍等价,所以玩家、怪、NPC 的位置在 E 拍两边相同。
3. **核站位**:`DM_POSCHK=E:x:y:xf:yf` 让宿主在 E 拍入口读玩家坐标,与真值在该拍的坐标比。不同就撤掉截图,该页报「站位不一致」;相同则写一行「一致」,页规格用 `require_log` 要求这一行必须出现。
4. **开面板**:往服务端注入交互包不会让客户端开面板,所以到达之后两边都由客户端自己按键(真值发输入指令,宿主用 `DM_KEYS` 按拍号按),并以 UI 消息确认面板已开。
5. **冻结拍截图**:画面随拍变化的页,两边都停在同一拍再截。宿主 `DM_TICK_HOLD=E:SHOT` 在进入 E 拍时冻结游戏时钟,截图写盘后解冻,触发写成 `DM:Tick:E#+N`;真值侧在 E 拍开始后的第一帧截图。这样截到哪一拍与帧率、本机负载无关。
客户端自己在动的东西(火焰、环境小动物)不在服务端状态里,冻结拍也对不齐,靠动画遮罩或放宽个别区域的阈值处理。遮罩的做法:真值侧在同一冻结拍连截两张,再用 `dynmask.py <a.png> <b.png> <输出遮罩.png> [阈值=8] [膨胀像素=3]` 取两张之差。
## 怎么出真值参照图
真值参照图由真值模拟器出,仓库里不带;出图用的模拟器驱动脚本也不随仓库提供。
- 静态界面页在触发消息之后隔若干帧截;要走位的页在到达拍截(见上节)。每页一张 `.png` 加一份 `.meta.json`。
- 出好的图连同 `meta.json` 放进页规格 `truth` 字段指的目录。换了标准存档就要重出全部参照图,放进新目录并改页规格,不覆盖旧目录。
## 加一页
1. 在真值侧定下触发消息与帧偏移(或到达拍),出参照图。
2. 写 `shotgate_pages/<页>.json`:照参照图框出视口、命名区域与应有元素;界面层静态页加 `fine_grid`。
3. 做负对照:把参照图里某个元素抹掉再比,闸门必须报红。判据抓不到的缺失,说明区域或阈值没设对。
+170
View File
@@ -0,0 +1,170 @@
# 对真值的画面闸门:同一关键画面,真值(Ryujinx 跑官方 94012)截图 vs 宿主截图,判「整块缺失 / 缺光照 / 结构走样」。
# 用法:shotgate.py <页规格.json> <真值.png> <宿主.png> <报告目录> → 报告目录/report.html(并排两图 + 差异热图 + 读数 + 应有元素表)、result.json
# 末行 SHOTGATE <页> OK|RED …;退出码 0 = 绿,1 = 红
# 不要求逐像素相同(两边 GPU、着色器链都不同)。四条判据(任一条红即红;阈值在页规格里,缺省见 DEF,标定记录见 dm/verify/screenshot_gate.md):
# ① 结构相似度(灰度、缩到 320×180、7×7 窗口;遮罩区不计)≥ ssim_min
# ② 3D 视口非黑像素比例(亮度 > 0.06):宿主 ≥ 真值 × nonblack_ratio_min
# ③ 8×8 网格逐格:平均亮度差 |ΔL| ≤ cell_dl_max 且平均颜色距离 ≤ cell_dc_max(整格被遮罩的跳过);红格进热图
# ④ 命名区域(角色、篝火、菜单……):区域平均亮度 宿主/真值 ∈ [region_ratio_min, 1/region_ratio_min],区域结构相似度 ≥ region_ssim_min
# 应有元素表逐项按其区域的 ④ 结论打勾;「不应有」的元素(如推广框)要求该区域与真值一致(真值里本来就没有)。
# Screenshot gate against ground truth: for the same key screen, the ground-truth screenshot (Ryujinx running the official 94012) vs the host screenshot, judging "whole block missing / lighting missing / structure distorted".
# Usage: shotgate.py <page spec.json> <ground truth.png> <host.png> <report dir> → <report dir>/report.html (two images side by side + difference heat map + readings + expected-elements table), result.json
# last line SHOTGATE <page> OK|RED ...; exit code 0 = pass, 1 = fail
# Pixel-identical output is not required (GPU and shader chain differ on the two sides). Four criteria (any one failing means the page fails; thresholds are in the page spec, defaults in DEF, calibration records in dm/verify/screenshot_gate.md):
# ① Structural similarity (grayscale, scaled to 320×180, 7×7 window; masked areas excluded) ≥ ssim_min
# ② Share of non-black pixels in the 3D viewport (brightness > 0.06): host ≥ ground truth × nonblack_ratio_min
# ③ 8×8 grid, per cell: mean brightness difference |ΔL| ≤ cell_dl_max and mean color distance ≤ cell_dc_max (fully masked cells are skipped); failing cells go into the heat map
# ④ Named regions (character, campfire, menu...): region mean brightness host/ground truth ∈ [region_ratio_min, 1/region_ratio_min], region structural similarity ≥ region_ssim_min
# Each item in the expected-elements table is ticked by the ④ result of its region; "must not be present" elements (such as the promotion box) require that region to match the ground truth (where it is absent to begin with).
import sys, os, json, html, base64, io
import numpy as np
from PIL import Image
DEF = dict(ssim_min=0.60, nonblack_ratio_min=0.90, cell_dl_max=0.10, cell_dc_max=0.16, region_ratio_min=0.75, region_ssim_min=0.45)
W, H = 320, 180
def load(p):
im = Image.open(p).convert('RGB').resize((W, H), Image.BILINEAR)
return np.asarray(im, dtype=np.float64) / 255.0
def lum(a): return a[..., 0] * 0.2126 + a[..., 1] * 0.7152 + a[..., 2] * 0.0722
def box(a, r=3):
"""(2r+1)² 盒滤波(积分图),边缘按有效像素数归一。 | (2r+1)² box filter (integral image), edges normalized by the number of valid pixels."""
p = np.pad(a, r, mode='edge'); c = p.cumsum(0).cumsum(1); c = np.pad(c, ((1, 0), (1, 0)))
k = 2 * r + 1
return (c[k:, k:] - c[:-k, k:] - c[k:, :-k] + c[:-k, :-k]) / (k * k)
def ssim_map(x, y):
C1, C2 = 0.01 ** 2, 0.03 ** 2
mx, my = box(x), box(y)
vx, vy, cxy = box(x * x) - mx * mx, box(y * y) - my * my, box(x * y) - mx * my
return ((2 * mx * my + C1) * (2 * cxy + C2)) / ((mx * mx + my * my + C1) * (vx + vy + C2))
def rect_px(r): return int(r[0] * W), int(r[1] * H), max(int(r[0] * W) + 1, int(r[2] * W)), max(int(r[1] * H) + 1, int(r[3] * H))
def main():
spec_p, tp, hp, out = sys.argv[1:5]
spec = json.load(open(spec_p, encoding='utf-8')); th = {**DEF, **spec.get('thresholds', {})}
os.makedirs(out, exist_ok=True)
T, Hs = load(tp), load(hp); LT, LH = lum(T), lum(Hs)
mask = np.zeros((H, W), bool)
for r in spec.get('mask', []):
x0, y0, x1, y1 = rect_px(r); mask[y0:y1, x0:x1] = True
# 动画遮罩(页规格 dynmask = 遮罩 png,dynmask.py 由同一冻结拍两张截图之差生成;白 = 客户端在动的像素):并入遮罩,射程报占视口比例;
# 占视口 > 30% 判据失明,标「弱判」
# Animation mask (page spec dynmask = mask png, generated by dynmask.py from the difference of two screenshots at the same frozen tick; white = pixels the client is animating): merged into the mask, coverage reports its share of the viewport;
# above 30% of the viewport the criterion is blind, marked 「弱判」(weak verdict)
dyn = None
if spec.get('dynmask'):
dm = np.asarray(Image.open(os.path.expanduser(spec['dynmask'])).convert('L').resize((W, H), Image.BOX), dtype=np.float64) > 0
mask |= dm
vx0_, vy0_, vx1_, vy1_ = rect_px(spec.get('viewport', [0, 0, 1, 1])); dyn = float(dm[vy0_:vy1_, vx0_:vx1_].mean())
keep = ~mask
S = ssim_map(LT, LH); ssim = float(S[keep].mean())
vx0, vy0, vx1, vy1 = rect_px(spec.get('viewport', [0, 0, 1, 1]))
nb_t = float((LT[vy0:vy1, vx0:vx1] > 0.06).mean()); nb_h = float((LH[vy0:vy1, vx0:vx1] > 0.06).mean())
# ③ 网格
# ③ Grid
G = 8; cells = []; red_cells = 0; heat = np.zeros((G, G))
for gy in range(G):
for gx in range(G):
ys, xs = slice(gy * H // G, (gy + 1) * H // G), slice(gx * W // G, (gx + 1) * W // G)
k = keep[ys, xs]
if k.mean() < 0.5: cells.append(None); heat[gy, gx] = -1; continue
dl = float(abs(LT[ys, xs][k].mean() - LH[ys, xs][k].mean()))
dc = float(np.linalg.norm(T[ys, xs][k].mean(0) - Hs[ys, xs][k].mean(0)))
bad = dl > th['cell_dl_max'] or dc > th['cell_dc_max']; red_cells += bad
heat[gy, gx] = max(dl / th['cell_dl_max'], dc / th['cell_dc_max']); cells.append((dl, dc, bad))
# ④ 命名区域
# ④ Named regions
regs = {}
for name, r in spec.get('regions', {}).items():
rth = {}
if isinstance(r, dict): rth = r; r = r['rect'] # 区域可单设阈值:{"rect": [...], "ratio_min": …, "ssim_min": …}(动画区如装载框里的视频) | A region can set its own thresholds: {"rect": [...], "ratio_min": ..., "ssim_min": ...} (animated regions such as the video in the loading frame)
x0, y0, x1, y1 = rect_px(r)
lt, lh = float(LT[y0:y1, x0:x1].mean()), float(LH[y0:y1, x0:x1].mean())
ratio = lh / lt if lt > 1e-4 else (1.0 if lh < 1e-4 else 99.0)
rs = float(S[y0:y1, x0:x1].mean())
rmin = rth.get('ratio_min', th['region_ratio_min']); smin = rth.get('ssim_min', th['region_ssim_min'])
ok = (rmin <= 0 or rmin <= ratio <= 1 / rmin) and rs >= smin # ratio_min 0 = 只比结构不比亮度(动画区) | ratio_min 0 = compare structure only, not brightness (animated regions)
regs[name] = dict(truth_lum=round(lt, 4), host_lum=round(lh, 4), ratio=round(ratio, 3), ssim=round(rs, 3), ok=ok)
# ⑤ 细网格(页规格 fine_grid = [列, 行, 结构下限];动画遮罩过半的格用 dyn_ssim_min):640×360 灰度逐格平均 SSIM,抓「一个小元素没画出来」这类大区域平均掩盖的缺失
# ⑤ Fine grid (page spec fine_grid = [columns, rows, structure floor]; cells more than half covered by the animation mask use dyn_ssim_min): per-cell mean SSIM on 640×360 grayscale, catches omissions like "one small element was not drawn" that large-region averages hide
fine = None
if spec.get('fine_grid'):
fc, fr, fmin = spec['fine_grid']
def load2(p):
a = np.asarray(Image.open(p).convert('RGB').resize((640, 360), Image.BILINEAR), dtype=np.float64) / 255.0; return lum(a)
S2 = ssim_map(load2(tp), load2(hp)); bad_cells = []
m2 = np.zeros((360, 640), bool)
for r in spec.get('mask', []):
m2[int(r[1] * 360):max(int(r[1] * 360) + 1, int(r[3] * 360)), int(r[0] * 640):max(int(r[0] * 640) + 1, int(r[2] * 640))] = True
dm2 = (np.asarray(Image.open(os.path.expanduser(spec['dynmask'])).convert('L').resize((640, 360), Image.BOX)) > 0) if spec.get('dynmask') else np.zeros((360, 640), bool)
dmin2 = th.get('dyn_ssim_min', 0.5)
for gy in range(fr):
for gx in range(fc):
ys, xs = slice(gy * 360 // fr, (gy + 1) * 360 // fr), slice(gx * 640 // fc, (gx + 1) * 640 // fc)
k = ~m2[ys, xs]
cx, cy = (gx + 0.5) / fc, (gy + 0.5) / fr; vp = spec.get('viewport', [0, 0, 1, 1])
if k.mean() < 0.5 or not (vp[0] <= cx <= vp[2] and vp[1] <= cy <= vp[3]): continue # 只看视口内(面板外露出的 3D 背景会随墙钟动) | Only look inside the viewport (the 3D background showing outside the panel moves with the wall clock)
v = float(S2[ys, xs][k].mean())
lim = dmin2 if dm2[ys, xs].mean() >= 0.5 else fmin # 动画遮罩盖住过半的格:不比像素级,结构下限放到 dyn_ssim_min | Cells more than half covered by the animation mask: no pixel-level comparison, the structure floor is relaxed to dyn_ssim_min
if v < lim: bad_cells.append((gx, gy, round(v, 3)))
fine = (fc, fr, fmin, bad_cells)
crit = [
('① 结构相似度', ssim >= th['ssim_min'], f'{ssim:.3f}(≥ {th["ssim_min"]})'),
('② 3D 视口非黑比例', nb_h >= nb_t * th['nonblack_ratio_min'], f'宿主 {nb_h:.3f} / 真值 {nb_t:.3f}(宿主 ≥ 真值 × {th["nonblack_ratio_min"]})'),
('③ 8×8 网格', red_cells == 0, f'红格 {red_cells} / {sum(c is not None for c in cells)}(|ΔL| ≤ {th["cell_dl_max"]}、色差 ≤ {th["cell_dc_max"]})'),
('④ 命名区域', all(v['ok'] for v in regs.values()), ';'.join(f'{k} 亮度比 {v["ratio"]} 结构 {v["ssim"]}{"" if v["ok"] else " ✗"}' for k, v in regs.items()) or '无'),
]
if dyn is not None:
crit.append(('⑥ 动画遮罩射程', True, f'遮罩占视口 {dyn:.1%}' + ('(> 30%:严格判据失明,本页为「弱判」)' if dyn > 0.30 else '')))
if fine:
fc, fr, fmin, bc = fine
# fine_red_max(页规格,缺省 0):允许的红格数。只给有「客户端环境小动物」的页用——它不在服务端状态里,位置随客户端帧游走,
# 真值与宿主各在各的随机位置,正好落在某格中央时该格结构掉到约 0.58(NPC 对话页的鸡);该页关键元素另有命名区域把关
# fine_red_max (page spec, default 0): number of failing cells allowed. Only for pages with "client-side ambient critters" - they are not in server state and their position wanders with client frames,
# ground truth and host each have them at their own random positions, and when one lands right in the middle of a cell that cell's structure drops to about 0.58 (the chicken on the NPC dialogue page); that page's key elements are separately guarded by named regions
fmax = int(spec.get('fine_red_max', 0))
crit.append(('⑤ 细网格', len(bc) <= fmax, f'{fc}×{fr} 格结构 ≥ {fmin}:红格 {len(bc)}' + (f'(本页允许 ≤ {fmax})' if fmax else '') + (f',最差 {sorted(bc, key=lambda t: t[2])[:3]}(列, 行, 值)' if bc else '')))
elems = []
for e in spec.get('elements', []):
r = regs.get(e['region']); ok = bool(r and r['ok']) if e['region'] != 'viewport' else crit[1][1]
elems.append((e['name'], e.get('expect', '有'), ok))
green = all(c[1] for c in crit) and all(e[2] for e in elems)
# 热图:绿 → 黄 → 红(≥1 即超阈值),遮罩格灰
# Heat map: green → yellow → red (≥1 means over threshold), masked cells gray
hm = np.zeros((G, G, 3))
for gy in range(G):
for gx in range(G):
v = heat[gy, gx]
hm[gy, gx] = (0.5, 0.5, 0.5) if v < 0 else ((min(1, v), 1 - min(1, v) * 0.8, 0.1) if v < 1 else (0.9, 0.05, 0.05))
hmi = Image.fromarray((hm * 255).astype(np.uint8)).resize((W * 2, H * 2), Image.NEAREST)
base = Image.fromarray((Hs * 255).astype(np.uint8)).resize((W * 2, H * 2)).convert('RGB')
over = Image.blend(base, hmi, 0.55); over.save(os.path.join(out, 'heat.png'))
res = dict(page=spec['page'], dynmask_ratio=dyn, truth=os.path.abspath(tp), host=os.path.abspath(hp), green=green, ssim=round(ssim, 4),
nonblack=dict(truth=round(nb_t, 4), host=round(nb_h, 4)), red_cells=red_cells, regions=regs,
elements=[dict(name=n, expect=x, ok=o) for n, x, o in elems], thresholds=th)
json.dump(res, open(os.path.join(out, 'result.json'), 'w'), ensure_ascii=False, indent=1)
def b64(p, w=800):
im = Image.open(p).convert('RGB'); im.thumbnail((w, w)); bio = io.BytesIO(); im.save(bio, 'PNG')
return base64.b64encode(bio.getvalue()).decode()
rows = ''.join(f'<tr><td>{html.escape(n)}</td><td class={"ok" if ok else "bad"}>{"绿" if ok else "红"}</td><td>{html.escape(d)}</td></tr>' for n, ok, d in crit)
erows = ''.join(f'<tr><td>{html.escape(n)}</td><td>{html.escape(x)}</td><td class={"ok" if ok else "bad"}>{"✓" if ok else "✗"}</td></tr>' for n, x, ok in elems)
page = f'''<!doctype html><meta charset=utf-8><title>画面闸门 {html.escape(spec["page"])}</title>
<style>body{{font:14px -apple-system,sans-serif;margin:16px;background:#fff;color:#111}}img{{width:100%;border:1px solid #ccc}}
.g{{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:10px}}td,th{{border:1px solid #ccc;padding:4px 8px}}table{{border-collapse:collapse}}
.ok{{color:#070;font-weight:600}}.bad{{color:#c00;font-weight:600}}h1 span{{font-size:18px}}</style>
<h1>{html.escape(spec["page"])} <span class={"ok" if green else "bad"}>{"绿" if green else "红"}</span></h1>
<div class=g><div><b>真值</b><img src="data:image/png;base64,{b64(tp)}"></div><div><b>宿主</b><img src="data:image/png;base64,{b64(hp)}"></div>
<div><b>差异热图(叠在宿主上;红 = 超阈值格,灰 = 遮罩)</b><img src="data:image/png;base64,{b64(os.path.join(out, "heat.png"))}"></div></div>
<h2>判据</h2><table><tr><th>判据</th><th>结论</th><th>读数</th></tr>{rows}</table>
<h2>应有元素</h2><table><tr><th>元素</th><th>应</th><th>结论</th></tr>{erows}</table>
<p>真值 {html.escape(os.path.abspath(tp))}<br>宿主 {html.escape(os.path.abspath(hp))}</p>'''
open(os.path.join(out, 'report.html'), 'w', encoding='utf-8').write(page)
print(f'SHOTGATE {spec["page"]} {"OK" if green else "RED"} 结构 {ssim:.3f} 非黑 宿主 {nb_h:.3f}/真值 {nb_t:.3f} 红格 {red_cells} '
+ ' '.join(f'{k}:{v["ratio"]}/{v["ssim"]}{"" if v["ok"] else "✗"}' for k, v in regs.items()) + (f' 细网格红格 {len(fine[3])}' if fine else '') + (f' 动画遮罩 {dyn:.1%}' + ('【弱判】' if dyn > 0.30 else '') if dyn is not None else '') + f' → {out}/report.html')
sys.exit(0 if green else 1)
if __name__ == '__main__': main()
+89
View File
@@ -0,0 +1,89 @@
#!/bin/bash
# 对真值的画面闸门,一条命令:逐个关键画面起宿主截图(按 UI 消息触发、按页规格的键序)→ 与真值参照图比(shotgate.py)→ 汇总报告(并排出图)。
# 用法:dm/verify/shotgate.sh [产物目录=out/3.3.94012-r11] [页名…=全部] 宿主用本工作树 dm/host/dmhost(开跑先 make)
# 报告:有红 / 标 KEEP 时在 $DM_ROOT/run/verify/dm/shotgate/<时刻>/index.html(整份现场保留);全绿时现场删掉、只留小结 shotgate/green/<时刻>.html。末行 SHOTGATE_ALL OK|RED → <报告路径>;退出码 0 = 全绿。旧现场由 shotgate_gc.sh 自清(缺省留 3 天)
# 页规格:dm/verify/shotgate_pages/<页>.json(truth = 参照图;host.trigger / host.keys = 宿主 DM_NVN_SHOT_UI 触发与 DM_KEYS;阈值与标定见 screenshot_gate.md)
# 指纹核对:参照图旁的 <页>.meta.json 记真值起始存档指纹,宿主所用存档(DM_GATE_SAVE,缺省现行标准存档)指纹不同即该页报红、不比
# Screenshot gate against ground truth, one command: for each key screen start the host and take a screenshot (triggered by UI message, with the page spec's key sequence) → compare with the ground-truth reference image (shotgate.py) → summary report (images side by side).
# Usage: dm/verify/shotgate.sh [build output dir=out/3.3.94012-r11] [page names...=all] the host is this worktree's dm/host/dmhost (make runs first)
# Report: with any failure / KEEP mark, at $DM_ROOT/run/verify/dm/shotgate/<timestamp>/index.html (full artifacts kept); when all green the artifacts are deleted and only the summary shotgate/green/<timestamp>.html is kept. Last line SHOTGATE_ALL OK|RED → <report path>; exit code 0 = all green. Old artifacts are cleaned up by shotgate_gc.sh (kept 3 days by default)
# Page spec: dm/verify/shotgate_pages/<page>.json (truth = reference image; host.trigger / host.keys = the host's DM_NVN_SHOT_UI trigger and DM_KEYS; thresholds and calibration in screenshot_gate.md)
# Fingerprint check: <page>.meta.json next to the reference image records the fingerprint of the ground truth's starting save; if the save the host uses (DM_GATE_SAVE, default: the current standard save) has a different fingerprint, that page is reported as a failure and not compared
set -u
HERE=$(cd "$(dirname "$0")" && pwd); PY=${DM_PY:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python}
OUT=${1:-$(bash "$(dirname "$0")/../tools/product.sh" path keypage)}; [ $# -gt 0 ] && shift
PAGES=${*:-$(cd "$HERE/shotgate_pages" && ls *.json | sed 's/\.json$//')}
BIN=${DM_HOST:-$HERE/../host/dmhost}
SV=${DM_GATE_SAVE:-${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001}; HSHA=$("$HERE/savesha.sh" "$SV")
TREE=$(basename "$(git -C "$HERE" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$HERE")")
mkdir -p "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/shotgate"
R=$(mktemp -d "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/shotgate/$(date +%m%d_%H%M%S)_${TREE}_$$.XXXXXX") || { echo "🔴 无法创建 shotgate 结果目录"; exit 1; }
touch "$R/index.start" # 起跑时刻(收崩溃报告用) | Run start time (used for collecting crash reports)
make -s -C "$HERE/../host" || { echo "🔴 宿主编译失败"; exit 1; }
# 宿主日志红线关键字表在 logred.sh(与 accept ② 共用)
# The host log a failure line-line keyword table lives in logred.sh (shared with accept ②)
ROUTE=${DM_NVN_ROUTE:-B}; [ -n "${DM_NVN_B:-}" ] && [ "${DM_NVN_B}" != all ] && ROUTE="A/B 混(DM_NVN_B=$DM_NVN_B)" # 着色器路线:宿主缺省 B,DM_NVN_ROUTE=A 切回 A | Shader route: the host defaults to B, DM_NVN_ROUTE=A switches back to A
echo "着色器路线 ${ROUTE};产物 $(basename "$OUT");宿主 $BIN"
rc=0; rows=""
page() { # 单页:截图 + 比对,结果写 $R/$1.res(首行 rc,次行读数) | Single page: screenshot + comparison, result written to $R/$1.res (first line rc, second line readings)
local p=$1 S=$HERE/shotgate_pages/$1.json T TRIG KEYS TSHA KE HL ERRS line prc=0
read -r T TRIG KEYS < <($PY -c "import json,os; d=json.load(open('$S')); h=d['host']; print(os.path.expanduser(d['truth']), h['trigger'], h.get('keys') or '-')")
local -a HE=(); while IFS= read -r kv; do [ -n "$kv" ] && HE+=("$kv"); done < <($PY -c "import json,os; [print(f'{k}={os.path.expanduser(v)}') for k,v in json.load(open('$S'))['host'].get('env',{}).items()]") # 页规格 host.env:回放文件、种子等 | Page spec host.env: replay file, seed, etc.
[ -f "$T" ] || { printf '1\n🔴 %s 缺真值参照图 %s\n' "$p" "$T" > "$R/$p.res"; return; }
TSHA=$($PY -c "import json; print(json.load(open('${T%.png}.meta.json'))['save'][0])" 2>/dev/null)
[ "$TSHA" = "$HSHA" ] || { printf '1\n🔴 %s 存档指纹不符:真值 %s / 宿主 %s\n' "$p" "${TSHA:0:12}" "${HSHA:0:12}" > "$R/$p.res"; return; }
if [ "$KEYS" = - ]; then KE=(); else KE=(DM_KEYS="$KEYS"); fi
# DM_BRIGHT_K=1:3D 画面加亮(nvn_mtl.m bright_lut, ×4 曝光)是有意偏离原版的后期效果,闸门比原版真值时关掉,只核翻译本身;加亮效果由合入前回归另验
# DM_BRIGHT_K=1: 3D scene brightening (nvn_mtl.m bright_lut, ×4 exposure) is a post effect that intentionally deviates from the original game; it is turned off when the gate check compares against the original-game ground truth, so only the translation itself is checked; the brightening effect is verified separately by the pre-merge regression
env DM_BRIGHT_K=1 ${KE[@]+"${KE[@]}"} ${HE[@]+"${HE[@]}"} DM_GATE_SAVE="$SV" "$HERE/hostshot.sh" "$BIN" "$OUT" "$TRIG" "$R/${p}_host.png" > "$R/${p}_shot.log" 2>&1 || {
# 站位不一致是判定结果(DM_POSCHK 按设计撤截图),不是宿主故障:报站位红,不标 KEEP
# A position mismatch is a verdict (DM_POSCHK withdraws the screenshot by design), not a host fault: report a position fail, do not mark KEEP
PR=$(grep -h '【红】DM_POSCHK' "$R/${p}_host.log" 2>/dev/null | head -1)
[ -n "$PR" ] && { printf '1\n🔴 %s 站位不一致:%s\n' "$p" "${PR#*【红】}" > "$R/$p.res"; return; }
printf '1\n🔴 %s 宿主截图失败:%s(现场保留)\n' "$p" "$(tail -1 "$R/${p}_shot.log")" > "$R/$p.res"
echo "$p 宿主截图失败 / 看门狗:本目录是现场,不许删、不许重跑覆盖" >> "$R/KEEP"
pid=$(cat "$R/${p}_host.png.pid" 2>/dev/null)
if [ -n "$pid" ]; then
find ~/Library/Logs/DiagnosticReports -name 'dmhost-*' -newer "$R/index.start" -exec sh -c 'grep -qE "(^|[^0-9])PID[^0-9]*$1([^0-9]|$)|dmhost[^0-9]*\[$1\]" "$2" 2>/dev/null && cp "$2" "$3/"' sh "$pid" {} "$R" \; 2>/dev/null
fi
return; }
# 宿主日志判据(截图绿而日志里 GPU 挂起 / 命令缓冲被拒也要红):【红】行、命令缓冲错误、GPU 挂起 / 故障、建管线失败
# Host log criterion (a green screenshot with a GPU hang / rejected command buffer in the log must still fail): 【红】(red) lines, command buffer errors, GPU hang / fault, pipeline creation failure
HL=$R/${p}_host.log; ERRS=$("$HERE/logred.sh" "$HL" | cut -f1)
line=$($PY "$HERE/shotgate.py" "$S" "$T" "$R/${p}_host.png" "$R/$p") || prc=1
# 页规格 host.require_log:宿主日志必须出现的行(如 DM_POSCHK 站位一致),缺一行即红
# Page spec host.require_log: lines that must appear in the host log (e.g. DM_POSCHK position match); one missing line is a fail
local miss=$($PY -c "import json,sys; L=open('$HL',errors='replace').read(); [print(x) for x in json.load(open('$S'))['host'].get('require_log',[]) if x not in L]")
# 截图前置结论由宿主一处判、每次截图必写一行(已撤 / 本局无读取画面 / 不适用);缺行即红,「未撤」由 hostshot 当场判红
# The screenshot precondition verdict is decided in one place by the host, and one line is always written per screenshot (dismissed / no loading screen in this run / not applicable); a missing line is a fail, and 「未撤」(not dismissed) is failed on the spot by hostshot
grep -qE 'SHOT 前置:(读取画面已撤|本局无读取画面|不适用)' "$HL" || miss="${miss}${miss:+$'\n'}SHOT 前置结论行(宿主未写)"
[ -n "$miss" ] && { prc=1; line="${line/ OK / RED(宿主日志缺:$(echo "$miss" | head -1 | cut -c1-80))}"; }
if [ "$ERRS" -gt 0 ]; then prc=1; line="${line/ OK / RED(宿主日志 $ERRS 行错误:$("$HERE/logred.sh" "$HL" | cut -f2 | cut -c1-120))}"; line="${line/ RED / RED(宿主日志 $ERRS 行错误)}"; fi
printf '%s\n%s\n' "$prc" "$line" > "$R/$p.res"
}
# 各页互相独立(每页自己的存档副本与截图),并行跑(SHOTGATE_JOBS,缺省 6):实测令牌池 17 页 J=4 61 秒 / J=6 44 秒 / 单页 8–17 秒不随并发变长
# 令牌池(/bin/bash 3.2 无 wait -n):任一页结束即起下一页,不按批等最慢的一页
# Pages are independent of each other (each has its own save copy and screenshot) and run in parallel (SHOTGATE_JOBS, default 6): measured with the token pool, 17 pages take 61 seconds at J=4 / 44 seconds at J=6 / a single page takes 8–17 seconds and does not get longer with concurrency
# Token pool (/bin/bash 3.2 has no wait -n): the next page starts as soon as any page ends, without waiting per batch for the slowest page
mkfifo "$R/sem" && exec 3<>"$R/sem" && rm "$R/sem"
for i in $(seq 1 ${SHOTGATE_JOBS:-6}); do echo >&3; done
for p in $PAGES; do read -u 3; { page "$p"; echo >&3; } & done; wait; exec 3>&-
for p in $PAGES; do
{ read -r prc; read -r line; } < "$R/$p.res"; [ "$prc" = 0 ] || rc=1
echo "$line"; rows="$rows<li><a href=\"$p/report.html\">$p</a>:${line#SHOTGATE }</li>"
done
echo "<!doctype html><meta charset=utf-8><title>画面闸门</title><h1>画面闸门 $(date '+%m-%d %H:%M')</h1><p>产物 ${OUT};宿主 ${BIN};着色器路线 ${ROUTE};存档指纹 ${HSHA:0:12};每页宿主完整日志 *_host.log</p><ul>${rows}</ul>" > "$R/index.html"
[ -f "$R/KEEP" ] && echo "⚠️ 宿主截图失败 / 看门狗:现场 $R 已标 KEEP(含崩溃报告副本),保留,勿重跑抹掉"
# 全绿且没标 KEEP:整个结果目录删掉,只留一份首页小结 green/<目录名>.html(各页结果行)。全绿的现场重跑就有,留着只占盘:
# 原先只删图,每页那份内嵌图的 report.html(约 1.8 MB × 17 页)还在,一次仍占约 27 MB;攒到 956 个目录 34 GB。
# 红的、标了 KEEP 的原样全留。想留全绿的整份现场看:SHOTGATE_KEEP_IMG=1
# All green and not marked KEEP: delete the whole result directory, keeping only a front-page summary green/<directory name>.html (the result line of each page). All-green artifacts can be had again by rerunning, keeping them only takes disk:
# previously only images were deleted, and each page's report.html with embedded images (about 1.8 MB × 17 pages) remained, still about 27 MB per run; it piled up to 956 directories and 34 GB.
# Failed ones and those marked KEEP are kept in full as they are. To keep the full artifacts of an all-green run for viewing: SHOTGATE_KEEP_IMG=1
ROOT=$(dirname "$R"); REP="$R/index.html"
if [ $rc = 0 ] && [ ! -f "$R/KEEP" ] && [ "${SHOTGATE_KEEP_IMG:-0}" != 1 ] && [ "$(basename "$ROOT")" = shotgate ] && [ -n "$(basename "$R")" ]; then
mkdir -p "$ROOT/green"; REP="$ROOT/green/$(basename "$R").html"
{ sed -e 's#<a href="[^"]*">##g' -e 's#</a>##g' "$R/index.html"; echo "<p>全绿:现场目录已删,只留这份小结(SHOTGATE_KEEP_IMG=1 可保留整份现场)</p>"; } > "$REP" && rm -rf -- "$R"
fi
bash "$HERE/shotgate_gc.sh" "$ROOT" # 超过 SHOTGATE_KEEP_DAYS(缺省 3)天的旧现场自清,KEEP 的不动 | Old run artifacts older than SHOTGATE_KEEP_DAYS (default 3) days are cleaned up automatically; those marked KEEP are left alone
echo "SHOTGATE_ALL $([ $rc = 0 ] && echo OK || echo RED) → $REP"; exit $rc
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# 画面闸门现场的自清:shotgate_gc.sh [根目录] [天数]。删根目录下「超过 N 天没动过」的一级结果目录(名字形如 月日_时分秒…)和 green/ 里同样旧的小结;
# 标了 KEEP 的(宿主截图失败 / 看门狗的现场)不删;想长期留某个现场(文档里引用了它)就在目录里放一个空文件 PIN。缺省根 $DM_ROOT/run/verify/dm/shotgate,缺省 3 天(SHOTGATE_KEEP_DAYS)。shotgate.sh 每次结束时调一次。
# 来由:这里攒了 956 个目录 34 GB 没人清,磁盘两次到线。
# Self-cleanup of screenshot gate artifacts: shotgate_gc.sh [root dir] [days]. Deletes first-level result directories under the root that have "not been touched for more than N days" (named like MMDD_HHMMSS...) and equally old summaries in green/;
# those marked KEEP (artifacts of a failed host screenshot / watchdog) are not deleted; to keep some artifacts long term (a document references them), put an empty file PIN in the directory. Default root $DM_ROOT/run/verify/dm/shotgate, default 3 days (SHOTGATE_KEEP_DAYS). shotgate.sh calls it once at the end of every run.
# Background: 956 directories and 34 GB piled up here with nobody cleaning, and the disk hit the limit twice.
ROOT=${1:-${DM_ROOT:-$HOME/dm-work}/run/verify/dm/shotgate}; DAYS=${2:-${SHOTGATE_KEEP_DAYS:-3}}
case "$ROOT" in */shotgate|*/shotgate/) ;; *) echo "shotgate_gc:根目录不是 shotgate($ROOT),不动"; exit 2;; esac
case "$DAYS" in ''|*[!0-9]*) echo "shotgate_gc:天数不是整数($DAYS),不动"; exit 2;; esac
[ -d "$ROOT" ] || exit 0
n=0
while IFS= read -r d; do
[ -d "$d" ] && [ ! -L "$d" ] && [ ! -e "$d/KEEP" ] && [ ! -e "$d/PIN" ] || continue
rm -rf -- "$d" && n=$((n+1))
done < <(find "$ROOT" -mindepth 1 -maxdepth 1 -type d -name '[0-9][0-9][0-9][0-9]_*' -mtime +"$DAYS" 2>/dev/null)
[ -d "$ROOT/green" ] && find "$ROOT/green" -maxdepth 1 -type f -name '*.html' -mtime +"$DAYS" -delete 2>/dev/null
[ $n -gt 0 ] && echo "shotgate_gc:清掉 $n 个超过 $DAYS 天的旧现场"
exit 0
+95
View File
@@ -0,0 +1,95 @@
{
"page": "局内·自动地图",
"truth": "~/dm-work/data/switch/truth_shots_v7/automap.png",
"host": {
"trigger": "OpenPanel:AutoMap+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,MINUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:AutoMap",
"env": {
"DM_TOWNWP_OFF": "1"
}
},
"viewport": [
0,
0,
1,
0.82
],
"mask": [
[
0.4,
0.17,
0.6,
0.27
],
[
0.36,
0.3,
0.47,
0.52
]
],
"note": "遮罩两处随墙钟 / 随机走的内容:进入营地的红字横幅(淡出时刻两边不同)、游荡 NPC 瓦瑞夫及其名牌。地图线与 NPC 名标、右上图例为静态,区域结构阈值 0.8",
"regions": {
"右上图例(区域名)": {
"rect": [
0.9,
0.03,
1.0,
0.13
],
"ssim_min": 0.8
},
"地图叠加线与 NPC 名标": {
"rect": [
0.55,
0.05,
0.8,
0.4
],
"ssim_min": 0.8
},
"玩家角色": {
"rect": [
0.45,
0.3,
0.54,
0.52
],
"ssim_min": 0.8
},
"生命球": [
0.14,
0.85,
0.26,
1.0
],
"法力球": [
0.74,
0.85,
0.86,
1.0
]
},
"elements": [
{
"name": "右上图例(流亡者营地 / 干燥高地 / 亡者大殿)",
"region": "右上图例(区域名)"
},
{
"name": "地图叠加线与 NPC 名标",
"region": "地图叠加线与 NPC 名标"
},
{
"name": "玩家角色",
"region": "玩家角色"
},
{
"name": "生命球",
"region": "生命球"
},
{
"name": "法力球",
"region": "法力球"
}
]
}
+123
View File
@@ -0,0 +1,123 @@
{
"page": "营地E拍对齐",
"truth": "~/dm-work/data/switch/truth_shots_v7/camp_e.png",
"host": {
"trigger": "DM:Tick:101#+1",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame",
"env": {
"DM_C2S_REPLAY": "~/dm-work/data/switch/truth_runs/camp1/c2s_to_E.jsonl",
"DM_GAME_SEED": "0x12345678",
"DM_FIXED_TIME": "1790000000",
"DM_TICK_HOLD": "101:SHOT",
"DM_POSCHK": "101:5813:4443:32768:32768"
},
"require_log": [
"DM_POSCHK 拍 101 玩家 (5813,4443)/(32768,32768) 真值 (5813,4443)/(32768,32768) 一致",
"冻结拍 101(目标 101)"
]
},
"viewport": [
0,
0,
1,
0.82
],
"mask": [],
"regions": {
"玩家角色": {
"rect": [
0.45,
0.3,
0.54,
0.52
],
"ssim_min": 0.8
},
"篝火": [
0.2,
0.63,
0.38,
0.82
],
"生命球": [
0.14,
0.85,
0.26,
1.0
],
"法力球": [
0.74,
0.85,
0.86,
1.0
],
"马车": {
"rect": [
0.74,
0.1,
0.95,
0.42
],
"ssim_min": 0.8
},
"石墙与帐篷": [
0.1,
0.0,
0.5,
0.3
],
"左上火把": {
"rect": [
0.02,
0.12,
0.08,
0.34
],
"ssim_min": 0.8
}
},
"elements": [
{
"name": "3D 营地(视口非黑)",
"region": "viewport"
},
{
"name": "玩家角色 joe",
"region": "玩家角色"
},
{
"name": "篝火",
"region": "篝火"
},
{
"name": "生命球",
"region": "生命球"
},
{
"name": "法力球",
"region": "法力球"
},
{
"name": "马车",
"region": "马车"
},
{
"name": "石墙与物件",
"region": "石墙与帐篷"
},
{
"name": "左上火把",
"region": "左上火把"
}
],
"dynmask": "~/dm-work/data/switch/shotgate_masks_v2/camp_e.png",
"thresholds": {
"dyn_ssim_min": 0.0
},
"note": "E 拍对齐(新口径):真值 camp1 第 101 拍拍入口发 SHOT 后放行;宿主回放到 E、核站位、冻结、DM:Tick:101#+1 截。动画遮罩 = 宿主冻结下全速 / 慢速两次之差(占视口 23.7%,非弱判);遮罩外细网格 32×18 ≥ 0.6,遮罩内元素靠命名区域 ≥ 0.8。负对照(抹玩家 / 火把 / 马车 / 生命球)全红。",
"fine_grid": [
32,
18,
0.6
]
}
+103
View File
@@ -0,0 +1,103 @@
{
"page": "局内·角色属性",
"truth": "~/dm-work/data/switch/truth_shots_v7/char_stats.png",
"host": {
"trigger": "OpenPanel:CharacterStatsPanel+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,L@%1>OpenPanel:CharacterStatsPanel"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"note": "界面层静态内容:命名区域结构阈值 0.9(宿主对真值实测 ≥0.98)",
"regions": {
"顶部页签": {
"rect": [
0.06,
0.0,
0.94,
0.06
],
"ssim_min": 0.9
},
"角色名与职业等级": {
"rect": [
0.13,
0.1,
0.4,
0.28
],
"ssim_min": 0.9
},
"经验值": {
"rect": [
0.62,
0.2,
0.86,
0.28
],
"ssim_min": 0.9
},
"四项属性": {
"rect": [
0.1,
0.3,
0.35,
0.82
],
"ssim_min": 0.9
},
"攻防生命法力": {
"rect": [
0.35,
0.3,
0.66,
0.82
],
"ssim_min": 0.9
},
"抗性": {
"rect": [
0.68,
0.3,
0.9,
0.56
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "顶部五页签(角色选中)",
"region": "顶部页签"
},
{
"name": "joe 76 级圣骑士",
"region": "角色名与职业等级"
},
{
"name": "经验值",
"region": "经验值"
},
{
"name": "力量 / 敏捷 / 活力 / 能量",
"region": "四项属性"
},
{
"name": "伤害 / 防御 / 耐力 / 生命 / 法力",
"region": "攻防生命法力"
},
{
"name": "四项抗性",
"region": "抗性"
}
],
"fine_grid": [
32,
18,
0.85
]
}
+92
View File
@@ -0,0 +1,92 @@
{
"page": "选角页",
"trigger": "两边:OpenPanel:MainMenuButtonRibbon 后第 150 帧(真值按 30 帧/秒折墙钟);存档 save_ref_warlock_v2",
"viewport": [
0.21,
0.0,
1.0,
0.88
],
"mask": [],
"regions": {
"左侧菜单": [
0.0,
0.0,
0.205,
1.0
],
"角色": [
0.445,
0.15,
0.585,
0.87
],
"篝火": [
0.21,
0.58,
0.27,
0.73
],
"右侧角色框": [
0.665,
0.4,
0.885,
0.5
],
"推广框位置": [
0.215,
0.01,
0.355,
0.22
],
"营地背景": [
0.6,
0.05,
1.0,
0.4
]
},
"elements": [
{
"name": "3D 营地(视口非黑)",
"region": "viewport",
"expect": "有"
},
{
"name": "营地背景(城堡、树)",
"region": "营地背景",
"expect": "有"
},
{
"name": "角色模型(受光,不是剪影)",
"region": "角色",
"expect": "有"
},
{
"name": "篝火与火光",
"region": "篝火",
"expect": "有"
},
{
"name": "左侧菜单",
"region": "左侧菜单",
"expect": "有"
},
{
"name": "右侧角色框(joe 76 级圣骑士)",
"region": "右侧角色框",
"expect": "有"
},
{
"name": "「术士君临现已上线」推广框",
"region": "推广框位置",
"expect": "无(拥有 DLC)"
}
],
"truth": "~/dm-work/data/switch/truth_shots_v7/charselect.png",
"host": {
"trigger": "OpenPanel:MainMenuButtonRibbon+150",
"keys": "",
"env": {"DM_FE_AUTO": "0"}
}
}
+90
View File
@@ -0,0 +1,90 @@
{
"page": "局内·赫拉迪克方块",
"truth": "~/dm-work/data/switch/truth_shots_v7/cube.png",
"host": {
"trigger": "OpenPanel:HoradricCubeLayout+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,LS@%1>OpenPanel:HoradricCubeLayout"
},
"viewport": [
0.06,
0.0,
0.94,
0.97
],
"mask": [],
"fine_grid": [
32,
18,
0.85
],
"note": "界面层静态内容:命名区域结构阈值 0.9,细网格 32×18",
"regions": {
"标题条(赫拉迪克魔盒 / 物品栏)": {
"rect": [
0.07,
0.02,
0.93,
0.07
],
"ssim_min": 0.9
},
"魔盒 3×4 格": {
"rect": [
0.22,
0.32,
0.3,
0.55
],
"ssim_min": 0.9
},
"合成按钮": {
"rect": [
0.26,
0.57,
0.31,
0.65
],
"ssim_min": 0.9
},
"魔盒装饰纹样": {
"rect": [
0.08,
0.1,
0.46,
0.86
],
"ssim_min": 0.8
},
"物品栏(含方块本体)": {
"rect": [
0.52,
0.1,
0.88,
0.82
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "标题「赫拉迪克魔盒 / 物品栏」",
"region": "标题条(赫拉迪克魔盒 / 物品栏)"
},
{
"name": "魔盒格子",
"region": "魔盒 3×4 格"
},
{
"name": "合成按钮",
"region": "合成按钮"
},
{
"name": "魔盒装饰纹样",
"region": "魔盒装饰纹样"
},
{
"name": "物品栏与方块本体",
"region": "物品栏(含方块本体)"
}
]
}
+77
View File
@@ -0,0 +1,77 @@
{
"page": "局内·物品栏",
"truth": "~/dm-work/data/switch/truth_shots_v7/inventory.png",
"host": {
"trigger": "OpenPanel:PlayerInventoryExpansionLayout+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"note": "界面层静态内容:命名区域结构阈值 0.9(宿主对真值实测 ≥0.98)",
"regions": {
"顶部页签": {
"rect": [
0.06,
0.0,
0.94,
0.06
],
"ssim_min": 0.9
},
"装备栏": {
"rect": [
0.35,
0.11,
0.64,
0.56
],
"ssim_min": 0.9
},
"背包格(含赫拉迪克方块)": {
"rect": [
0.35,
0.57,
0.65,
0.8
],
"ssim_min": 0.9
},
"金币": {
"rect": [
0.44,
0.8,
0.56,
0.86
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "顶部五页签(物品栏选中)",
"region": "顶部页签"
},
{
"name": "装备栏(含腰带药水)",
"region": "装备栏"
},
{
"name": "背包与方块、护身符",
"region": "背包格(含赫拉迪克方块)"
},
{
"name": "金币数",
"region": "金币"
}
],
"fine_grid": [
32,
18,
0.85
]
}
+71
View File
@@ -0,0 +1,71 @@
{
"page": "装载画面",
"truth": "~/dm-work/data/switch/truth_shots_v7/loading.png",
"host": {
"trigger": "OpenPanel:LoadScreenPanel+15",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame"
},
"viewport": [
0.29,
0.25,
0.71,
0.75
],
"mask": [
[
0.3,
0.27,
0.7,
0.7
]
],
"regions": {
"读取框边框": [
0.285,
0.245,
0.715,
0.29
],
"读取框内画面": {
"rect": [
0.3,
0.27,
0.7,
0.7
],
"ratio_min": 0,
"ssim_min": 0.5
},
"正在读取": [
0.43,
0.7,
0.57,
0.75
],
"右下角标": [
0.89,
0.82,
0.98,
0.92
]
},
"elements": [
{
"name": "读取框(边框)",
"region": "读取框边框"
},
{
"name": "框内装载动画画面(动画,只核亮度不核结构)",
"region": "读取框内画面"
},
{
"name": "「正在读取」",
"region": "正在读取"
},
{
"name": "右下角 Diablo 标志",
"region": "右下角标"
}
],
"note": "装载框内是修道院大门插画,门开合是按墙钟走的动画(真值实测 +0/+15/+30/+45 帧框内亮度 0.161/0.107/0.299/0.299),宿主装载快、+45 帧时已离开装载画面,两边无法按帧对齐相位(宿主 +15 ≈ 真值 +45 的亮度)。故该区:遮罩出全局结构 / 网格;区域只比结构(≥0.5)、不比亮度。负对照:框内整块变黑 → 结构判红。框外(边框 / 文字 / 角标)照常严比。"
}
+83
View File
@@ -0,0 +1,83 @@
{
"page": "职业选择页",
"truth": "~/dm-work/data/switch/truth_shots_v7/newchar.png",
"host": {
"trigger": "OpenExclusivePanel:CharacterCreatePanel+180",
"keys": "PLUS@OpenPanel:MainMenuButtonRibbon>OpenPanel:OnlinePlayModeModal,DOWN@OpenPanel:OnlinePlayModeModal,A@ControllerActionEnd>OpenExclusivePanel:CharacterCreatePanel"
},
"viewport": [
0,
0,
1,
1
],
"mask": [],
"regions": {
"职业角色一排": [
0.12,
0.31,
0.92,
0.67
],
"篝火": [
0.46,
0.66,
0.54,
0.77
],
"标题": [
0.35,
0.04,
0.65,
0.22
],
"左侧城墙": [
0.0,
0.05,
0.25,
0.45
],
"右侧房屋": [
0.62,
0.05,
1.0,
0.45
],
"选中职业(野蛮人,左起第 4 个)": [
0.4,
0.31,
0.5,
0.67
]
},
"elements": [
{
"name": "3D 场景(视口非黑)",
"region": "viewport"
},
{
"name": "八个职业角色(含术士)",
"region": "职业角色一排"
},
{
"name": "篝火与火光",
"region": "篝火"
},
{
"name": "标题「选择英雄职业 / 野蛮人」",
"region": "标题"
},
{
"name": "城墙背景",
"region": "左侧城墙"
},
{
"name": "房屋背景",
"region": "右侧房屋"
},
{
"name": "选中职业野蛮人(聚光)",
"region": "选中职业(野蛮人,左起第 4 个)"
}
]
}
+137
View File
@@ -0,0 +1,137 @@
{
"page": "NPC 对话页(瓦瑞夫)",
"truth": "~/dm-work/data/switch/truth_shots_v8/npc.png",
"host": {
"trigger": "DM:Tick:103#+30",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,A@DM:Tick:84#>OpenPanel:NpcDialogPanel",
"env": {
"DM_C2S_REPLAY": "~/dm-work/data/switch/truth_runs/npc1/c2s_to_E.jsonl",
"DM_GAME_SEED": "0x12345678",
"DM_FIXED_TIME": "1790000000",
"DM_POSCHK": "83:5806:4453:33359:24778",
"DM_TICK_HOLD": "103:SHOT"
},
"require_log": [
"DM_POSCHK 拍 83 玩家 (5806,4453)/(33359,24778) 真值 (5806,4453)/(33359,24778) 一致",
"冻结拍 103(目标 103)",
"确认「PanelManager:OpenPanel:NpcDialogPanel」"
]
},
"viewport": [
0,
0,
1,
0.86
],
"mask": [],
"regions": {
"对话菜单": {
"rect": [
0.42,
0.22,
0.485,
0.385
],
"ssim_min": 0.8
},
"玩家角色": {
"rect": [
0.42,
0.41,
0.47,
0.56
],
"ssim_min": 0.6
},
"瓦瑞夫": {
"rect": [
0.48,
0.36,
0.525,
0.52
],
"ssim_min": 0.6
},
"马车与木桶": {
"rect": [
0.56,
0.08,
0.7,
0.3
],
"ssim_min": 0.8
},
"篝火": [
0.52,
0.63,
0.73,
0.8
],
"生命球": [
0.14,
0.85,
0.26,
1.0
],
"法力球": [
0.74,
0.85,
0.86,
1.0
],
"生命数值": {
"rect": [
0.24,
0.84,
0.33,
0.885
],
"ssim_min": 0.8
}
},
"elements": [
{
"name": "3D 营地(视口非黑)",
"region": "viewport"
},
{
"name": "对话菜单(瓦瑞夫 / 交谈 / 前往东方 / 取消)",
"region": "对话菜单"
},
{
"name": "玩家角色 joe",
"region": "玩家角色"
},
{
"name": "NPC 瓦瑞夫",
"region": "瓦瑞夫"
},
{
"name": "马车与木桶",
"region": "马车与木桶"
},
{
"name": "篝火",
"region": "篝火"
},
{
"name": "生命球",
"region": "生命球"
},
{
"name": "法力球",
"region": "法力球"
},
{
"name": "生命数值 928/928",
"region": "生命数值"
}
],
"fine_grid": [
32,
18,
0.6
],
"note": "站位硬判据:DM_POSCHK 在 arrive 拍 83 核玩家坐标 = 真值 npc1(events.jsonl),宿主日志须有「一致」行。宿主回放 npc1 命令包到 E(c2s_to_E.jsonl),拍 84 宿主客户端自己按 A(注入交互包客户端不开面板),冻结拍 103 后第 30 帧截:真值在面板打开(约拍 85)后 45 帧 = 0.75 s ≈ 拍 103 截;原写法「OpenPanel+45 帧」不冻结,拍按墙钟走,负载高时 45 帧里多走很多拍,角色 / NPC 位姿随之不同(17 页并行时红)。现与营地 E 拍页同一机制:进入拍 103 冻结客体时钟再截,截到哪一拍与帧率无关;面板须已打开(日志确认行)。 细网格允许 1 格红(fine_red_max):营地有一只客户端环境小动物(鸡,monstats 的 critter 类,不在服务端单位表里——同种子两局拍 103 的 12 个怪物类单位坐标全同、没有它),位置随客户端帧游走,真值与宿主各自随机;走到某格中央时该格结构约 0.58 < 0.6(整跑 5 次红 1 次,与负载无关)。对话菜单 / 角色 / 瓦瑞夫 / 马车 / 篝火 / 血球蓝球 / 生命数值仍由命名区域逐项判。",
"fine_red_max": 1
}
+71
View File
@@ -0,0 +1,71 @@
{
"page": "局内·选项页",
"truth": "~/dm-work/data/switch/truth_shots_v7/options.png",
"host": {
"trigger": "OpenPanel:PauseLayout+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,R@%1>OpenPanel:SkillsTreePanel,R@%1>OpenPanel:PauseLayout"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"regions": {
"顶部页签": [
0.06,
0.0,
0.94,
0.06
],
"菜单六项": {
"rect": [
0.4,
0.16,
0.6,
0.74
],
"ssim_min": 0.9
},
"保存并退出(光标)": {
"rect": [
0.4,
0.48,
0.6,
0.54
],
"ssim_min": 0.9
},
"左右装饰格栅": [
0.08,
0.1,
0.23,
0.85
]
},
"elements": [
{
"name": "顶部五页签(选项选中)",
"region": "顶部页签"
},
{
"name": "菜单六项(转换后角色:含战利品过滤器 / 编年史)",
"region": "菜单六项"
},
{
"name": "光标在「保存并退出」",
"region": "保存并退出(光标)"
},
{
"name": "左右格栅装饰",
"region": "左右装饰格栅"
}
],
"note": "界面层静态内容:命名区域结构阈值收紧到 0.9(宿主对真值实测 1.0)。负对照:未转换角色的四项菜单图在「菜单六项」区 0.641,宽阈值 0.45 会放过",
"fine_grid": [
32,
18,
0.85
]
}
+77
View File
@@ -0,0 +1,77 @@
{
"page": "局内·任务日志",
"truth": "~/dm-work/data/switch/truth_shots_v7/quest_log.png",
"host": {
"trigger": "OpenPanel:QuestLogPanelExpansion+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,L@%1>OpenPanel:CharacterStatsPanel,L@%1>OpenPanel:QuestLogPanelExpansion"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"note": "界面层静态内容:命名区域结构阈值 0.9(宿主对真值实测 ≥0.98)",
"regions": {
"顶部页签": {
"rect": [
0.06,
0.0,
0.94,
0.06
],
"ssim_min": 0.9
},
"幕页签 I–V": {
"rect": [
0.24,
0.11,
0.76,
0.17
],
"ssim_min": 0.9
},
"任务图标": {
"rect": [
0.33,
0.2,
0.66,
0.52
],
"ssim_min": 0.9
},
"任务名与说明": {
"rect": [
0.24,
0.53,
0.76,
0.72
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "顶部五页签(任务日志选中)",
"region": "顶部页签"
},
{
"name": "幕页签 I–V",
"region": "幕页签 I–V"
},
{
"name": "第一幕六个任务图标(完成状态)",
"region": "任务图标"
},
{
"name": "任务名「交易的工具」与说明",
"region": "任务名与说明"
}
],
"fine_grid": [
32,
18,
0.85
]
}
+87
View File
@@ -0,0 +1,87 @@
{
"page": "局内·技能树",
"truth": "~/dm-work/data/switch/truth_shots_v7/skilltree.png",
"host": {
"trigger": "OpenPanel:SkillsTreePanel+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,R@%1>OpenPanel:SkillsTreePanel"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"regions": {
"顶部页签": {
"rect": [
0.06,
0.0,
0.94,
0.06
],
"ssim_min": 0.9
},
"技能树分页签": {
"rect": [
0.31,
0.12,
0.69,
0.17
],
"ssim_min": 0.9
},
"技能图标列": {
"rect": [
0.36,
0.18,
0.62,
0.7
],
"ssim_min": 0.9
},
"技能说明浮窗(精力)": {
"rect": [
0.475,
0.5,
0.635,
0.97
],
"ssim_min": 0.9
},
"左右装饰格栅": [
0.08,
0.1,
0.23,
0.85
]
},
"elements": [
{
"name": "顶部五页签(技能树选中)",
"region": "顶部页签"
},
{
"name": "技能树分页签",
"region": "技能树分页签"
},
{
"name": "技能图标",
"region": "技能图标列"
},
{
"name": "技能说明浮窗(光标悬停精力)",
"region": "技能说明浮窗(精力)"
},
{
"name": "左右格栅装饰",
"region": "左右装饰格栅"
}
],
"note": "界面层静态内容:命名区域结构阈值收紧到 0.9(宿主对真值实测 1.0)。负对照:未转换角色的四项菜单图在「菜单六项」区 0.641,宽阈值 0.45 会放过",
"fine_grid": [
32,
18,
0.85
]
}
+90
View File
@@ -0,0 +1,90 @@
{
"page": "仓库页(高级仓库)",
"truth": "~/dm-work/data/switch/truth_shots_v7/stash.png",
"host": {
"trigger": "OpenPanel:BankExpansionLayout+30",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,A@DM:Tick:66#>OpenPanel:BankExpansionLayout",
"env": {
"DM_C2S_REPLAY": "~/dm-work/data/switch/truth_runs/stash1/c2s_to_arrive.jsonl",
"DM_GAME_SEED": "0x12345678",
"DM_FIXED_TIME": "1790000000",
"DM_POSCHK": "65:5808:4445:26203:15410"
},
"require_log": [
"DM_POSCHK 拍 65 玩家 (5808,4445)/(26203,15410) 真值 (5808,4445)/(26203,15410) 一致"
]
},
"note": "站位硬判据:DM_POSCHK 在拍 65 核玩家坐标 = 真值 arrive(stash1 events.jsonl),宿主日志须出现「一致」行(不一致会带【红】并撤截图)。走位:宿主回放真值局 stash1 的命令包到 arrive 拍 65(坐标 (5808,4445),服务端逐拍等价 ⇒ 站位相同),拍 66 宿主客户端自己按 A(注入交互包客户端不开面板)。早先按时长推摇杆的写法负载下会走偏,已弃。真值:按坐标闭环走到仓库(物件类号 267)按 A;宿主:装载结束后按时长推摇杆走到仓库按 A。面板是界面层,背后营地位姿差异被面板遮住大半。 扩展页签区是静态界面文字,结构阈值收紧到 0.85:普通仓库(只有个人 / 共享)该区为空,须判红(负对照:未转换 joe 的仓库图)。;mask:个人页下方的「第 n/5 页」页码块(个人仓库 2–5 页 dm_pages.c,宿主手柄档带 L / R 键位提示),原版个人页没有这块",
"viewport": [
0.06,
0.03,
0.94,
0.97
],
"mask": [
[
0.19,
0.72,
0.37,
0.78
]
],
"regions": {
"五页签横条": [
0.12,
0.1,
0.46,
0.16
],
"个人仓库格子与物品": [
0.13,
0.17,
0.46,
0.7
],
"物品栏(装备与背包)": [
0.52,
0.1,
0.88,
0.75
],
"标题条": [
0.07,
0.03,
0.93,
0.08
],
"扩展页签(宝石 / 材料 / 符文)": {
"rect": [
0.24,
0.115,
0.42,
0.165
],
"ssim_min": 0.85
}
},
"elements": [
{
"name": "高级仓库五页签(个人 / 共享 / 宝石 / 材料 / 符文)",
"region": "扩展页签(宝石 / 材料 / 符文)"
},
{
"name": "个人仓库与其中物品",
"region": "个人仓库格子与物品"
},
{
"name": "物品栏",
"region": "物品栏(装备与背包)"
},
{
"name": "标题「储藏箱 / 物品栏」",
"region": "标题条"
}
],
"fine_grid": [
32,
18,
0.85
]
}
+100
View File
@@ -0,0 +1,100 @@
{
"page": "局内·术士营地",
"truth": "~/dm-work/data/switch/truth_shots_v7/warlock_camp.png",
"host": {
"trigger": "UnloadPanel:LoadScreenPanel+60",
"keys": "X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@%0.5+0.03>UpdateCharacterInfo,A@%0.5>SelectCharacter,A@%1>FrontEndNavigation:ToGame",
"env": {
"DM_TOWNWP_OFF": "1"
}
},
"viewport": [
0,
0,
1,
0.82
],
"mask": [
[
0.36,
0.3,
0.43,
0.52
]
],
"regions": {
"术士角色": {
"rect": [
0.47,
0.33,
0.53,
0.52
],
"ssim_min": 0.9
},
"篝火": [
0.2,
0.63,
0.38,
0.82
],
"生命球": [
0.14,
0.85,
0.26,
1.0
],
"法力球": [
0.74,
0.85,
0.86,
1.0
],
"马车": [
0.74,
0.1,
0.95,
0.42
],
"技能栏": {
"rect": [
0.27,
0.9,
0.73,
1.0
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "3D 营地(视口非黑)",
"region": "viewport"
},
{
"name": "术士角色",
"region": "术士角色"
},
{
"name": "篝火",
"region": "篝火"
},
{
"name": "生命球",
"region": "生命球"
},
{
"name": "法力球",
"region": "法力球"
},
{
"name": "马车",
"region": "马车"
},
{
"name": "术士技能栏",
"region": "技能栏"
}
],
"note": "术士角色与技能栏结构阈值收紧到 0.9:同位姿换成圣骑士 joe(负对照)时角色区 0.769、技能栏 0.778,宽阈值 0.45 会放过"
}
@@ -0,0 +1,77 @@
{
"page": "局内·术士技能树(DLC)",
"truth": "~/dm-work/data/switch/truth_shots_v7/warlock_skilltree.png",
"host": {
"trigger": "OpenPanel:SkillsTreePanel+45",
"keys": "X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@%0.5+0.03>UpdateCharacterInfo,A@%0.5>SelectCharacter,A@%1>FrontEndNavigation:ToGame,PLUS@UnloadPanel:LoadScreenPanel%1>OpenPanel:PlayerInventoryExpansionLayout,R@%1>OpenPanel:SkillsTreePanel"
},
"viewport": [
0.06,
0.06,
0.94,
0.97
],
"mask": [],
"note": "界面层静态内容:命名区域结构阈值 0.9(宿主对真值实测 ≥0.98)",
"regions": {
"顶部页签": {
"rect": [
0.06,
0.0,
0.94,
0.06
],
"ssim_min": 0.9
},
"术士技能分页签": {
"rect": [
0.31,
0.12,
0.69,
0.17
],
"ssim_min": 0.9
},
"技能图标": {
"rect": [
0.36,
0.18,
0.62,
0.75
],
"ssim_min": 0.9
},
"技能说明浮窗": {
"rect": [
0.47,
0.47,
0.72,
0.99
],
"ssim_min": 0.9
}
},
"elements": [
{
"name": "顶部五页签(技能树选中)",
"region": "顶部页签"
},
{
"name": "术士技能分页签(DLC 专属)",
"region": "术士技能分页签"
},
{
"name": "术士技能图标",
"region": "技能图标"
},
{
"name": "技能说明浮窗",
"region": "技能说明浮窗"
}
],
"fine_grid": [
32,
18,
0.85
]
}
+116
View File
@@ -0,0 +1,116 @@
{
"page": "小站页(传送点 第一幕)",
"truth": "~/dm-work/data/switch/truth_shots_v8/waypoint.png",
"host": {
"trigger": "OpenPanel:WaypointsPanelExpansion+45",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,A@DM:Tick:135#>OpenPanel:WaypointsPanelExpansion",
"env": {
"DM_C2S_REPLAY": "~/dm-work/data/switch/truth_runs/wp1/c2s_to_E.jsonl",
"DM_GAME_SEED": "0x12345678",
"DM_FIXED_TIME": "1790000000",
"DM_POSCHK": "134:5802:4417:4925:44409"
},
"require_log": [
"DM_POSCHK 拍 134 玩家 (5802,4417)/(4925,44409) 真值 (5802,4417)/(4925,44409) 一致"
]
},
"viewport": [
0.065,
0.02,
0.935,
0.965
],
"mask": [],
"regions": {
"标题条": {
"rect": [
0.4,
0.02,
0.6,
0.07
],
"ssim_min": 0.85
},
"幕页签": {
"rect": [
0.24,
0.12,
0.76,
0.18
],
"ssim_min": 0.85
},
"当前小站高亮行": {
"rect": [
0.235,
0.18,
0.765,
0.26
],
"ssim_min": 0.85
},
"已激活小站行": {
"rect": [
0.235,
0.26,
0.765,
0.63
],
"ssim_min": 0.85
},
"未激活行(监牢一层)": {
"rect": [
0.235,
0.63,
0.765,
0.71
],
"ssim_min": 0.85
},
"关闭提示": {
"rect": [
0.46,
0.91,
0.55,
0.96
],
"ssim_min": 0.85
}
},
"elements": [
{
"name": "面板(视口非黑)",
"region": "viewport"
},
{
"name": "标题「传送点」",
"region": "标题条"
},
{
"name": "幕页签 I–V",
"region": "幕页签"
},
{
"name": "当前小站(流亡者营地)高亮",
"region": "当前小站高亮行"
},
{
"name": "已激活小站 5 行",
"region": "已激活小站行"
},
{
"name": "未激活小站(灰色、无图标)",
"region": "未激活行(监牢一层)"
},
{
"name": "B 关闭菜单",
"region": "关闭提示"
}
],
"fine_grid": [
32,
18,
0.85
],
"note": "站位硬判据:DM_POSCHK 在 arrive 拍 134 核玩家坐标 = 真值 wp1,宿主日志须有「一致」行。宿主回放 wp1 命令包到 E,拍 135 自己按 A,OpenPanel:WaypointsPanelExpansion+45 截。面板是界面层、背景压暗;已激活 / 未激活行的区别来自存档里的小站状态(save_ref_warlock_v2 joe),存档错位会红。"
}
+155
View File
@@ -0,0 +1,155 @@
{
"page": "野外页(冰冷之原小站,E 拍对齐)",
"truth": "~/dm-work/data/switch/truth_shots_v9/wild.png",
"host": {
"trigger": "DM:Tick:194#+1",
"keys": "A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,A@DM:Tick:133#>OpenPanel:WaypointsPanelExpansion,DOWN@DM:Tick:142#,A@DM:Tick:150#>ClosePanel:WaypointsPanelExpansion",
"env": {
"DM_C2S_REPLAY": "~/dm-work/data/switch/truth_runs/wild1/c2s_to_arrive.jsonl",
"DM_GAME_SEED": "0x12345678",
"DM_FIXED_TIME": "1790000000",
"DM_TICK_HOLD": "194:SHOT",
"DM_POSCHK": "194:5423:4688:32768:32768"
},
"require_log": [
"DM_POSCHK 拍 194 玩家 (5423,4688)/(32768,32768) 真值 (5423,4688)/(32768,32768) 一致",
"冻结拍 194(目标 194)"
]
},
"viewport": [
0,
0,
1,
0.86
],
"mask": [],
"regions": {
"区域名「进入冰冷之原」": {
"rect": [
0.44,
0.2,
0.56,
0.245
],
"ssim_min": 0.8
},
"小站标签": {
"rect": [
0.47,
0.285,
0.53,
0.365
],
"ssim_min": 0.8
},
"玩家角色": {
"rect": [
0.47,
0.38,
0.53,
0.53
],
"ssim_min": 0.8
},
"小站平台": {
"rect": [
0.36,
0.46,
0.64,
0.65
],
"ssim_min": 0.8
},
"生命球": [
0.14,
0.85,
0.26,
1.0
],
"法力球": [
0.74,
0.85,
0.86,
1.0
],
"生命数值": {
"rect": [
0.24,
0.84,
0.33,
0.885
],
"ssim_min": 0.8
},
"左蓝焰": {
"rect": [
0.42,
0.46,
0.45,
0.53
],
"ssim_min": 0.75
},
"右蓝焰": {
"rect": [
0.545,
0.46,
0.575,
0.53
],
"ssim_min": 0.75
}
},
"elements": [
{
"name": "3D 野外(视口非黑)",
"region": "viewport"
},
{
"name": "进区提示「进入冰冷之原」",
"region": "区域名「进入冰冷之原」"
},
{
"name": "小站标签「冰冷之原 传送点」",
"region": "小站标签"
},
{
"name": "玩家角色 joe",
"region": "玩家角色"
},
{
"name": "小站平台与蓝焰",
"region": "小站平台"
},
{
"name": "生命球",
"region": "生命球"
},
{
"name": "法力球",
"region": "法力球"
},
{
"name": "生命数值",
"region": "生命数值"
},
{
"name": "小站左蓝焰",
"region": "左蓝焰"
},
{
"name": "小站右蓝焰",
"region": "右蓝焰"
}
],
"fine_grid": [
32,
18,
0.6
],
"note": "真值局 wild1(plans/wild_tick.tsv):走到营地小站 arrive 拍 132,A 开小站、拍 142 方向下选冰冷之原、拍 150 A 传送,第 194 拍拍入口截(tickshot)。宿主回放命令包到 arrive(c2s_to_arrive.jsonl),三次按键按真值拍号自己按(客户端面板须客户端自己开),DM_TICK_HOLD=194:SHOT 冻结、DM_POSCHK 194 核站位(= 传送到了冰冷之原),DM:Tick:194#+1 截。 动画遮罩 9.9%(shotgate_masks_v3)。负对照全红:抹进区提示 / 小站标签 / 玩家 / 左蓝焰 / 生命数值、错地点(营地图);站位错走 DM_POSCHK 撤图判「站位不一致」。",
"dynmask": "~/dm-work/data/switch/shotgate_masks_v3/wild.png",
"thresholds": {
"dyn_ssim_min": 0.0
}
}
+558
View File
@@ -0,0 +1,558 @@
# 改写结构核对:不跑代码,逐字核对改写器产物。分母用独立反汇编器(llvm-objdump)重数,不依赖改写器自己的 capstone 扫描。
# 用法:structck.py <改写产物目录> <模块> <NSO> 输出末行 STRUCT <模块> OK|FAIL ...,退出码 0/1
# 核对项:
# ⓪ 已登记剪口(cuts.tsv):构建号对得上,原映像该处 == 原字节、改写映像 == 新字节、理由非空,不与改写点 / 窗口重叠;剪口引入的宿主调用门(svc #N≥0x80)按 hle.h 登记行核号、偏移与形态(入口形 svc;ret 在函数入口 / 调用点形原指令是 bl 且目标符登记)
# ① 非 text 段除剪口外与原映像逐字节相同,映像尾到补丁区之间全 0
# ② text 改动的字 == 改写点头(sites.tsv 非 J 行 + 窗口起点)∪ text 内剪口,改写点头都是跳进补丁区的 B
# ③ 独立分母:llvm-objdump 读原 text,x18/w18 操作数、tpidr_el0 读写、tpidrro_el0 读、svc、cntpct/cntvct
# 全部落在改写点或窗口内;反向,每个改写点都在独立集合里(窗口起点除外)
# ④ 补丁区里不再有 x18/w18、tpidr_el0、svc、cntpct/cntvct
# ⑤ 宿主门(svc / 计时)块逐字等于模板,gates.tsv 一一对上(返回点、种类、svc 号 / 目标寄存器、原地址)
# ⑧ 参数门(params.tsv):原两字为 64 位 movz/movk 造常数、新两字 = mrs tpidrro / ldr 键槽、中间不碰该寄存器、区间无分支目标、键号登记、同键原值唯一
# ⑦ 已登记观测门(obs.tsv):原映像该处 == 登记原指令字;原指令可搬(非 PC 相对 / 非分支 / 不涉 x18 / 不读写系统寄存器,capstone 判);
# 可在函数中间(门 ABI 全存回,gatefn 核);不与改写点 / 窗口 / 剪口重叠;门块逐字 = 模板(svc 门同构前半 + 原指令 + b 回 off+4),gates.tsv 记 obs 行
# ⑩ 跳板出口:每个跳进补丁区的 b,补丁块回 text 的出口只能是 原处+4 / 吸收段尾 / 窗口尾 / 段内原指令的分支目标(已登记剪口放行并列出)
# ⑪ 剪口引入的分支门(hle.h 登记「分支门」行):块逐字 = 模板、两路恢复 x8、gates.tsv 对上
# ⑥ 线程槽:表头四个键号互不相同且 < 512;补丁区每条 mrs xN, tpidrro_el0 之后(跳过不写 xN 的 adrp/add)都是 ldr/str xM,[xN,#键号×8]
# Rewrite structural check: no code is run, the rewriter's build output is checked word by word. Denominators are recounted with an independent disassembler (llvm-objdump), not relying on the rewriter's own capstone scan.
# Usage: structck.py <rewrite build output dir> <module> <NSO> last output line STRUCT <module> OK|FAIL ..., exit code 0/1
# Checks:
# ⓪ Registered cuts (cuts.tsv): build ID matches, original image at that site == original bytes, rewritten image == new bytes, reason non-empty, no overlap with rewrite sites / windows; host-call gates introduced by cuts (svc #N≥0x80) have number, offset and form checked against the hle.h registry row (entry form svc;ret at a function entry / call-site form where the original instruction is bl and the target matches the registration)
# ① Non-text segments are byte-for-byte identical to the original image except for cuts; everything from the end of the image to the patch area is 0
# ② Changed words in text == rewrite site heads (non-J rows of sites.tsv + window starts) ∪ cuts inside text; all rewrite site heads are a B into the patch area
# ③ Independent denominator: llvm-objdump reads the original text; x18/w18 operands, tpidr_el0 reads/writes, tpidrro_el0 reads, svc, cntpct/cntvct
# all fall within rewrite sites or windows; conversely, every rewrite site is in the independent set (except window starts)
# ④ The patch area no longer contains x18/w18, tpidr_el0, svc, cntpct/cntvct
# ⑤ Host gate (svc / timer) blocks equal the template word for word, and match gates.tsv one to one (return point, kind, svc number / destination register, original address)
# ⑧ Parameter gates (params.tsv): the two original words build a constant with 64-bit movz/movk, the two new words = mrs tpidrro / ldr key slot, the register is not touched in between, no branch target in the range, key number registered, a unique original value per key
# ⑦ Registered observation gates (obs.tsv): original image at that site == the registered original instruction word; the original instruction is relocatable (not PC-relative / not a branch / does not involve x18 / does not read or write system registers, judged by capstone);
# may be in the middle of a function (the gate ABI saves and restores everything, checked by gatefn); no overlap with rewrite sites / windows / cuts; the gate block = the template word for word (the same first half as an svc gate + original instruction + b back to off+4), gates.tsv records an obs row
# ⑩ Trampoline exits: for every b jumping into the patch area, the patch block's exits back to text may only be original site+4 / end of the absorbed span / end of the window / a branch target of an original instruction within the span (registered cuts are let through and listed)
# ⑪ Branch gates introduced by cuts (hle.h registry 「分支门」(branch gate) rows): block = template word for word, x8 restored on both paths, matches gates.tsv
# ⑥ Thread slots: the four key numbers in the header are mutually distinct and < 512; every mrs xN, tpidrro_el0 in the patch area is followed (skipping adrp/add that do not write xN) by ldr/str xM,[xN,#key number×8]
import sys, os, re, struct, subprocess, tempfile
sys.path.insert(0, os.path.dirname(__file__))
import nsoimg
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
LLVM = os.environ.get('LLVM_BIN', '/opt/homebrew/opt/llvm@23/bin')
out_dir, mod, nso = sys.argv[1:4]
orig = nsoimg.load(nso)
h = nsoimg.header(out_dir, mod)
PO, TE = h['PATCH_OFF'], h['TEXT_END']
pat = open(f'{out_dir}/{mod}.patched.bin', 'rb').read()
W = lambda b, o: struct.unpack_from('<I', b, o)[0]
fails = []
def bad(msg):
fails.append(msg)
if len(fails) <= 30: print('FAIL', msg)
def llvm_dis(blob, base):
"""按原始字节反汇编,返回相关行 {偏移: 小写指令文本}。 | Disassemble from raw bytes and return the relevant lines {offset: lowercase instruction text}."""
with tempfile.TemporaryDirectory() as td:
b, e = os.path.join(td, 'x.bin'), os.path.join(td, 'x.elf')
open(b, 'wb').write(blob)
subprocess.run([f'{LLVM}/llvm-objcopy', '-I', 'binary', '-O', 'elf64-littleaarch64',
'--rename-section', '.data=.text,code', b, e], check=True)
# 只留可能相关的行(x18/w18、tpidr、svc、cnt?ct),几百万行的筛选交给 grep
# Keep only potentially relevant lines (x18/w18, tpidr, svc, cnt?ct); filtering millions of lines is left to grep
od = subprocess.Popen([f'{LLVM}/llvm-objdump', '-d', '--no-show-raw-insn', e], stdout=subprocess.PIPE)
r = subprocess.run(['/usr/bin/grep', '-iE', r'[xw]18|tpidr|svc|cnt[pv]ct'], stdin=od.stdout, capture_output=True, text=True)
od.stdout.close(); assert od.wait() == 0
out = {}
for line in r.stdout.splitlines():
m = re.match(r'\s*([0-9a-f]+):\s+(.*)$', line)
if m: out[base + int(m.group(1), 16)] = m.group(2).split('//')[0].split('<')[0].strip().lower()
return out
RX18 = re.compile(r'\b[xw]18\b')
def sysk(t):
if re.match(r'svc\s', t): return 'svc'
if re.match(r'mrs\s', t) and 'tpidr_el0' in t: return 'tpidr_r'
if re.match(r'msr\s', t) and 'tpidr_el0' in t: return 'tpidr_w'
if re.match(r'mrs\s', t) and 'tpidrro_el0' in t: return 'tpidrro_r'
if re.match(r'mrs\s', t) and 'cntpct_el0' in t: return 'cntpct'
if re.match(r'mrs\s', t) and 'cntvct_el0' in t: return 'cntvct'
return None
# ---- sites.tsv ----
sites = {}; wins = []; jumps = 0
for l in open(f'{out_dir}/{mod}.sites.tsv'):
f = l.split(); a = int(f[0], 16)
if f[1] == 'J': jumps += 1; continue
if f[1] == 'W': wins.append((a, int(f[2], 16))); sites[a] = 'W'
else: sites[a] = f[1]
inwin = set(o for lo, hi in wins for o in range(lo, hi, 4))
# ⓪ 已登记剪口
# ⓪ Registered cuts
cuts = []; bid = None
for l in open(f'{out_dir}/{mod}.cuts.tsv'):
if l.startswith('# BUILD_ID'): bid = l.split()[-1]; continue
f = l.rstrip('\n').split('\t')
if len(f) == 4: f = f[:3] + ['全'] + f[3:] # 旧 4 列格式:作用域缺省「全」 | Old 4-column format: scope defaults to 「全」(all)
off, ob, nb, scope, why = f[:5]
if scope not in ('全', '仅宿主'): bad(f'剪口 {off} 作用域不认识:{scope}')
cuts.append((int(off, 16), bytes.fromhex(ob), bytes.fromhex(nb), why))
if bid != open(nso, 'rb').read(0x50)[0x40:0x50].hex(): bad(f'cuts.tsv 构建号 {bid} 与 NSO 不符')
cutb = set()
for off, ob, nb, why in cuts:
if orig[off:off + len(ob)] != ob: bad(f'剪口 {off:#x} 原字节不符')
for k in range(0, len(nb), 4): # 新字节里的 svc 字随后被改写成门(头是 B),按改写点核,这里跳过 | The svc words in the new bytes are subsequently rewritten into gates (head is B) and checked as rewrite sites; skipped here
if int.from_bytes(nb[k:k + 4], 'little') & 0xFFE0001F == 0xD4000001: continue
if pat[off + k:off + k + len(nb[k:k + 4])] != nb[k:k + 4]: bad(f'剪口 {off:#x}+{k} 改写映像不是新字节'); break
if not why.strip() or len(ob) != len(nb): bad(f'剪口 {off:#x} 理由为空或长度不等')
cutb |= set(range(off, off + len(ob)))
# 剪口产生的宿主调用门:剪口新字节里解出 svc #N 的那个字(N ≥ 0x80,须在 hle.h 宿主调用号登记表 SVC_HOST_*)
# Host-call gates produced by cuts: the word in the cut's new bytes that decodes to svc #N (N ≥ 0x80, must be in the hle.h host-call number registry SVC_HOST_*)
_hostcall = {}
_reg = {int(v, 16) for v in re.findall(r'SVC_HOST_\w+\s*=\s*(0x[0-9a-fA-F]+)', open(os.path.join(os.path.dirname(__file__), '..', 'host', 'hle.h')).read())}
for off, ob, nb, why in cuts:
for k in range(0, len(nb), 4):
w = int.from_bytes(nb[k:k + 4], 'little')
if w & 0xFFE0001F == 0xD4000001:
n = (w >> 5) & 0xFFFF; a = off + k
if n < 0x80: bad(f'剪口 {off:#x} 引入 svc #{n:#x}:0x80 以下是 Horizon 号段,剪口不得占用')
elif n not in _reg: bad(f'剪口 {off:#x} 引入 svc #{n:#x}:未在 hle.h 宿主调用号登记表')
elif sites.get(a) != 'svc': bad(f'剪口 {off:#x} 引入的 svc #{n:#x} 没被改写成宿主门(sites.tsv 无 {a:#x} svc)')
_hostcall[a] = n
# 宿主调用门的形态按 hle.h 登记表那一行核(「号 … 剪口(main 偏移)」列):
# 入口形(「…入口」):新字节 = svc #N ; ret,偏移是 eh_frame 函数入口——门保存恢复 x30,ret 回原调用者;
# 调用点形(「bl 0x目标 …」):原指令必须是 bl 且目标 = 登记目标,新字节 = 单条 svc #N,门返回 off+4(⑤ 模板的末条 b 核)。
# 调用点形的寄存器理由:bl 处按 AAPCS 被调函数本可破坏 x9..x17、x16/x17、x30 与 NZCV,所以门在这些上的副作用不改变调用方可见行为;
# x0..x7 返回值与 x19..x28 / sp 由宿主门契约保持(gatefn 逐门核)。
# The form of a host-call gate is checked against its row in the hle.h registry (the 「号 … 剪口(main 偏移)」(number ... cut (main offset)) column):
# entry form (「…入口」(... entry)): new bytes = svc #N ; ret, the offset is an eh_frame function entry - the gate saves and restores x30, ret returns to the original caller;
# call-site form (「bl 0x目标 …」(bl 0x<target> ...)): the original instruction must be bl with target = the registered target, new bytes = a single svc #N, the gate returns to off+4 (checked by the final b of the ⑤ template).
# Register rationale for the call-site form: at a bl, per AAPCS the callee could clobber x9..x17, x16/x17, x30 and NZCV anyway, so the gate's side effects on these do not change caller-visible behavior;
# the x0..x7 return values and x19..x28 / sp are preserved by the host gate contract (checked gate by gate by gatefn).
_hreg = {}
for l in open(os.path.join(os.path.dirname(__file__), '..', 'host', 'hle.h'), encoding='utf-8'):
m = re.match(r'//\s+(0x[0-9a-fA-F]+)\s.*?\s(0x[0-9a-fA-F]+)(([^)]*)', l)
if m: _hreg[int(m[1], 16)] = (int(m[2], 16), m[3])
def _bl(w, o): return o + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000) if w & 0xFC000000 == 0x94000000 else None
for a, n in _hostcall.items():
if n not in _hreg: bad(f'宿主调用 svc #{n:#x}:hle.h 登记表没有对应行'); continue
roff, form = _hreg[n]
if mod != 'main' or roff != a: bad(f'宿主调用 svc #{n:#x} 在 {mod} {a:#x},登记表写 main {roff:#x}'); continue
nbw = next(c[2] for c in cuts if c[0] <= a < c[0] + len(c[2]))
mt = re.search(r'\bbl (0x[0-9a-fA-F]+)', form)
if mt:
t = _bl(W(orig, a), a)
if t is None: bad(f'宿主调用 svc #{n:#x} {a:#x}:登记为调用点形,原指令 {W(orig, a):#010x} 不是 bl')
elif t != int(mt[1], 16): bad(f'宿主调用 svc #{n:#x} {a:#x}:原 bl 目标 {t:#x} ≠ 登记 {mt[1]}')
if len(nbw) != 4: bad(f'宿主调用 svc #{n:#x} {a:#x}:调用点形剪口只许换这一条指令')
elif '入口' in form:
if a not in set(nsoimg.func_starts(orig, TE)): bad(f'宿主调用 svc #{n:#x} {a:#x}:登记为入口形,不是 eh_frame 函数入口')
if nbw[4:8] != (0xD65F03C0).to_bytes(4, 'little'): bad(f'宿主调用 svc #{n:#x} {a:#x}:入口形新字节不是 svc ; ret')
else: bad(f'宿主调用 svc #{n:#x}:登记表形态认不出(须含「bl 0x目标」或「入口」):{form}')
if cutb & {a + i for a in list(sites) + list(inwin) if a not in _hostcall for i in range(4)}: bad('剪口与改写点 / 窗口重叠')
ncut_code = sum(1 for c in cuts if c[0] < TE); ncut_data = len(cuts) - ncut_code
obs = []
obs_p = f'{out_dir}/{mod}.obs.tsv'
if os.path.exists(obs_p):
for l in open(obs_p, encoding='utf-8'):
if l.startswith('# BUILD_ID'):
if l.split()[-1] != open(nso, 'rb').read(0x50)[0x40:0x50].hex(): bad('obs.tsv 构建号与 NSO 不符')
continue
off, oid, ow, why = l.rstrip('\n').split('\t', 3); obs.append((int(off, 16), int(oid), int(ow, 16), why))
obs_heads = {o for o, *_ in obs}
params = [] # 参数门(params.tsv,r11 起):(A 偏移, B 偏移, 寄存器号, 键名) | Parameter gates (params.tsv, since r11): (A offset, B offset, register number, key name)
par_p = f'{out_dir}/{mod}.params.tsv'
if os.path.exists(par_p):
for l in open(par_p, encoding='utf-8'):
if l.startswith('# BUILD_ID'):
if l.split()[-1] != open(nso, 'rb').read(0x50)[0x40:0x50].hex(): bad('params.tsv 构建号与 NSO 不符')
continue
a, b, r, k, why = l.rstrip('\n').split('\t', 4)
if not why.strip(): bad(f'参数门 {a} 理由为空')
params.append((int(a, 16), int(b, 16), int(r.lstrip('x')), k))
par_words = {o for a, b, r, k in params for o in (a, b)}
# ① 非 text 段:先整块比,块不同再逐字节,差异只许落在剪口里(剪口字节已在 ⓪ 按应有值核过)
# ① Non-text segments: compare whole blocks first, then byte by byte where blocks differ; differences may only fall inside cuts (cut bytes were already checked against their expected values in ⓪)
nd = []
for blk in range(TE, len(orig), 4096):
e = min(blk + 4096, len(orig))
if pat[blk:e] != orig[blk:e]: nd += [o for o in range(blk, e) if pat[o] != orig[o] and o not in cutb]
if nd: bad(f'非 text 段与原映像不同(剪口以外){len(nd)} 字节 例 {[hex(x) for x in nd[:5]]}')
if any(pat[len(orig):PO]): bad('映像尾到补丁区之间非 0')
# ② text 改动 == 改写点头
# ② text changes == rewrite site heads
diff = set()
for blk in range(0, TE & ~3, 4096): # 先整块比,块不同再逐字 | Compare whole blocks first, then word by word where blocks differ
e = min(blk + 4096, TE & ~3)
if orig[blk:e] != pat[blk:e]: diff |= {o for o in range(blk, e, 4) if W(orig, o) != W(pat, o)}
heads = set(sites)
cutw = {o & ~3 for o in cutb if o < TE}
_exp = (heads | obs_heads | par_words) - cutw; _got = diff - cutw # 剪口里的宿主调用门头在剪口字节里,按剪口核 | Host-call gate heads inside cuts are within the cut bytes and are checked as cuts
if _got != _exp: bad(f'text 改动与改写点不一致:多改 {len(_got - _exp)} 漏改 {len(_exp - _got)} 例 {[hex(x) for x in sorted(_got ^ _exp)[:5]]}')
def btarget(o):
w = W(pat, o)
if w & 0xFC000000 != 0x14000000: return None
imm = w & 0x3FFFFFF
if imm & 0x2000000: imm -= 0x4000000
return o + 4 * imm
nb = [a for a in heads | obs_heads if not (btarget(a) is not None and PO <= btarget(a) < len(pat))]
if nb: bad(f'改写点头不是跳进补丁区的 B:{len(nb)} 例 {[hex(x) for x in nb[:5]]}')
# ③ 独立分母
# ③ Independent denominator
def cached_dis(blob):
"""原映像是固定数据:相关行按 sha 缓存(llvm 换版本另起键),只在首次付反汇编的十来秒。 | The original image is fixed data: relevant lines are cached by sha (a new llvm version gets a new key), so the ten-odd seconds of disassembly are paid only the first time."""
import hashlib, json
cd = os.environ.get('DM_VCACHE', os.path.join(DM_ROOT, 'build/cache/dm/verify'))
ver = os.path.basename(os.path.dirname(LLVM.rstrip('/')))
p = os.path.join(cd, f'{mod}.{hashlib.sha256(blob).hexdigest()[:16]}.{ver}.json')
if os.path.exists(p): return {int(k): v for k, v in json.load(open(p)).items()}
d = llvm_dis(blob, 0)
os.makedirs(cd, exist_ok=True); tmp = f'{p}.new.{os.getpid()}'; json.dump(d, open(tmp, 'w')); os.replace(tmp, p)
return d
D = cached_dis(orig[:TE])
ind = {}
for o, t in D.items():
if RX18.search(t): ind[o] = 'x18'
k = sysk(t)
if k: ind[o] = k
miss = sorted(o for o in ind if o not in sites and o not in inwin)
if miss: bad(f'独立反汇编有、改写点没覆盖:{len(miss)} 例 {[(hex(x), D[x]) for x in miss[:5]]}')
extra = sorted(a for a, k in sites.items() if k != 'W' and a not in ind and a not in _hostcall) # 剪口引入的 svc 不在原映像里 | The svc introduced by a cut is not in the original image
if extra: bad(f'改写点不在独立集合里:{len(extra)} 例 {[(hex(x), D.get(x)) for x in extra[:5]]}')
kmis = sorted(a for a, k in sites.items() if k != 'W' and a in ind and ind[a] != k)
if kmis: bad(f'改写点种类与独立判读不同:{len(kmis)} 例 {[(hex(x), sites[x], D[x]) for x in kmis[:5]]}')
nwin_ref = sum(1 for o in ind if o in inwin)
# ④ 补丁区干净
# ④ Patch area is clean
P = llvm_dis(pat[PO:], PO)
left = sorted(o for o, t in P.items() if RX18.search(t) or sysk(t) not in (None, 'tpidrro_r'))
if left: bad(f'补丁区残留 x18/系统寄存器/svc:{len(left)} 例 {[(hex(x), P[x]) for x in left[:5]]}')
# ⑤ 宿主门
# ⑤ Host gates
KEY = {k[4:-4]: v for k, v in h.items() if k.startswith('KEY_') and k.endswith('_IDX')}
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
_md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); _md.detail = True
def keyseq(at):
q = list(_md.disasm(pat[at:at + 20], at))
if len(q) < 5 or q[0].mnemonic != 'mrs' or 'tpidrro_el0' not in q[0].op_str \
or q[1].mnemonic != 'adrp' or q[1].operands[1].imm != h['KEY_PAGE_OFF'] \
or q[2].mnemonic != 'ldr' or q[2].operands[1].mem.base != q[1].operands[0].reg \
or q[3].mnemonic != 'add' or q[3].operands[0].reg != q[0].operands[0].reg \
or q[3].operands[1].reg != q[0].operands[0].reg:
return None
d = q[2].operands[1].mem.disp
return (q[3].address + 4, d // 8) if d % 8 == 0 and 0 <= d // 8 < 8 else None
def paramseq(at, r):
q = list(_md.disasm(pat[at:at + 40], at))
tmp = 17 if r == 16 else 16
rn = lambda ins, i: ins.reg_name(ins.operands[i].reg)
if len(q) < 8 or q[0].mnemonic not in ('stur', 'str') or rn(q[0], 0) != f'x{tmp}' \
or q[0].operands[1].mem.base != capstone.arm64_const.ARM64_REG_SP or q[0].operands[1].mem.disp not in (-16, -24) \
or q[1].mnemonic != 'mrs' or rn(q[1], 0) != f'x{r}' \
or 'tpidrro_el0' not in q[1].op_str or q[2].mnemonic != 'adrp' \
or q[2].operands[1].imm != h['KEY_PAGE_OFF'] or q[3].mnemonic != 'ldr' \
or q[3].operands[1].mem.base != q[2].operands[0].reg or q[4].mnemonic != 'add' \
or q[4].operands[0].reg != q[1].operands[0].reg or q[4].operands[1].reg != q[1].operands[0].reg \
or q[5].mnemonic != 'ldr' or q[5].operands[0].reg != q[1].operands[0].reg \
or q[5].operands[1].mem.base != q[4].operands[0].reg or q[6].mnemonic not in ('ldur', 'ldr') \
or rn(q[6], 0) != f'x{tmp}' \
or q[6].operands[1].mem.base != capstone.arm64_const.ARM64_REG_SP \
or q[6].operands[1].mem.disp != q[0].operands[1].mem.disp or q[7].mnemonic != 'b':
return None
d = q[3].operands[1].mem.disp
return (q[6].address + 4, d // 8)
gates = {}
for l in open(f'{out_dir}/{mod}.gates.tsv'):
r, k, arg, oa = l.split(); gates[int(r, 16)] = (k, int(arg), int(oa, 16))
def B(frm, to): return 0x14000000 | (((to - frm) >> 2) & 0x3FFFFFF)
# 门块 blr 前须有 ldr x29,[sp]:键页取槽借用的 x29 还原成客体原值,宿主读到的 x29 才是真帧指针(r26,见 patch_nso emit_gate_call)
# The gate block must have ldr x29,[sp] before blr: the x29 borrowed for fetching the slot via the key page is restored to the guest's original value, so the x29 the host reads is the real frame pointer (r26, see patch_nso emit_gate_call)
LDR_X29_SP = 0xF94003FD
gsites = sorted(a for a, k in sites.items() if k in ('svc', 'cntpct', 'cntvct'))
seen = set()
for a in gsites:
s = btarget(a); ow = W(orig, a) if a not in _hostcall else (0xD4000001 | _hostcall[a] << 5)
ks = keyseq(s + 4)
if W(pat, s) != 0xA9BF7BFD or not ks or ks[1] != KEY.get('KGATE') \
or W(pat, ks[0]) & 0xFFC00000 != 0xF9400000 or W(pat, ks[0] + 4) != LDR_X29_SP or W(pat, ks[0] + 8) != 0xD63F03C0 \
or W(pat, ks[0] + 12) != 0xA8C17BFD or W(pat, ks[0] + 16) != B(ks[0] + 16, a + 4):
bad(f'门块不符键页模板 {a:#x}'); continue
arg = (ow >> 5) & 0xFFFF if sites[a] == 'svc' else ow & 31
g = gates.get(ks[0] + 12)
if g != (sites[a], arg, a): bad(f'gates.tsv 不符 {a:#x}:表 {g} 期望 {(sites[a], arg, a)}')
seen.add(ks[0] + 12)
# ⑦ 观测门
# ⑦ Observation gates
import bisect as _bs
_starts = set(nsoimg.func_starts(orig, TE))
_busy = {a + i for a in list(sites) + list(inwin) for i in range(4)} | cutb
for off, oid, ow, why in obs:
if W(orig, off) != ow: bad(f'观测门 {off:#x} 原指令字不符:映像 {W(orig, off):08x} 登记 {ow:08x}'); continue
ins = next(_md.disasm(struct.pack('<I', ow), off), None)
m = ins.mnemonic if ins else '?'
if ins is None or m in ('adr', 'adrp', 'b', 'bl', 'br', 'blr', 'ret', 'cbz', 'cbnz', 'tbz', 'tbnz', 'svc', 'mrs', 'msr', 'eret') or m.startswith('b.') \
or (m.startswith('ldr') and '[' not in ins.op_str) or RX18.search(ins.op_str or ''):
bad(f'观测门 {off:#x} 原指令不可搬:{m} {ins.op_str if ins else ""}')
# 不再要求函数入口:_dm_gate 存回 x0–x17、x19–x30、q0–q31 与 NZCV/FPSR/FPCR,函数中间的活寄存器不受影响;
# 这条 ABI 由 gatefn 功能核(桩故意破坏 x9–x17 与 NZCV,核全部恢复),不在这里按位置近似
# Function entry is no longer required: _dm_gate saves and restores x0–x17, x19–x30, q0–q31 and NZCV/FPSR/FPCR, so live registers in the middle of a function are unaffected;
# this ABI is checked functionally by gatefn (the stub deliberately clobbers x9–x17 and NZCV, and full restoration is checked), not approximated here by position
if set(range(off, off + 4)) & _busy: bad(f'观测门 {off:#x} 与改写点 / 窗口 / 剪口重叠')
s_ = btarget(off)
if s_ is None or not (PO <= s_ < len(pat)): bad(f'观测门头 {off:#x} 不是跳进补丁区的 B'); continue
ks = keyseq(s_ + 4)
if W(pat, s_) != 0xA9BF7BFD or not ks or ks[1] != KEY.get('KGATE') \
or W(pat, ks[0]) & 0xFFC00000 != 0xF9400000 or W(pat, ks[0] + 4) != LDR_X29_SP or W(pat, ks[0] + 8) != 0xD63F03C0 \
or W(pat, ks[0] + 12) != 0xA8C17BFD or W(pat, ks[0] + 16) != ow \
or W(pat, ks[0] + 20) != B(ks[0] + 20, off + 4):
bad(f'观测门块不符键页模板 {off:#x}'); continue
if gates.get(ks[0] + 12) != ('obs', oid, off): bad(f'观测门行不符 {off:#x}:表 {gates.get(ks[0] + 12)}')
seen.add(ks[0] + 12)
# ⑪ 剪口引入的分支门(hle.h 登记表形态「分支门:x8≠0 跳 0x目标,否则执行原指令回 0x原处+4」):原处换成 B 进补丁区,块逐字 =
# stp x8,xzr,[sp,#-16]! ; stp x29,x30,[sp,#-16]! ; 键页取 KGATE ; ldr x30,[x30] ; ldr x29,[sp] ; blr x30 ; ldp x29,x30 ; cbz w8,+12 ;
# ldp x8,xzr ; b 目标 ; ldp x8,xzr ; 原指令 ; b 原处+4 —— x8 两路都恢复为原值,宿主结果只用于选路;gates.tsv 记 (svc, 号, 原处)
# ⑪ Branch gates introduced by cuts (hle.h registry form 「分支门:x8≠0 跳 0x目标,否则执行原指令回 0x原处+4」(branch gate: x8≠0 jumps to 0x<target>, otherwise executes the original instruction and returns to 0x<original site>+4)): the original site is replaced with a B into the patch area, and the block equals word for word
# stp x8,xzr,[sp,#-16]! ; stp x29,x30,[sp,#-16]! ; fetch KGATE via key page ; ldr x30,[x30] ; ldr x29,[sp] ; blr x30 ; ldp x29,x30 ; cbz w8,+12 ;
# ldp x8,xzr ; b target ; ldp x8,xzr ; original instruction ; b original site+4 - x8 is restored to its original value on both paths, the host result is only used to pick the path; gates.tsv records (svc, number, original site)
nbranch = 0
for n, (roff, form) in _hreg.items():
if not form.startswith('分支门'): continue
cut = next((c for c in cuts if c[0] == roff), None)
if cut is None: continue # 本产物没开这扇私有门 | This build output does not enable this private gate
mt, mb = re.search(r'跳 (0x[0-9a-fA-F]+)', form), re.search(r'回 (0x[0-9a-fA-F]+)', form)
if not mt or not mb or int(mb[1], 16) != roff + 4: bad(f'分支门 svc #{n:#x}:登记表形态缺跳转目标或回点 ≠ 原处+4:{form}'); continue
tgt = int(mt[1], 16); s_ = btarget(roff); ks = keyseq(s_ + 8) if s_ is not None else None
if s_ is None or not (PO <= s_ < len(pat)) or W(pat, s_) != 0xA9BF7FE8 or W(pat, s_ + 4) != 0xA9BF7BFD or not ks or ks[1] != KEY.get('KGATE') \
or W(pat, ks[0]) & 0xFFC00000 != 0xF9400000 or W(pat, ks[0] + 4) != LDR_X29_SP or W(pat, ks[0] + 8) != 0xD63F03C0 or W(pat, ks[0] + 12) != 0xA8C17BFD \
or W(pat, ks[0] + 16) != 0x34000068 or W(pat, ks[0] + 20) != 0xA8C17FE8 or W(pat, ks[0] + 24) != B(ks[0] + 24, tgt) \
or W(pat, ks[0] + 28) != 0xA8C17FE8 or W(pat, ks[0] + 32) != W(orig, roff) or W(pat, ks[0] + 36) != B(ks[0] + 36, roff + 4):
bad(f'分支门 svc #{n:#x} {roff:#x}:块不符模板'); continue
if gates.get(ks[0] + 12) != ('svc', n, roff): bad(f'分支门 svc #{n:#x} gates.tsv 行不符:{gates.get(ks[0] + 12)}')
seen.add(ks[0] + 12); nbranch += 1
if set(gates) != seen: bad(f'gates.tsv 有多余行 {len(set(gates) - seen)}')
# ⑥ 线程槽
# ⑥ Thread slots
_base = {'K18', 'KTLS', 'KTLR', 'KGATE'}; _extra = set(KEY) - _base # 额外键 = 参数门键(KRES* / KASPECT* …;改写器全局键表,三模块表头都列):须是 K 开头大写名、键号低于基础四键 | Extra keys = parameter-gate keys (KRES* / KASPECT* ...; the rewriter's global key table, listed in the headers of all three modules): must be uppercase names starting with K, with key numbers below the four base keys
if set(KEY) != {'K18', 'KTLS', 'KTLR', 'KGATE', 'KRES0', 'KRES1', 'KASPECT', 'KASPECTUI'} \
or not {k for *_, k in params} <= set(KEY) or set(KEY.values()) != set(range(8)):
bad(f'表头键页下标不合规:{KEY}(须含八个键且下标恰为 0..7)')
kv = {v: k for k, v in KEY.items()}; nk = {}
for o in range(PO, len(pat) - 4, 4):
w = W(pat, o)
if w & 0xFFFFFFE0 != 0xD53BD060: continue # mrs xN, tpidrro_el0
n = w & 31; ks = keyseq(o); k = kv.get(ks[1]) if ks else None
if not ks or k is None:
bad(f'补丁区 {o:#x} 读 tpidrro 后不是键页间接槽序列'); continue
nk[k] = nk.get(k, 0) + 1
expected = {}
for kind in sites.values():
key = {'x18': 'K18', 'W': 'K18', 'tpidr_r': 'KTLS', 'tpidr_w': 'KTLS', 'tpidrro_r': 'KTLR'}.get(kind)
if key: expected[key] = expected.get(key, 0) + 1
expected['KGATE'] = len(gsites) + len(obs) + nbranch
for _, _, _, key in params: expected[key] = expected.get(key, 0) + 1
if any(nk.get(k, 0) != v for k, v in expected.items()) or any(k not in expected and v for k, v in nk.items()):
bad(f'键页槽访问计数不符:期望 {expected} 实际 {nk}')
# ⑧ 参数门(PARAMS,仅宿主):原处 movz xR,#lo / movk xR,#hi,lsl #32 造的 64 位常数,等长换成 mrs xR,tpidrro_el0 / ldr xR,[xR,#键*8]
# 核:A 原字是 64 位 movz(hw=0)写 xR、B 原字是 64 位 movk(hw=2)写 xR;新字逐位 = 模板;A、B 之间的指令不读写 xR;
# (A, B] 不是任何直接分支的目标、也不是函数入口(否则从中间进来的路径会拿到槽指针而不是常数);键号在表头登记;不与改写点 / 剪口 / 观测门重叠。
# 宿主给槽原值(宽高打包 = 下列常数)时语义与原两条逐位等价:B 之后 xR 同值,A、B 之间无人读 xR。
# ⑧ Parameter gates (PARAMS, host only): a 64-bit constant originally built by movz xR,#lo / movk xR,#hi,lsl #32 is replaced at equal length by mrs xR,tpidrro_el0 / ldr xR,[xR,#key*8]
# Checks: original word A is a 64-bit movz (hw=0) writing xR, original word B is a 64-bit movk (hw=2) writing xR; the new words = the template bit for bit; instructions between A and B do not read or write xR;
# (A, B] is not the target of any direct branch nor a function entry (otherwise a path entering in the middle would get the slot pointer instead of the constant); the key number is registered in the header; no overlap with rewrite sites / cuts / observation gates.
# When the host gives the slot the original value (packed width/height = the constants below), the semantics are bit-for-bit equivalent to the original two instructions: xR has the same value after B, and nobody reads xR between A and B.
par_const = {}
if params:
import capstone
_cs = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM); _cs.detail = True
_tg = set()
for o in range(0, TE & ~3, 4): # 全 text 直接分支目标 | Direct branch targets across all of text
w = W(orig, o)
if w & 0x7C000000 == 0x14000000: d = ((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000; _tg.add(o + 4 * d)
elif w & 0xFF000010 == 0x54000000 or w & 0x7E000000 == 0x34000000: d = (((w >> 5) & 0x7FFFF) ^ 0x40000) - 0x40000; _tg.add(o + 4 * d)
elif w & 0x7E000000 == 0x36000000: d = (((w >> 5) & 0x3FFF) ^ 0x2000) - 0x2000; _tg.add(o + 4 * d)
_fs = set(nsoimg.func_starts(orig, TE))
_busy8 = {a for a in sites} | set(inwin) | obs_heads | {o & ~3 for o in cutb}
for a, b, r, k in params:
wa, wb = W(orig, a), W(orig, b)
# 两种原指令对:64 位 movz xR,#lo / movk xR,#hi,lsl #32(KRES*);32 位 movz wR,#lo / movk wR,#hi,lsl #16(KASPECT*,原值 = hi<<16|lo,
# 写 w 寄存器高 32 位清零 ⇒ 宿主槽须按 u32 位模式存、高 32 位为 0(运行期约束,静态核不到,见 platform thread.c)
# Two kinds of original instruction pair: 64-bit movz xR,#lo / movk xR,#hi,lsl #32 (KRES*); 32-bit movz wR,#lo / movk wR,#hi,lsl #16 (KASPECT*, original value = hi<<16|lo,
# writing a w register zeroes the upper 32 bits ⇒ the host slot must be stored as a u32 bit pattern with the upper 32 bits 0 (a runtime constraint that cannot be checked statically, see platform thread.c)
w64 = wa & 0xFFE00000 == 0xD2800000 and wb & 0xFFE00000 == 0xF2C00000
w32 = wa & 0xFFE00000 == 0x52800000 and wb & 0xFFE00000 == 0x72A00000
if not (w64 or w32) or wa & 31 != r or wb & 31 != r:
bad(f'参数门 {a:#x}/{b:#x}:原指令 {wa:#010x}/{wb:#010x} 不是 movz/movk 造常数对(64 位 lsl #32 或 32 位 lsl #16)写 x{r}')
if not a < b: bad(f'参数门 {a:#x}/{b:#x} 顺序不对')
if k not in KEY: bad(f'参数门 {a:#x} 键 {k} 未在表头登记'); continue
s = btarget(a); ks = paramseq(s, r) if s is not None else None
ok = ks and ks[1] == KEY[k] and W(pat, b) == 0xD503201F
if not ok: bad(f'参数门 {a:#x}/{b:#x}:键页间接模板不符')
for o in range(a + 4, b, 4):
ins = next(_cs.disasm(orig[o:o + 4], o), None)
if ins is None: bad(f'参数门 {a:#x}:中间 {o:#x} 解不出'); continue
rr, ww = ins.regs_access()
names = {ins.reg_name(x) for x in rr + ww}
if f'x{r}' in names or f'w{r}' in names: bad(f'参数门 {a:#x}:中间 {o:#x} {ins.mnemonic} {ins.op_str} 读写 x{r}')
bt = sorted(t for t in _tg if a < t <= b) + sorted(t for t in _fs if a < t <= b)
if bt: bad(f'参数门 {a:#x}..{b:#x}:区间内有分支目标 / 函数入口 {[hex(x) for x in bt[:4]]}')
if {a, b} & _busy8: bad(f'参数门 {a:#x}/{b:#x} 与改写点 / 窗口 / 观测门 / 剪口重叠')
par_const[(a, k)] = ((wb >> 5) & 0xFFFF) << (16 if w32 else 32) | ((wa >> 5) & 0xFFFF)
_kc = {}
for (a, k), v in par_const.items(): _kc.setdefault(k, set()).add(v)
for k, vs in _kc.items():
if len(vs) != 1: bad(f'参数门键 {k} 对应多个原常数 {[hex(v) for v in vs]}(同一槽给不出唯一原值)')
print('参数门 ' + ', '.join(f'{a:#x}={k}:原值 {v:#x}' for (a, k), v in par_const.items()))
# 参数寄存器的下游不得再被常数掩码:编译器会把「值只可能是这几个常数」折进后续指令——运行模式通知处理 0xe10e48 的
# mov w9,#0x740; and x9,x25,x9 就是 1280|1600 推出的掩码,换成参数后宽度被掩成 768 / 64。从每个参数位起按函数内线性顺序做污点传播
# (mov / csel 类传递,其余写入清除;不跟分支,属保守近似),被污染的寄存器遇到 and / ands / bic 且另一操作数是立即数或 mov 立即数造的寄存器即报
# Downstream of a parameter register there must be no further masking by a constant: the compiler folds "the value can only be one of these constants" into later instructions - in the operation mode notification handler at 0xe10e48,
# mov w9,#0x740; and x9,x25,x9 is exactly a mask derived from 1280|1600, and once replaced by a parameter the width gets masked to 768 / 64. From each parameter site, do taint propagation in linear order within the function
# (mov / csel kinds propagate, other writes clear; branches are not followed, a conservative approximation); report when a tainted register meets and / ands / bic whose other operand is an immediate or a register built by a mov immediate
_fsl = sorted(_fs)
def _rn(ins, x): return re.sub(r'^[wx]', '', ins.reg_name(x)) if re.match(r'^[wx]\d+$', ins.reg_name(x) or '') else None
_donef = set()
for a, b, r, k in params:
import bisect as _bi
i = _bi.bisect_right(_fsl, a); f0 = _fsl[i - 1]; f1 = _fsl[i] if i < len(_fsl) else TE
if f0 in _donef: continue
_donef.add(f0)
seeds = {(pa, str(pr)) for pa, pb, pr, pk in params if f0 <= pa < f1}
taint, const = set(), {}
for o in range(f0, f1, 4):
for pa, pr in seeds:
if o == pa: taint.add(pr)
if any(o == pa for pa, _ in seeds): continue
ins = next(_cs.disasm(pat[o:o + 4], o), None)
if ins is None: continue
rr, ww = ins.regs_access(); rd = {x for x in (_rn(ins, q) for q in rr) if x}; wr = {x for x in (_rn(ins, q) for q in ww) if x}
m = ins.mnemonic
if m in ('and', 'ands', 'bic', 'bics') and rd & taint:
imm = any(op.type == capstone.arm64.ARM64_OP_IMM for op in ins.operands)
if imm or (rd - taint) & set(const): bad(f'参数门下游常数掩码 {o:#x}:{m} {ins.op_str}(函数 {f0:#x},被参数寄存器污染的值再被常数掩码)')
if m in ('mov', 'csel', 'csinc', 'csinv', 'csneg') and rd & taint: taint |= wr; [const.pop(x, None) for x in wr]
else:
taint -= wr
isimm = m in ('mov', 'movz') and len(ins.operands) == 2 and ins.operands[1].type == capstone.arm64.ARM64_OP_IMM
for x in wr:
if isimm: const[x] = ins.operands[1].imm
else: const.pop(x, None)
# ⑨ 临时寄存器静态检查:每个补丁块的非原指令目的寄存器必须有同偏移红区存取配对。
# ⑨ Static check of temporary registers: every non-original-instruction destination register in a patch block must have a matching red-zone save/restore pair at the same offset.
import capstone
def _writes(ins):
_, ww = ins.regs_access()
return {'x29' if ins.reg_name(r) == 'fp' else 'x30' if ins.reg_name(r) == 'lr' else re.sub(r'^[wx]', 'x', ins.reg_name(r))
for r in ww if ins.reg_name(r) not in ('sp', 'pc')}
def _mem_sp(ins, load):
if (load and not ins.mnemonic.startswith('ld')) or (not load and not ins.mnemonic.startswith('st')):
return None
for op in ins.operands:
if op.type == capstone.arm64_const.ARM64_OP_MEM and ins.reg_name(op.mem.base) == 'sp':
if op.mem.disp < 0: return op.mem.disp
if load and ins.mnemonic == 'ldp' and op.mem.disp == 0: return -16
return None
def _block(start):
out = []
for ins in _md.disasm(pat[start:start + 256], start):
out.append(ins)
if ins.mnemonic == 'b':
t = ins.operands[0].imm
if not (PO <= t < len(pat)): break
return out
static_entries = [(a, set()) for a in sites]
for a, b, r, _ in params:
static_entries.append((a, {f'x{r}'}))
static_seen = 0
for a, allowed in static_entries:
s = btarget(a)
if s is None: continue
block = _block(s); static_seen += 1
if not allowed:
end = next((hi for lo, hi in wins if lo == a), a + 4)
for ins in _md.disasm(orig[a:end], a): allowed |= _writes(ins)
if next(_md.disasm(orig[a:a + 4], a), None).mnemonic in ('stp', 'ldp'):
allowed.update(('x0', 'x1'))
saved = {}
restored = {}
for i, ins in enumerate(block):
d = _mem_sp(ins, False)
if d is not None:
regs = [op.reg for op in ins.operands[:2] if op.type == capstone.arm64_const.ARM64_OP_REG]
for reg in regs:
name = ins.reg_name(reg); name = 'x29' if name == 'fp' else 'x30' if name == 'lr' else re.sub(r'^[wx]', 'x', name)
saved.setdefault(name, []).append((d, i))
d = _mem_sp(ins, True)
if d is not None:
regs = [op.reg for op in ins.operands[:2] if op.type == capstone.arm64_const.ARM64_OP_REG]
for reg in regs:
name = ins.reg_name(reg); name = 'x29' if name == 'fp' else 'x30' if name == 'lr' else re.sub(r'^[wx]', 'x', name)
restored.setdefault(name, []).append((d, i))
writes = set().union(*(_writes(ins) for ins in block)) if block else set()
for reg in sorted(writes - allowed):
wi = [i for i, ins in enumerate(block) if reg in _writes(ins) and not (i > 0 and _mem_sp(ins, True) is not None)]
dead = any(ins.mnemonic in ('br', 'blr') and ins.operands and ins.reg_name(ins.operands[0].reg) in (reg, reg[1:]) for ins in block)
ok = dead or any(sd == rd and si < min(wi, default=10**9) and ri > max(wi, default=-1)
for sd, si in saved.get(reg, []) for rd, ri in restored.get(reg, []))
if not ok: bad(f'临时寄存器 {a:#x}:块写 {reg},原目的寄存器外且无同偏移存取配对')
print(f'STATIC {mod} scanned={static_seen} violations={sum(1 for x in fails if x.startswith("临时寄存器"))}')
# ⑩ 跳板出口(切掌机崩溃:参数门跳板回到 B+4,越过 A、B 之间未改的原指令和另一个跳板头):
# text 里每条跳进补丁区的 b(跳板头 a)沿补丁块走遍全部回 text 的出口(顺序 b 与条件分支,bl 视为返回,ret / br 不算回 text)。
# 合法出口:a+4;越过的字全是被改写吸收的字(≠ 原字且不是别的跳板头,如参数门 B 处的 nop)后的地址;
# 窗口(W 行 [lo, hi))头:hi 与窗口内原指令自己的分支目标;非窗口头:连续吸收段内原指令自己的分支目标。
# ⑩ Trampoline exits (the handheld-switch crash: the parameter-gate trampoline returned to B+4, skipping the unmodified original instructions between A and B and another trampoline head):
# for every b in text that jumps into the patch area (trampoline head a), follow the patch block through all exits back to text (sequential b and conditional branches; bl is treated as returning; ret / br do not count as returning to text).
# Legal exits: a+4; the address after skipped words that are all words absorbed by the rewrite (≠ the original word and not another trampoline head, e.g. the nop at parameter-gate B);
# window (W row [lo, hi)) heads: hi and the branch targets of the original instructions inside the window; non-window heads: the branch targets of the original instructions inside the contiguous absorbed span.
_heads = {o for o in range(0, TE & ~3, 4) if W(pat, o) & 0xFC000000 == 0x14000000 and btarget(o) is not None and btarget(o) >= PO}
_wend = dict(wins)
def _bt(w, o):
if w & 0x7C000000 == 0x14000000: return o + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000)
if w & 0xFF000010 == 0x54000000 or w & 0x7E000000 == 0x34000000: return o + 4 * ((((w >> 5) & 0x7FFFF) ^ 0x40000) - 0x40000)
if w & 0x7E000000 == 0x36000000: return o + 4 * ((((w >> 5) & 0x3FFF) ^ 0x2000) - 0x2000)
return None
def _exits(start):
ex, seen, st = set(), set(), [start]
while st:
o = st.pop()
while o not in seen and o + 4 <= len(pat):
seen.add(o); w = W(pat, o)
if w & 0xFC000000 == 0x14000000:
t = _bt(w, o)
if t < PO: ex.add(t); break
o = t; continue
if w & 0xFC000000 == 0x94000000: o += 4; continue
if w == 0xD65F03C0 or w & 0xFFFFFC1F == 0xD61F0000: break
t = _bt(w, o)
if t is not None:
if t < PO: ex.add(t)
else: st.append(t)
o += 4
return ex
nexit = 0; _cutoff = {c[0] for c in cuts}; _cutex = []
for a in sorted(_heads):
if a in _wend:
seg = range(a, _wend[a], 4); legal = {_wend[a]}
else:
e = a + 4
while e < TE and W(pat, e) != W(orig, e) and e not in _heads: e += 4
seg = range(a, e, 4); legal = {a + 4 * k for k in range(1, len(seg) + 1)}
legal |= {t for o in seg for t in [_bt(W(orig, o), o)] if t is not None}
for t in _exits(btarget(a)):
nexit += 1
if t not in legal and a in _cutoff: _cutex.append(f'{a:#x}→{t:#x}'); continue # 已登记剪口(带理由,故意改控制流):放行并列出 | Registered cuts (with a reason, deliberately changing control flow): let through and listed
if t not in legal: bad(f'跳板出口 {a:#x} → {t:#x}:既不是 {a + 4:#x} / 吸收段尾 / 窗口尾,也不是段内原指令的分支目标(越过未改原指令或别的跳板头)')
print(f'EXITS {mod} 跳板头={len(_heads)} 出口={nexit} 已登记剪口改控制流出口={_cutex}')
cnt = {}
if _hostcall: print(f'剪口引入宿主调用门 {len(_hostcall)} 个:' + ', '.join(f"{a:#x}=svc#{n:#x}" for a, n in _hostcall.items()))
for k in sites.values(): cnt[k] = cnt.get(k, 0) + 1
print(f'STRUCT {mod} {"OK" if not fails else "FAIL"} 改写点={len(sites)} {cnt} 跳转表={jumps} 窗口内x18引用={nwin_ref} '
f'已登记剪口={len(cuts)}(代码{ncut_code}/数据{ncut_data}) 观测门={len(obs)} 参数门={len(params)} '
f'独立分母={len(ind)} text改动字={len(diff)} 门={len(gsites)} 槽访问={nk} 失败项={len(fails)}')
sys.exit(1 if fails else 0)
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""只验证快/全档接线与失败传播;替身输出不冒充游戏验收。 | Verifies only the fast/full tier wiring and failure propagation; stand-in output does not pass for game acceptance."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
class AcceptTests(unittest.TestCase):
def setUp(self):
root = Path(DM_ROOT) / 'run/verify/dm/accept_tests'
root.mkdir(parents=True, exist_ok=True)
self.tmp = tempfile.TemporaryDirectory(dir=root)
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.verify = self.root / 'dm/verify'
(self.verify / 'shotgate_pages').mkdir(parents=True)
(self.root / 'dm-work/run/verify/dm').mkdir(parents=True)
self.trace = self.root / 'trace'
self.env = dict(os.environ, HOME=str(self.root), DM_ROOT=str(self.root / 'dm-work'), LC_ALL='C', TRACE=str(self.trace))
src = Path(os.environ.get('ACCEPT_SOURCE', Path(__file__).with_name('accept.sh')))
shutil.copyfile(src, self.verify / 'accept.sh')
self.write('dm-work/build/cache/dm/venv/bin/python', 'echo "替身 plan test OK"\n')
self.write('dm/verify/bootchk.sh', 'echo BOOTLIST OK\n')
self.write('dm/verify/regress.sh', 'echo REGRESS OK\n')
self.write('dm/verify/test_accept.py', 'import unittest\nclass T(unittest.TestCase):\n def test(self): pass\n') # ④ 里 accept 自身单测的替身(防递归) | Stand-in for accept's own unit tests in ④ (prevents recursion)
self.write('dm/ios/run.sh', 'echo "替身 iOS 构建 $*"\n') # ⑧ iOS 构建项的替身 | ⑧ Stand-in for the iOS build item
self.write('dm/verify/opmode.sh', 'echo "OPMODE ${OPMODE_RES:-OK} 替身"; [ "${OPMODE_RES:-OK}" = OK ]\n') # ⑩ 局内切运行模式的替身 | ⑩ Stand-in for the in-game operation mode switch
self.write('dm/verify/touchchain.sh', 'echo "TOUCHCHAIN $1 OK 用时 0 秒"\n')
gen = self.root / 'dm/ios/tools/gen_romfs_overlay.py'; gen.parent.mkdir(parents=True, exist_ok=True) # ⑨ 起跑前生成界面覆盖层的替身(python 脚本,不走 write 的 bash 头) | ⑨ Stand-in for generating the UI overlay before the run (a python script, not using write's bash header)
gen.write_text('import os, sys\nif os.environ.get("GEN_RC"): sys.exit("替身:覆盖层生成失败")\nos.makedirs(sys.argv[2], exist_ok=True)\n')
for case in ['move', 'inv_tap', 'inv_long_press']:
case_dir = self.verify / 'touchcases' / case
case_dir.mkdir(parents=True)
(case_dir / 'script.txt').write_text('# fixture\n')
(case_dir / 'assert.py').write_text('# fixture\n')
self.write('dm/verify/shotgate.sh', 'echo "shot:$*" >> "$TRACE"; echo SHOTGATE_ALL OK\n')
self.write('dm/verify/logred.sh', 'printf "0\\t\\n"\n')
self.write('dm/tools/host_savecmp.sh',
'mkdir -p "$HOME/host"; printf "DM_TACT_PREFETCH:命中 %s\\n下一拍时限 0 → %s\\n" "${PF_HIT:-4000}" "${LAG_INC:-250}" > "$HOME/host/host.log"; echo "局目录 $HOME/host"; echo SAVECMP 一致\n')
self.write('dm/tools/save_txn_regress.sh',
'echo txn >> "$TRACE"; echo "结论:存档事务回归 4/4 绿"; exit "${TXN_RC:-0}"\n')
for tree in ['host', 'gfx']:
p = self.root / f'dm/{tree}/tests'; p.mkdir(parents=True)
(p / 'Makefile').write_text('run:\n\t@echo OK\n')
p = self.root / 'dm/ios/tests'; p.mkdir(parents=True) # iOS 触摸层单测(accept ④ 第六套)的替身 | Stand-in for the iOS touch layer unit tests (accept ④, sixth suite)
(p / 'Makefile').write_text('test:\n\t@echo OK\n')
(self.root / 'dm/host/Makefile').write_text(
'all:\n\t@test "$${HOST_BUILD_RC:-0}" = 0\n'
'\t@echo built >> "$$HOME/build-count"\n'
'\t@touch "$$HOME/host-built"\n')
for p in ['camp_e', 'stash', 'wild', 'charselect', 'skilltree', 'npc']:
(self.verify / f'shotgate_pages/{p}.json').write_text('{}')
def write(self, rel, body):
p = self.root / rel; p.parent.mkdir(parents=True, exist_ok=True)
p.write_text('#!/bin/bash\n' + body); p.chmod(0o755)
def run_accept(self, *args, **env):
self.env.update(env)
return subprocess.run(['bash', str(self.verify / 'accept.sh'), *args],
env=self.env, capture_output=True, text=True, errors='replace', timeout=10)
def test_fast_has_only_five_pages_and_no_transaction(self):
r = self.run_accept('--fast', '/fixture/out')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(self.trace.read_text().strip(), 'shot:/fixture/out camp_e stash wild charselect skilltree')
def test_full_runs_transaction_and_propagates_its_failure(self):
r = self.run_accept('--full', '/fixture/out', TXN_RC='1')
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertIn('txn', self.trace.read_text())
self.assertTrue(list((self.root / 'dm-work/run/verify/dm/accept').glob('*/KEEP')))
def test_default_keeps_full_coverage(self):
r = self.run_accept('/fixture/out')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn('txn', self.trace.read_text())
self.assertIn('npc', r.stdout)
def test_pending_case_skipped_but_listed(self):
# 待接入用例(目录里有 pending)不跑、不算分母,但必须在读数里列出,不静默
# Cases awaiting hookup (a pending file in the directory) are not run and not counted in the denominator, but must be listed in the readings, never silently
d = self.verify / 'touchcases' / 'slow_prefix'
d.mkdir(parents=True)
for n in ('script.txt', 'assert.py'): (d / n).write_text('# fixture\n')
(d / 'pending').write_text('等前缀不限速\n')
r = self.run_accept('--fast', '/fixture/out')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn('FUNC 3/3', r.stdout)
self.assertIn('FUNCPENDING 待接入 1 例:slow_prefix:等前缀不限速', r.stdout)
self.assertNotIn('FUNCCASE slow_prefix', r.stdout)
def test_prefetch_hit_is_report_only(self):
# 预取命中取决于预取线程调度,只报不判;清单对不对归 ⓪ 静态核对
# Prefetch hits depend on prefetch thread scheduling: reported only, not judged; whether the list is right belongs to the ⓪ static check
r = self.run_accept('--fast', '/fixture/out', PF_HIT='2999')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn('预取命中 2999 块(只报不判)', r.stdout)
def test_lag_below_range_is_red(self):
r = self.run_accept('--fast', '/fixture/out', LAG_INC='199')
self.assertEqual(r.returncode, 1)
self.assertIn('LAGRANGE 空跑', r.stdout)
def test_overlay_generation_failure_is_red(self):
r = self.run_accept('--fast', '/fixture/out', GEN_RC='1')
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertIn('界面覆盖层生成失败', r.stdout)
def test_opmode_failure_is_red(self):
r = self.run_accept('--fast', '/fixture/out', OPMODE_RES='RED')
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertIn('⑩ 局内切运行模式', r.stdout)
self.assertIn('OPMODE RED', r.stdout)
def test_host_built_once_before_parallel_runtime_checks(self):
self.write('dm/verify/shotgate.sh',
'test -f "$HOME/host-built" || exit 27; echo SHOTGATE_ALL OK\n')
self.write('dm/tools/host_savecmp.sh',
'test -f "$HOME/host-built" || exit 27; mkdir -p "$HOME/host"; '
'printf "DM_TACT_PREFETCH:命中 4000\\n下一拍时限 0 → 250\\n" > "$HOME/host/host.log"; '
'echo "局目录 $HOME/host"; echo SAVECMP 一致\n')
r = self.run_accept('--fast', '/fixture/out')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual((self.root / 'build-count').read_text().splitlines(), ['built'])
def test_host_build_failure_stops_all_runtime_children(self):
r = self.run_accept('/fixture/out', HOST_BUILD_RC='1')
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertFalse(self.trace.exists(), '宿主构建失败后不得启动画面或事务子项')
self.assertTrue(list((self.root / 'dm-work/run/verify/dm/accept').glob('*/KEEP')))
if __name__ == '__main__': unittest.main(verbosity=2)
+73
View File
@@ -0,0 +1,73 @@
# Per-Tick Game State Hash Format
中文:[tick_state_format.zh-CN.md](tick_state_format.zh-CN.md)
The game's server-side logic advances in "ticks" (each tick processes all units once). Before each tick begins, the key fields of all units in the game are computed into a few hashes and recorded as one line; if the two sides are identical tick by tick, the game logic has run exactly the same way. The two sides are the **ground truth** (reference data obtained by running the original game in a patched Ryujinx emulator) and the **host** (`dmhost` from `dm/host`). Both sides run the same Switch version 3.3.94012 program, and are compared byte by byte.
- Ground-truth side: `dm/verify/oracle/swtick.py` reads it through the emulator's GDB interface, and it is written as `<run dir>/ticks.jsonl` when a run is recorded. The emulator driver scripts used for recording are not shipped with the repository, so the checks that depend on ground truth cannot be run with this repository alone.
- Host side: enabled by the environment variable `DM_TICKS=<path>`; with `DM_TICKS_N=<tick count>` it exits normally once that many have been recorded; `DM_TICKS_FULL=1` additionally outputs per-unit detail.
- Comparison: two `ticks.jsonl` files are aligned by tick number and the first differing tick number is reported for each slot; with fewer than 10 common ticks no conclusion is drawn. The comparison script `selfcmp.py` belongs to the emulator driver scripts and is not shipped with the repository.
## Capture point and base address
- **Capture point**: the server tick entry `main + 0x5d3bc0`, taken before the first instruction of the entry executes (the tick number has not yet been incremented).
- **Base address G** = `x0` at entry. G is the game object, embedded in a game hash-table node: G = node + 0x10 (node = the result of looking up the ID from the slot array `main + 0x2d665d8` in the hash table `*(main + 0x2d685e0)`).
**All offsets in this document are relative to G**: the `+0x1b8` that the game-creation function `0x5d0bd0` writes relative to the node is `G + 0x1a8` here.
- **Tick number** = `u32 [G+0x170]` (read at entry, equal to the value before this tick begins).
- Each tick number is taken only once (the emulator reports the same breakpoint hit repeatedly; deduplicate by tick number); tick numbers must be consecutive one by one, and a gap is reported red.
## One line of JSON per tick
```
{"tick":39,"n":[4,12,24,0,21],"h":["…16 lowercase hex digits…" ×6],"bad":0}
```
- `n`: the counts of the 5 unit classes (0 player / 1 monster / 2 object / 3 missile / 4 item).
- `h`: 6 hash slots (5 unit classes + global seed).
- `bad`: the number of unit pointers that could not be read + the number of units whose self-reported type does not match the table they are in.
- Other fields (game, dt, reads) are for human reading only and take no part in the comparison.
## Unit tables and fields
All offsets are relative to the start of their respective structure.
| Class t | Table | Notes |
|---|---|---|
| 0 player | G+0x2230 | Each table has 128 buckets (u64 pointers), each bucket a singly linked list `next = [u + 0x158]`, at most 4096 per chain |
| 1 monster | G+0x2630 | |
| 2 object | G+0x2a30 | |
| 3 missile | G+0x3230 | Note that the table order and addresses of 3 and 4 are not monotonic |
| 4 item | G+0x2e30 | |
Fields of unit u:
| Field | How to read |
|---|---|
| type, cls, id, mode | u32 [u+0x0], [u+0x4], [u+0x8], [u+0xC] |
| act | u8 [u+0x18] |
| rlo, rhi (unit seed) | u32 [u+0x28], [u+0x2C] |
| Coordinates (t = 0/1/3 only) | path = u64 [u+0x38]; u16 xf=[path+0], x=[path+2], yf=[path+4], y=[path+6]; when path is 0 or unreadable all four are taken as 0; for the other classes all four are always 0 |
| statlist (t = 0/1/4) | sl = u64 [u+0x88]; arr = u64 [sl+0x30], cnt = u32 [sl+0x38]; take min(cnt, 96) entries, each 8 bytes as-is (u32 a = layer<<16 \| statId, u32 b = value) |
| Item extras (t = 4 only) | d = u64 [u+0x10]; iq=[d+0x0], is_lo=[d+0x4], is_hi=[d+0x8], iflags=[d+0x18], iinit=[d+0x10] (u32); when d is 0 all five are taken as 0 |
## Hash
FNV-1a 64, offset basis `0xcbf29ce484222325`, multiplier `0x100000001b3`, byte by byte, all numeric values as little-endian u32.
1. The hash of each class t starts from the offset basis; all units are sorted by (type, id) ascending and then folded in turn into the slot corresponding to their type (those with type ≥ 5 are not counted).
2. Each unit folds in, in order:
- 9 u32: type, cls, id, mode, act, x, y, xf, yf
- 2 u32: rlo, rhi
- t = 4 only: 5 u32: iq, is_lo, is_hi, iflags, iinit
- t = 0/1/4 only: u32 entry count, then each entry's 8 bytes as-is
3. Slot 6 (global seed) = the offset basis with the 8 bytes of `[G+0x1a8]` folded in (u32 lo + u32 hi as-is).
4. Output is a string of 16 lowercase hex digits.
## Determinism (the precondition for comparison)
For the two sides to be identical tick by tick, the inputs must be identical:
- **Game-creation seed**: the game-creation function `0x5d0bd0` reads `u32 [main + 0x20a0074]`; when it is ≠ `0xffffffff` the seed = {that value, 666}, otherwise it is taken from the system clock. Both sides must write the same value before game creation: on the ground-truth side the driver script's `--game-seed N`, host `DM_GAME_SEED=N`.
- **Game-creation time**: the system time is read once at game creation. On the ground-truth side the driver script's `--fix-time <seconds>`, host `DM_FIXED_TIME=<seconds>`; give the same value.
- **Save**: both sides each start from a fresh copy of the same standard save (`$DM_ROOT/data/switch/save_ref_warlock`); the save content fingerprint is computed with `dm/verify/savesha.sh` and noted down before the run.
- **Input**: the input the client sends to the server always follows the command packet sequence recorded from the ground truth (see [command_packet_format.md](command_packet_format.md)). Both command packets and **system-class messages** (`0x6d` heartbeat, `0x6f` progress, etc.) must have their original bytes injected at their original tick numbers, and messages of the same kind produced by the host itself are discarded (the `0x67` join at game entry is let through as usual). The tick number at which a system-class message arrives depends on how fast the client is; among them `0x6f` determines when the server inserts a sync, so it is timing-dependent input; without injecting it the per-tick state will not match.
+73
View File
@@ -0,0 +1,73 @@
# 逐拍游戏状态哈希格式
English: [tick_state_format.md](tick_state_format.md)
游戏的服务端逻辑按「拍」推进(每拍处理一次全部单位)。每一拍开始前,把游戏里全部单位的关键字段算成几个哈希、记一行;两边逐拍相同,就说明游戏逻辑走得一模一样。两边指**真值**(用打了补丁的 Ryujinx 模拟器跑原版游戏得到的参照数据)与**宿主**(`dm/host` 的 `dmhost`)。两边跑的是同一份 Switch 版 3.3.94012 程序,逐字节比。
- 真值侧:`dm/verify/oracle/swtick.py` 经模拟器的 GDB 接口读,录一局时写成 `<局目录>/ticks.jsonl`。录制用的模拟器驱动脚本不随仓库提供,所以依赖真值的检查在仓库外跑不了。
- 宿主侧:环境变量 `DM_TICKS=<路径>` 打开;`DM_TICKS_N=<拍数>` 记满即正常退出;`DM_TICKS_FULL=1` 另出逐单位明细。
- 对拍:两份 `ticks.jsonl` 按拍号对齐,报每一格首个不同的拍号;共同拍数 < 10 不下结论。对拍脚本 `selfcmp.py` 属于模拟器驱动脚本那一组,不随仓库提供。
## 采集点与基址
- **采集点**:服务端拍入口 `main + 0x5d3bc0`,在入口第一条指令执行之前取(拍号尚未自增)。
- **基址 G** = 入口处的 `x0`。G 是游戏对象,嵌在游戏哈希表节点里:G = 节点 + 0x10(节点 = 槽数组 `main + 0x2d665d8` 的 ID 查哈希表 `*(main + 0x2d685e0)` 所得)。
**本文所有偏移都以 G 为基址**:建局函数 `0x5d0bd0` 以节点为基址写的 `+0x1b8`,就是这里的 `G + 0x1a8`。
- **拍号** = `u32 [G+0x170]`(入口处读,等于本拍开始前的值)。
- 同一拍号只取一次(模拟器会重复报告同一次断点命中,按拍号去重);拍号必须逐一连续,断档报红。
## 每拍一行 JSON
```
{"tick":39,"n":[4,12,24,0,21],"h":["…16 位小写十六进制…" ×6],"bad":0}
```
- `n`:5 类单位的个数(0 玩家 / 1 怪 / 2 物件 / 3 飞弹 / 4 物品)。
- `h`:6 格哈希(5 类单位 + 全局种子)。
- `bad`:读不到的单位指针数 + 自报类型与所在表不符的单位数。
- 其他字段(game、dt、reads)只供人看,不参与对拍。
## 单位表与字段
偏移全部相对各自结构的起点。
| 类 t | 表 | 说明 |
|---|---|---|
| 0 玩家 | G+0x2230 | 每表 128 个桶(u64 指针),桶内单链 `next = [u + 0x158]`,每链最多 4096 |
| 1 怪 | G+0x2630 | |
| 2 物件 | G+0x2a30 | |
| 3 飞弹 | G+0x3230 | 注意 3、4 的表序与地址不单调 |
| 4 物品 | G+0x2e30 | |
单位 u 的字段:
| 字段 | 读法 |
|---|---|
| type, cls, id, mode | u32 [u+0x0], [u+0x4], [u+0x8], [u+0xC] |
| act | u8 [u+0x18] |
| rlo, rhi(单位种子) | u32 [u+0x28], [u+0x2C] |
| 坐标(仅 t = 0/1/3) | path = u64 [u+0x38];u16 xf=[path+0], x=[path+2], yf=[path+4], y=[path+6];path 为 0 或读不到时四项都取 0;其余类四项恒 0 |
| statlist(t = 0/1/4) | sl = u64 [u+0x88];arr = u64 [sl+0x30],cnt = u32 [sl+0x38];取 min(cnt, 96) 项,每项 8 字节原样(u32 a = 层<<16 \| statId,u32 b = 值) |
| 物品附加(仅 t = 4) | d = u64 [u+0x10];iq=[d+0x0],is_lo=[d+0x4],is_hi=[d+0x8],iflags=[d+0x18],iinit=[d+0x10](u32);d 为 0 时五项取 0 |
## 哈希
FNV-1a 64,偏移基 `0xcbf29ce484222325`,乘数 `0x100000001b3`,逐字节,数值一律小端 u32。
1. 每类 t 的哈希从偏移基起;全部单位按 (type, id) 升序后依次并入其 type 对应的格(type ≥ 5 的不计)。
2. 每个单位依次并入:
- 9 个 u32:type, cls, id, mode, act, x, y, xf, yf
- 2 个 u32:rlo, rhi
- 仅 t = 4:5 个 u32:iq, is_lo, is_hi, iflags, iinit
- 仅 t = 0/1/4:u32 项数,再逐项 8 字节原样
3. 第 6 格(全局种子)= 偏移基并入 8 字节 `[G+0x1a8]`(u32 lo + u32 hi 原样)。
4. 输出为 16 位小写十六进制字符串。
## 确定性(对拍的前提)
两边要逐拍相同,输入必须相同:
- **建局种子**:建局函数 `0x5d0bd0` 读 `u32 [main + 0x20a0074]`;≠ `0xffffffff` 时种子 = {该值, 666},否则取系统时钟。两边须在建局前写同一个值:真值侧是驱动脚本的 `--game-seed N`,宿主 `DM_GAME_SEED=N`。
- **建局时刻**:建局时读一次系统时间。真值侧是驱动脚本的 `--fix-time <秒>`,宿主 `DM_FIXED_TIME=<秒>`,给同一个值。
- **存档**:两边各用同一份标准存档(`$DM_ROOT/data/switch/save_ref_warlock`)的新副本开局;存档内容指纹用 `dm/verify/savesha.sh` 算,跑前记下。
- **输入**:客户端发给服务端的输入一律以真值录下的命令包序列为准(见 [command_packet_format.zh-CN.md](command_packet_format.zh-CN.md))。命令包与**系统类消息**(`0x6d` 心跳、`0x6f` 进度等)都要按原拍号注入原字节,宿主自己产生的同类消息丢弃(进局时的 `0x67` 加入照常放行)。系统类消息到达的拍号取决于客户端快慢,其中 `0x6f` 决定服务端何时插入同步,属于与时序相关的输入;不注入的话逐拍状态对不上。
+14
View File
@@ -0,0 +1,14 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
rows = r.state_rows()
lib.check(any(opcode == 0x26 for _, opcode, _ in r.c2s_ops()), "没有喝药包 0x26")
before = {(item.get("x"), item.get("id")) for item in rows[0].get("items", []) if item.get("mode") == 2} if rows else set()
after = {(item.get("x"), item.get("id")) for item in rows[-1].get("items", []) if item.get("mode") == 2} if rows else set()
lib.check(before != after, "腰带物品集合没有变化")
gone = sorted(x for x, _ in before - after) # 脚本点的是底栏第 3 格 = 腰带第 3 列(格位 x = 2):喝掉的必须是这一列的(第 3、4 列的键写反过,点第 3 格喝了第 4 列) | The script taps bottom bar slot 3 = belt column 3 (slot x = 2): what gets drunk must be from this column (the keys for columns 3 and 4 were once swapped, and tapping slot 3 drank from column 4)
lib.check(gone == [2], f"喝掉的不是第 3 列:消失的格位 {gone}")
sys.exit(lib.main())
@@ -0,0 +1,2 @@
0 down 0 1450,1241
0.2 up 0
+11
View File
@@ -0,0 +1,11 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
seen = [row.get("players") for row in r.state_rows()]
lib.check(seen and seen[0] == 1, f"起局人数档应为 1,实际 {seen[:1]}")
lib.check(seen and seen[-1] == 8, f"选第 8 格后人数档应为 8,实际 {seen[-1:]}")
lib.check(not any(op == 0x30 for _, op, _ in r.c2s_ops()), "点难度格不应打开功能页(0x30)")
sys.exit(lib.main())
@@ -0,0 +1,5 @@
# 难度(底部 UI v4 第 0 格):点第 0 格展开 1–8 选择条,点第 8 格 → 人数档 8(下一拍走原版 /players 路径)。坐标 = 2868×1320 效果图像素
0.5 down 0 1090,1241
0.6 up 0
1.5 down 0 1810,1051
1.6 up 0
@@ -0,0 +1,19 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
rows = [(row.get("tick"), row.get("act"), row.get("arg")) for row in r._uimsg if row.get("cat") == "PanelManager"]
note_open = [t for t, act, arg in rows if act == "OpenPanel" and arg == "NotificationPanel"]
note_close = [t for t, act, arg in rows if act == "ClosePanel" and arg == "NotificationPanel"]
inv_open = [t for t, act, arg in rows if act == "OpenPanel" and arg == "PlayerInventoryExpansionLayout"]
lib.check(len(note_open) == 1, f"改难度后系统通知应弹一次,实际 {note_open}")
lib.check(len(inv_open) == 1, f"通知开着时点功能键应打开功能页一次,实际 {inv_open}")
if note_open and inv_open:
lib.check(note_open[0] < inv_open[0], f"功能页应在通知弹出之后打开(通知拍 {note_open[0]},功能页拍 {inv_open[0]})")
lib.check(not note_close or note_close[0] > inv_open[0], f"通知不应被这次按键关掉(通知关于拍 {note_close[:1]},功能页开于拍 {inv_open[0]})")
# 停留时长是产品覆盖层设的 5 秒(dm/ios/tools/gen_romfs_overlay.py 的 notificationSeconds;原版 10 秒 ≈ 270 拍)。在覆盖层上实测开到关 146 拍
# The dwell time is the 5 seconds set by the product overlay (notificationSeconds in dm/ios/tools/gen_romfs_overlay.py; the original game's 10 seconds ≈ 270 ticks). Measured on the overlay: 146 ticks from open to close
lib.check(bool(note_close) and 120 <= note_close[0] - note_open[0] <= 175, f"通知应约 5 秒(实测 146 拍)后自己关,实际开 {note_open} 关 {note_close}")
sys.exit(lib.main())
@@ -0,0 +1,7 @@
# 改难度后游戏弹系统通知「游戏难度设为 N…」(停 10 秒)。通知还开着时点红十字(功能键)必须打开功能页,不被通知吃掉(r28 剪口,真机发现)
0.5 down 0 1090,1241
0.6 up 0
1.5 down 0 1810,1051
1.6 up 0
4.0 down 0 1690,1241
4.1 up 0
@@ -0,0 +1 @@
1200
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
ticks = sorted(r._state_by_tick)
lib.check(any(a == "OpenPanel" and p == "HoradricCubeLayout" for _, a, p in r._panel_events), "双击魔盒后魔盒面板打开(界面消息 OpenPanel HoradricCubeLayout)")
lib.check(all(r.cursor_at(t) is None for t in ticks), "双击全程 cursor 为空(没拿起)")
lib.check(not any(op == 0x19 for _, op, _ in r.c2s_ops()), "双击不发 0x19 拿起")
sys.exit(lib.main())
@@ -0,0 +1,7 @@
# 物品区双击 = 按住 A(游戏提示「按住打开 / 使用 / 装备」)。术士存档魔盒占背包 (8,0)–(9,1),心点 1775,832;双击 → 魔盒面板打开,不拿起。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1775,832
2.1 up 0
2.3 down 0 1775,832
2.4 up 0
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
ticks = sorted(r._state_by_tick)
first_tick = min(ticks)
initial = r.items_at(first_tick)
source = [item for item in initial.values() if item.get("x") == 5 and item.get("y") == 3]
target = [item for item in initial.values() if item.get("x") == 6 and item.get("y") == 3]
lib.check(len(source) == 1, "初始 (5,3) 目标物品唯一")
lib.check(not target, "初始 (6,3) 目标格为空")
if source:
item_id = source[0]["id"]
picked = [t for t in ticks if r.items_at(t).get(item_id, {}).get("mode") == 4 and r.cursor_at(t) == item_id]
placed = [t for t in ticks if r.items_at(t).get(item_id, {}).get("x") == 6 and r.items_at(t).get(item_id, {}).get("y") == 3 and r.items_at(t).get(item_id, {}).get("mode") == 0 and r.cursor_at(t) is None]
lib.check(bool(picked), "某拍 cursor 指向目标物品且 mode=4")
lib.check(bool(placed), "最终目标物品在 (6,3)、mode=0 且 cursor 清空")
lib.check(all(item_id == r.cursor_at(t) for t in ticks if r.cursor_at(t) is not None), "全程没有拿起第二件物品")
lib.check(all(item.get("id") == item_id or item.get("mode") != 4 for t in ticks for item in r.items_at(t).values()), "全程没有误触发第二件物品 mode=4")
ops = r.c2s_ops()
lib.check(any(op == 0x19 for _, op, _ in ops), "c2s 含 0x19 拿起")
lib.check(any(op == 0x18 for _, op, _ in ops), "c2s 含 0x18 放下")
lib.check(next((t for t, op, _ in ops if op == 0x19), 1 << 60) < next((t for t, op, _ in ops if op == 0x18), 0), "0x19 先于 0x18")
sys.exit(lib.main())
+8
View File
@@ -0,0 +1,8 @@
# 先点屏幕功能键开背包;物品格 (5,3) 心点 1478,1003,右邻 (6,3) 心点 1563,1003。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1478,1003
2.2 move 0 1500,1003
2.5 move 0 1535,1003
2.8 move 0 1563,1043
3.2 up 0
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
ticks = sorted(r._state_by_tick)
initial = r.items_at(min(ticks))
source = [item for item in initial.values() if item.get("x") == 5 and item.get("y") == 3]
lib.check(len(source) == 1, "初始 (5,3) 目标物品唯一")
if source:
item_id = source[0]["id"]
final = r.items_at(ticks[-1]).get(item_id, {})
lib.check(final.get("x") == 5 and final.get("y") == 3 and final.get("mode") == 0, "拖回后物品仍在 (5,3)、mode=0")
lib.check(r.cursor_at(ticks[-1]) is None, "拖回最终 cursor 为空")
lib.check(all(item_id == r.cursor_at(t) for t in ticks if r.cursor_at(t) is not None), "拖回全程没有拿起第二件物品")
ops = r.c2s_ops()
lib.check(any(op == 0x19 for _, op, _ in ops), "c2s 含 0x19 拿起")
lib.check(any(op == 0x18 for _, op, _ in ops), "c2s 含 0x18 放下")
sys.exit(lib.main())
@@ -0,0 +1,7 @@
# 先点屏幕功能键开背包;物品格 (5,3) 心点 1478,1003,回放时松手点下移 40pt。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1478,1003
2.2 move 0 1510,1003
2.5 move 0 1478,1043
3.2 up 0
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
ops = [op for _, op, _ in r.c2s_ops()]
lib.check(0x19 in ops, "c2s 含 0x19 拿起")
lib.check(0x17 in ops, "c2s 含 0x17 丢到地上")
lib.check(0x19 in ops and 0x17 in ops and ops.index(0x19) < ops.index(0x17), "0x19 先于 0x17")
lib.check(0x18 not in ops, "没有放回格子(0x18)")
rows = r.state_rows() if callable(getattr(r, "state_rows", None)) else []
sys.exit(lib.main())
@@ -0,0 +1,8 @@
# 拖到面板外松手 = 丢弃:从物品格 (5,3) 拖到屏幕左缘(面板外),指针回原处后按 Y(拿着物品时游戏提示「Y 丢弃」)。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1478,1003
2.3 move 0 1300,1003
2.6 move 0 600,800
3.0 move 0 80,660
3.4 up 0
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
first_tick = min(r._state_by_tick)
initial = r.items_at(first_tick)
targets = [item for item in initial.values() if item.get("x") == 5 and item.get("y") == 3]
lib.check(len(targets) == 1, "初始 (5,3) 目标物品唯一")
if targets:
item_id = targets[0]["id"]
rows = [r.items_at(t).get(item_id) for t in sorted(r._state_by_tick)]
lib.check(all(row and row.get("x") == 5 and row.get("y") == 3 for row in rows), "长按期间目标物品始终在 (5,3)")
lib.check(all(r.cursor_at(t) is None for t in sorted(r._state_by_tick)), "长按全程 cursor 为空")
lib.check(not any(op == 0x19 for _, op, _ in r.c2s_ops()), "长按不发 0x19")
sys.exit(lib.main())
@@ -0,0 +1,5 @@
# 术士存档目标:DM_STATE 初始背包物品格 (5,3),脚本断言按格位取 id,不硬编码数字。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1478,1003
2.8 up 0
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
# 物品区单击 = 只移光标(游戏出物品说明),不拿起(单击选中并展示详情;拿起只在拖动时)
# Single tap in the item area = only moves the cursor (the game shows the item description), no pick-up (a single tap selects and shows details; pick-up happens only on drag)
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
first_tick = min(r._state_by_tick)
initial = r.items_at(first_tick)
targets = [item for item in initial.values() if item.get("x") == 5 and item.get("y") == 3]
lib.check(len(targets) == 1, "初始 (5,3) 目标物品唯一")
if targets:
item_id = targets[0]["id"]
rows = [r.items_at(t).get(item_id) for t in sorted(r._state_by_tick)]
lib.check(all(row and row.get("x") == 5 and row.get("y") == 3 and row.get("mode") == 0 for row in rows), "单击后目标物品始终在 (5,3)")
lib.check(all(r.cursor_at(t) is None for t in sorted(r._state_by_tick)), "单击全程 cursor 为空")
lib.check(not any(op == 0x19 for _, op, _ in r.c2s_ops()), "单击不发 0x19 拿起")
sys.exit(lib.main())
+7
View File
@@ -0,0 +1,7 @@
# 术士存档:背包物品格 (5,3)。物品区单击只移光标不拿起;再点右邻空格也只是移光标。
1.0 down 0 1690,1241
1.1 up 0
2.0 down 0 1478,1003
2.1 up 0
3.0 down 0 1563,1003
3.1 up 0
+184
View File
@@ -0,0 +1,184 @@
"""触屏全链用例断言公共库。
面板开关按 uimsg.jsonl 每行的 ``tick``(宿主 DM_UIMSG 在局内写服务端当前拍号)对齐;
局外(无 tick)的消息归入此前最近的拍号,首个拍号之前归入拍 0。
Shared assertion library for touch full-chain cases.
Panel open/close is aligned by the ``tick`` of each line in uimsg.jsonl (in-run, the host's DM_UIMSG writes the server's current tick number);
out-of-run messages (no tick) are attributed to the most recent preceding tick number, and those before the first tick number to tick 0.
"""
import json
import re
import sys
from pathlib import Path
class AssertFail(AssertionError):
pass
_FAILURES = []
_CHECKS = 0
_TICK_RE = re.compile(r"^(?:DM:Tick:)?(\d+)(?:#)?$")
def check(cond, msg):
global _CHECKS
_CHECKS += 1
if not cond:
_FAILURES.append(str(msg))
return bool(cond)
def _read_jsonl(path):
try:
with path.open(encoding="utf-8") as stream:
return [json.loads(line) for line in stream if line.strip()]
except (OSError, ValueError) as exc:
raise AssertFail(f"无法读取 {path}: {exc}") from exc
def _required(directory, name):
path = directory / name
if not path.is_file():
raise AssertFail(f"缺少必需文件:{path}")
return path
def _tick_from_message(row):
if isinstance(row.get("tick"), int):
return row["tick"]
if row.get("cat") == "DM" and row.get("act") == "Tick":
match = _TICK_RE.match(str(row.get("arg", "")))
if match:
return int(match.group(1))
if row.get("act") == "DM:Tick":
match = _TICK_RE.match(str(row.get("arg", "")))
if match:
return int(match.group(1))
return None
class Result:
def __init__(self, directory, c2s, ticks, uimsg, state):
self.directory = directory
self._c2s = c2s
self._ticks = ticks
self._uimsg = uimsg
self._state = state
self._state_by_tick = {}
for row in state:
tick = row.get("tick")
if isinstance(tick, int):
self._state_by_tick[tick] = row
self._panel_events = self._build_panel_events(uimsg)
@staticmethod
def _build_panel_events(rows):
current_tick = 0
events = []
for row in rows:
if isinstance(row.get("tick"), int): # 宿主 DM_UIMSG 局内每行带服务端拍号 | In-run, each line of the host's DM_UIMSG carries the server tick number
current_tick = row["tick"]
else:
marker_tick = _tick_from_message(row)
if marker_tick is not None:
current_tick = marker_tick
continue
action = row.get("act")
panel = row.get("arg")
if not panel or action not in {
"OpenPanel", "OpenExclusivePanel", "UnloadPanel", "ClosePanel"
}:
continue
events.append((current_tick, action, panel))
return events
def _state_at(self, tick):
rows = [item for item in self._state_by_tick if item <= tick]
if not rows:
return None
return self._state_by_tick[max(rows)]
def items_at(self, tick):
row = self._state_at(tick)
if row is None:
return {}
return {item["id"]: dict(item) for item in row.get("items", [])}
def cursor_at(self, tick):
row = self._state_at(tick)
return None if row is None else row.get("cursor")
def players_at(self, tick):
row = self._state_at(tick)
return None if row is None else row.get("players")
def panels_at(self, tick):
panels = set()
for event_tick, action, panel in self._panel_events:
if event_tick > tick:
break
if action == "OpenExclusivePanel":
panels.clear()
panels.add(panel)
elif action == "OpenPanel":
panels.add(panel)
else:
panels.discard(panel)
return panels
def c2s_ops(self, t0=None, t1=None):
result = []
for row in self._c2s:
if row.get("q") == "sys":
continue
tick = row.get("tick")
if not isinstance(tick, int) or (t0 is not None and tick < t0) or (
t1 is not None and tick > t1
):
continue
packet = str(row.get("pkt", ""))
if len(packet) < 2:
raise AssertFail(f"命令包缺少 opcode:tick={tick} pkt={packet!r}")
try:
opcode = int(packet[:2], 16)
except ValueError as exc:
raise AssertFail(f"命令包不是十六进制:tick={tick} pkt={packet!r}") from exc
result.append((tick, opcode, packet))
return result
def state_rows(self):
return list(self._state)
def tick_units(self):
return [row["u"] for row in self._ticks if isinstance(row.get("u"), dict)]
def load(directory):
directory = Path(directory)
paths = {name: _required(directory, name) for name in (
"c2s.jsonl", "ticks.jsonl", "uimsg.jsonl", "state.jsonl"
)}
return Result(
directory,
_read_jsonl(paths["c2s.jsonl"]),
_read_jsonl(paths["ticks.jsonl"]),
_read_jsonl(paths["uimsg.jsonl"]),
_read_jsonl(paths["state.jsonl"]),
)
def main(argv=None):
del argv
if _FAILURES:
print(f"红 {len(_FAILURES)} 条")
for failure in _FAILURES:
print(f"- {failure}")
return 1
print(f"绿 {_CHECKS} 条")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
import json
import sys
from pathlib import Path
run = Path(sys.argv[1])
def fail(message):
print(f"断言失败:{message}", file=sys.stderr)
raise SystemExit(1)
c2s = [json.loads(line) for line in (run / "c2s.jsonl").open() if line.strip()]
if not any(row.get("q") != "sys" and row.get("pkt", "").startswith("42") for row in c2s):
fail("没有移动包")
xs = []
for line in (run / "ticks.jsonl").open():
row = json.loads(line)
unit = row.get("u")
if unit and unit.get("type") == 0 and unit.get("id") == 1:
xs.append((row["t"], unit["x"]))
if len(xs) < 2 or xs[-1][1] <= xs[0][1]:
fail("x 没增大")
print(f"触屏移动断言通过:移动包存在,x {xs[0][1]}→{xs[-1][1]};DM_TICKS 射程={len(xs)} 条单位收样")
+3
View File
@@ -0,0 +1,3 @@
0 down 0 90,1220
3.1 move 0 150,1220
5.1 up 0
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
rows = [(t, op) for t, op, _ in r.c2s_ops()]
ops = [op for _, op in rows]
# 点到目标(NPC / 物件 / 物品,dm_world.c 带约 7 毫米余量)会走过去交互,那是允许的:带单位的包 0x02 / 0x04 / 0x13 / 0x16 / 0x2f / 0x40 / 0x41。
# 不许的是「没有目标的点地移动」:0x01 / 0x03 前后 40 拍内必须有带单位的包,否则就是点空地走开了。
# Tapping a target (NPC / object / item; dm_world.c has a margin of about 7 mm) walks over and interacts, which is allowed: packets with a unit 0x02 / 0x04 / 0x13 / 0x16 / 0x2f / 0x40 / 0x41.
# What is not allowed is "tap-ground movement without a target": within 40 ticks before or after 0x01 / 0x03 there must be a packet with a unit, otherwise it was a tap on empty ground that walked away.
TARGET = {0x02, 0x04, 0x13, 0x16, 0x2f, 0x40, 0x41}
stray = [(t, op) for t, op in rows if op in (0x01, 0x03) and not any(o in TARGET and abs(t2 - t) <= 40 for t2, o in rows)]
lib.check(not stray, "没有无目标的点地移动包(0x01 / 0x03 都伴随带单位的交互包):%s" % stray[:3])
lib.check(0x42 not in ops, "没有摇杆移动包(0x42)")
ev = r._panel_events
opened = [t for t, a, p in ev if a == "OpenPanel" and p == "PlayerInventoryExpansionLayout"]
closed = [t for t, a, p in ev if a == "ClosePanel" and p == "PlayerInventoryExpansionLayout" and opened and t > opened[0]]
lib.check(bool(opened), "功能键开物品栏")
lib.check(bool(closed), "点面板外后物品栏关闭")
sys.exit(lib.main())
@@ -0,0 +1,68 @@
# 除摇杆外任何触点不许触发移动。局内不碰摇杆区(左 43% 且上 25% 以下)点 30 下:空地、技能钮之间、屏幕上沿;
# 再开物品栏点面板外 2 下(= 关面板,不走路)。判据:没有 0x42(摇杆移动);0x01 / 0x03 只许伴随「点到目标走过去交互」出现(点世界目标 = 交互)。
# 进局落在小站上(dm_townwp.c):原来落在小站选择框里的 8 下右移 600(仍是空地),否则点开小站面板、后面的点按在面板里选了目的地
# 进局落在小站旁 10 格(小站在人右下方):落进小站选择框的 8 下上移 450(仍是空地),理由同上
1.00 down 0 1963,348
1.08 up 0
1.25 down 0 2108,138
1.33 up 0
1.50 down 0 1448,1137
1.58 up 0
1.75 down 0 2092,338
1.83 up 0
2.00 down 0 2493,158
2.08 up 0
2.25 down 0 2339,479
2.33 up 0
2.50 down 0 1376,216
2.58 up 0
2.75 down 0 2188,446
2.83 up 0
3.00 down 0 2043,532
3.08 up 0
3.25 down 0 2085,459
3.33 up 0
3.50 down 0 2021,293
3.58 up 0
3.75 down 0 1757,166
3.83 up 0
4.00 down 0 2481,852
4.08 up 0
4.25 down 0 2001,492
4.33 up 0
4.50 down 0 1995,312
4.58 up 0
4.75 down 0 1893,448
4.83 up 0
5.00 down 0 1595,1147
5.08 up 0
5.25 down 0 2141,221
5.33 up 0
5.50 down 0 2447,410
5.58 up 0
5.75 down 0 2111,424
5.83 up 0
6.00 down 0 2062,239
6.08 up 0
6.25 down 0 2421,168
6.33 up 0
6.50 down 0 2455,162
6.58 up 0
6.75 down 0 2567,461
6.83 up 0
7.00 down 0 2316,1128
7.08 up 0
7.25 down 0 2175,233
7.33 up 0
7.50 down 0 2253,518
7.58 up 0
7.75 down 0 2040,203
7.83 up 0
8.00 down 0 1808,408
8.08 up 0
8.25 down 0 2731,642
8.33 up 0
9.00 down 0 1690,1241
9.10 up 0
10.50 down 0 2840,600
10.60 up 0
+15
View File
@@ -0,0 +1,15 @@
import os, json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
# 主技能 = 原版施放包:对地点 0x05、对单位 0x06(真机 e2e/s6:05 ×16、06 ×6,有怪在射程内才出 06)。
# 只看前缀回放结束之后(前缀里的包是回放注入的,不算触屏产生);末拍取本用例 prefix 文件声明的前缀
# Main skill = the original game's cast packets: 0x05 on a location, 0x06 on a unit (real device e2e/s6: 05 ×16, 06 ×6; 06 only appears when a monster is in range).
# Only look after the prefix replay ends (packets in the prefix are injected by the replay and do not count as touch-generated); the end tick is taken from the prefix declared in this case's prefix file
prefix = Path(os.environ["DM_TOUCH_PREFIX"]) # touchchain.sh 已把 prefix 文件里相对工作区根的路径拼成绝对路径 | touchchain.sh has already joined the workspace-root-relative path from the prefix file into an absolute path
last = max(json.loads(l)["tick"] for l in open(prefix / "c2s.jsonl") if l.strip())
r = lib.load(sys.argv[1])
lib.check(any(op in (0x05, 0x06) for _, op, _ in r.c2s_ops(t0=last + 1)), f"前缀末拍 {last} 之后没有主技能施放包 0x05 / 0x06")
sys.exit(lib.main())
+1
View File
@@ -0,0 +1 @@
run/verify/dm/run_sta_contract_1002_090004/wild_prefix_original_warlock
@@ -0,0 +1,3 @@
# 起局(前缀回放结束且读取画面已撤)后 1 s 再按:撤屏当拍按下并一直按住的 A 不算一次按下(实测 0 s 不施放、1 s / 3 s 施放)
1.0 down 0 2812,1238
2.5 up 0
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1]))
import lib
r = lib.load(sys.argv[1])
opens = [(t, p) for t, a, p in r._panel_events if a in ("OpenPanel", "OpenExclusivePanel")]
inv = [t for t, p in opens if p == "PlayerInventoryExpansionLayout"]
skill = [t for t, p in opens if p == "SkillsTreePanel"]
quest = [t for t, p in opens if p == "QuestLogPanelExpansion"]
lib.check(bool(inv), "功能键开物品栏")
lib.check(bool(skill) and bool(inv) and skill[0] > inv[0], "点「技能树」页签后技能树打开")
lib.check(bool(quest) and bool(skill) and quest[-1] > skill[0], "再点「任务日志」页签后任务日志打开")
lib.check(not any(op == 0x19 for _, op, _ in r.c2s_ops()), "全程不拿起物品")
sys.exit(lib.main())
+7
View File
@@ -0,0 +1,7 @@
# 点页签切页:鼠标左键点不动页签,宿主按够次数的 L / R。开背包(物品栏页)→ 点「技能树」页签(心点 1904,59)→ 点「任务日志」页签(心点 490,59)。
1.0 down 0 1690,1241
1.1 up 0
2.5 down 0 1904,59
2.6 up 0
4.5 down 0 490,59
4.6 up 0
+58
View File
@@ -0,0 +1,58 @@
import json
import contextlib
import io
import pathlib
import shutil
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from lib import AssertFail, check, load, main
def write_jsonl(directory, name, rows):
(directory / name).write_text(
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows),
encoding="utf-8",
)
FIXTURE_DIR = pathlib.Path(__file__).parent / "tests" / "fixture"
class TestTouchcaseLib(unittest.TestCase):
def test_all_interfaces(self):
with tempfile.TemporaryDirectory() as path:
directory = pathlib.Path(path)
shutil.copytree(FIXTURE_DIR, directory, dirs_exist_ok=True)
result = load(directory)
self.assertEqual(result.items_at(2), {8: {"id": 8, "cls": 2}})
self.assertIsNone(result.cursor_at(3))
self.assertEqual(result.players_at(3), 2)
self.assertEqual(result.panels_at(3), {"Inventory"})
self.assertEqual(result.panels_at(4), set())
self.assertEqual(result.panels_at(5), {"Inventory"})
self.assertEqual(result.c2s_ops(), [(2, 0x19, "1900"), (5, 0x18, "18ff")])
self.assertEqual(result.c2s_ops(3, 5), [(5, 0x18, "18ff")])
def test_missing_state_is_red(self):
with tempfile.TemporaryDirectory() as path:
directory = pathlib.Path(path)
shutil.copytree(FIXTURE_DIR, directory, dirs_exist_ok=True)
(directory / "state.jsonl").unlink()
with self.assertRaises(AssertFail):
load(directory)
def test_check_records_failures_and_main_exits_red(self):
check(False, "反例失败")
output = io.StringIO()
with contextlib.redirect_stdout(output):
result = main([])
self.assertEqual(result, 1)
self.assertIn("红", output.getvalue())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,3 @@
{"tick":2,"unit":7,"len":2,"pkt":"1900"}
{"tick":2,"q":"sys","unit":null,"len":2,"pkt":"6f00"}
{"tick":5,"unit":7,"len":2,"pkt":"18ff"}
@@ -0,0 +1,3 @@
{"tick":2,"items":[{"id":7,"cls":1}],"cursor":7,"players":1}
{"tick":2,"items":[{"id":8,"cls":2}],"cursor":null,"players":2}
{"tick":5,"items":[],"cursor":8,"players":null}
@@ -0,0 +1 @@
{"tick":0,"n":[],"h":[],"bad":0}
@@ -0,0 +1,6 @@
{"seq":0,"cat":"DM","act":"Tick","arg":"3#"}
{"seq":1,"cat":"PanelManager","act":"OpenPanel","arg":"Inventory"}
{"seq":2,"cat":"DM","act":"Tick","arg":"4#"}
{"seq":3,"cat":"PanelManager","act":"UnloadPanel","arg":"Inventory"}
{"seq":4,"cat":"DM","act":"Tick","arg":"5#"}
{"seq":5,"cat":"PanelManager","act":"OpenPanel","arg":"Inventory"}
+82
View File
@@ -0,0 +1,82 @@
#!/bin/bash
set -u
export LC_ALL=C
ROOT=$(cd "$(dirname "$0")/.." && pwd)
CASE=${1:?用法:touchchain.sh <用例名>}
CASE_DIR="$ROOT/verify/touchcases/$CASE"
[ -f "$CASE_DIR/script.txt" ] && [ -f "$CASE_DIR/assert.py" ] || { echo "【红】未知或不完整用例:$CASE" >&2; exit 2; }
BIN="$ROOT/host/dmhost"
OUT=${DM_HOST_OUT:-"$(bash "$(dirname "$0")/../tools/product.sh" path touch)"}
REF=${DM_TOUCH_SAVE:-"${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001/0"}
# 野外等前缀:用例目录里 prefix 文件(一行,前缀目录相对工作区根的路径)声明;环境变量 DM_TOUCH_PREFIX 可覆盖。accept 按目录收集用例时靠它带上前缀
# Replay prefixes such as the wilderness one: declared by a prefix file in the case directory (one line, the prefix directory's path relative
# to the workspace root); the environment variable DM_TOUCH_PREFIX can override it. accept relies on this file to bring the prefix along when
# it collects cases by directory
PREFIX=${DM_TOUCH_PREFIX:-$( [ -f "$CASE_DIR/prefix" ] && head -1 "$CASE_DIR/prefix" )}
case "$PREFIX" in ""|/*) ;; *) PREFIX="${DM_ROOT:-$HOME/dm-work}/$PREFIX";; esac # 用例的 prefix 文件里写相对工作区根的路径(如 run/verify/dm/…);绝对路径原样用 | a case's prefix file holds a path relative to the workspace root (e.g. run/verify/dm/...); an absolute path is used as is
STAMP=$(date +%s)
RUNROOT=${DM_TOUCH_RUNROOT:-${DM_ROOT:-$HOME/dm-work}/run/verify/dm/touchchain}
RUN="$RUNROOT/${CASE}_${STAMP}_$$"
START=$SECONDS
status=2
mkdir -p "$RUN/user" || exit 2
if [ -n "$PREFIX" ]; then
[ -f "$PREFIX/manifest.json" ] && [ -f "$PREFIX/c2s.jsonl" ] || { echo "【红】前缀不完整:$PREFIX" >&2; exit 2; }
sha=$(sed -n 's/.*"start_save_sha": "\([0-9a-f]*\)".*/\1/p' "$PREFIX/manifest.json")
root="" # 起始存档指纹 = data/switch/*/MANIFEST.sha256 文件本身的 SHA-256(同 dm/tools/host_savecmp.sh) | Starting save fingerprint = SHA-256 of the data/switch/*/MANIFEST.sha256 file itself (same as dm/tools/host_savecmp.sh)
for m in "${DM_ROOT:-$HOME/dm-work}"/data/switch/*/MANIFEST.sha256; do [ "$(shasum -a 256 "$m" | cut -c1-64)" = "$sha" ] && { root=$(dirname "$m"); break; }; done
[ -n "$root" ] || { echo "【红】按指纹找不到前缀存档:$sha" >&2; exit 2; }
REF="$root/0000000000000001/0"
export DM_C2S_REPLAY="$PREFIX/c2s.jsonl" DM_TOUCH_PREFIX="$PREFIX" # 宿主 touch_mac 据此改为 DM:ReplayDone 后起局 | Based on this, the host's touch_mac starts the run after DM:ReplayDone instead
# 选第 2 行(术士)再进局:点右侧存档列表第 2 行 → 载入高亮的角色(同真机冒烟的键序)。旧写法「下 → A 确认选人 → A」在产品布局下走不通——覆盖层把「确认选人」那条消息换成了空操作
# Select row 2 (Warlock) then enter the game: tap row 2 of the save list on the right → load the highlighted character (same key sequence as the real device smoke test). The old "Down → A to confirm character → A" does not work under the product layout - the overlay replaced the "confirm character" message with a no-op
export DM_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'
fi
cp -R "$REF" "$RUN/user/0" || { echo "【红】术士存档副本失败:$REF" >&2; exit 2; }
chmod -R u+w "$RUN/user/0" || exit 2
export DM_SAVE="$RUN/user/0" DM_GAME_SEED=305419896 DM_FIXED_TIME=1790895128
export DM_TOUCH_SCRIPT="$CASE_DIR/script.txt"
# 功能用例跑在 iOS 包同一份界面覆盖层上(测的就是玩家看到的布局;画面闸门仍对原版真值、不挂)。
# accept 起跑前生成一次经 DM_ROMFS_OVERLAY 传进来;单跑本脚本时自己生成到局目录(生成脚本幂等,约 3 秒)。
# Functional cases run on the same UI overlay as the iOS app (what is tested is the layout the player sees; the screenshot gate still compares against the original-game ground truth and does not attach it).
# accept generates it once before the run and passes it in via DM_ROMFS_OVERLAY; when this script is run alone it generates it into the run directory itself (the generation script is idempotent, about 3 seconds).
if [ -z "${DM_ROMFS_OVERLAY:-}" ]; then
python3 "$ROOT/ios/tools/gen_romfs_overlay.py" "${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}" "$RUN/romfs_overlay" > /dev/null || { echo "【红】界面覆盖层生成失败(gen_romfs_overlay.py)" >&2; exit 2; }
export DM_ROMFS_OVERLAY="$RUN/romfs_overlay"
fi
# 进局:X 进选角页 → 载入第 1 个角色。产品布局(前端换成键鼠版)下主菜单按 A 没有落点,原来的「A → 难度框 → A」进不了局
# Game entry: X to the character select page → load the 1st character. Under the product layout (front end switched to the keyboard-and-mouse version) pressing A on the main menu has nothing to land on, so the old "A → difficulty box → A" cannot enter the game
export DM_KEYS=${DM_KEYS:-'X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame'}
export DM_TICKS="$RUN/ticks.jsonl" DM_TICKS_FULL=1 DM_TICKS_N=${DM_TICKS_N:-${PREFIX:+720}}
[ -f "$CASE_DIR/ticks" ] && export DM_TICKS_N=${DM_TICKS_N:-$(head -1 "$CASE_DIR/ticks")} # 用例自带总拍数(如等通知 10 秒自己关) | The case brings its own total tick count (e.g. waiting for a notification that closes itself after 10 seconds)
export DM_TICKS_N=${DM_TICKS_N:-900}
export DM_C2S_LOG="$RUN/c2s.jsonl" DM_UIMSG="$RUN/uimsg.jsonl" DM_STATE="$RUN/state.jsonl" DM_WATCH_STALL=15 DM_WATCH=90
# 功能用例的判据都是命令包 / 游戏状态(逻辑判据),不需要产品节奏:出图不限速 + 确定性客体时钟快进,
# 起局按状态(进局 / 回放结束且读取画面已撤,touch_mac.c),触点脚本按服务端游戏拍推进,与出图速度、本机负载无关。
# 原先按产品节奏每例 17–19 s、时限 20 s,本机一并行就超时报红。
# 快进下服务端拍跑在客户端加载前面:读取画面约第 600 拍才撤,所以总拍数给到 900(前缀例 720 起算点不同,见上)
# Functional case criteria are all command packets / game state (logic criteria) and do not need product pacing: unthrottled rendering + fast-forward on the deterministic guest clock,
# the run starts by state (game entered / replay finished and loading screen dismissed, touch_mac.c), and the touch point script advances by server game ticks, independent of rendering speed and machine load.
# Previously at product pacing each case took 17–19 s with a 20 s limit, and timed out (a failure) as soon as anything ran in parallel on this machine.
# Under fast-forward the server ticks run ahead of client loading: the loading screen is only dismissed around tick 600, so the total tick count is set to 900 (prefix cases use 720 with a different starting point, see above)
export DM_PRESENT_HZ=0 DM_DETCLOCK=33333333
[ -x "$BIN" ] || timeout 75s make -C "$ROOT/host" dmhost >/dev/null || { echo "【红】宿主编译失败" >&2; exit 2; }
set +e
timeout 100s "$BIN" "$OUT" main sdk > "$RUN/host.log" 2>&1
rc=$?; [ "$rc" -eq 0 ] || { grep '【红】看门狗' "$RUN/host.log" | tail -1 >&2 || true; exit "$rc"; }
host_status=$?
timeout 5s python3 "$CASE_DIR/assert.py" "$RUN"
assert_status=$?
# 与宿主状态探针的接口约定:每例局目录必须有宿主写的 state.jsonl(DM_STATE,首拍必写),缺了说明宿主没带状态探针,断言库读不到状态
# Interface contract with the host state probe: each case's run directory must have a state.jsonl written by the host (DM_STATE, always written on the first tick); if missing, the host was built without the state probe and the assertion library cannot read state
[ -s "$RUN/state.jsonl" ] || { echo "断言失败:局目录缺 state.jsonl(宿主未写 DM_STATE)" >&2; assert_status=1; }
set -e
if [ "$host_status" -eq 0 ] && [ "$assert_status" -eq 0 ]; then
status=0
[ "${DM_TOUCH_KEEP:-0}" = 1 ] || rm -rf "$RUN"
echo "TOUCHCHAIN $CASE OK 用时 $((SECONDS - START)) 秒"
exit 0
fi
echo "【红】touchchain $CASE:host=$host_status assert=$assert_status;局目录:$RUN" >&2
echo "TOUCHCHAIN $CASE RED 用时 $((SECONDS - START)) 秒"
exit 1
+62
View File
@@ -0,0 +1,62 @@
# UI Message Stream Format
中文:[ui_message_stream.zh-CN.md](ui_message_stream.zh-CN.md)
Every change in the game's UI (opening a panel, closing a panel, switching pages, moving the cursor…) is announced by the game itself with a UI message. Recording the UI messages of a run in order into a file makes it possible to compare whether the UI flow is the same on both sides: one side is the **ground truth** (reference data obtained by running the original game in a patched Ryujinx emulator), the other is the **host** (`dmhost` from `dm/host`, which executes the rewritten game program on a Mac). This page defines the format of that file and the comparison rules.
## Capture point
- All of the game's UI messages are dispatched through virtual function `+0x28` of the UI bus object `*(main + 0x2f05458)`; in `main` of 3.3.94012, the implementing function is `main + 0xb1dc60` (the vtable read at run time is authoritative; it is not hard-coded).
- At entry: `x0` = the bus object, `x1` → the message header `{+0x00 u64 category hash, +0x08 u64 action hash, +0x10 u64 payload pointer}`.
- The hash is FNV-1a 64 (offset basis `0xcbf29ce484222325`, multiplier `0x100000001b3`), computed byte by byte over the original string. Example: `PanelManager` = `0x7127a406e0b6452c`.
- The same virtual function occasionally has non-message calls (`x1` is not a readable pointer): these are not output.
## One line of JSON per message
UTF-8, terminated by `\n`, with a fixed field order:
```
{"seq":N,"cat_h":"0x7127a406e0b6452c","act_h":"0x...","arg":"MainMenuPanel","cat":"PanelManager","act":"OpenExclusivePanel"}
```
| Field | Required | Meaning |
|---|---|---|
| seq | Yes | Index within this run (starting from 0, counting only messages that are output) |
| cat_h / act_h | Yes | Category / action hash, `0x` + 16 lowercase hex digits. **Comparison uses only these two and arg** |
| arg | Yes | The C string the payload pointer points to (≤ 64 bytes, truncated at 0; must consist entirely of printable ASCII or UTF-8 high bytes), otherwise `null` |
| cat / act | No | Names, for human reading only: looked up in reverse by FNV-1a over all printable strings of ≥ 3 bytes in the read-only region `[0x1b79000, 0x2056000)` of `main`; omitted if not found |
- Time, frame number, thread number and pointer values are not output: these are not comparable between the two sides.
- File location: on the ground-truth side it is `<run dir>/uimsg.jsonl` (written by the emulator driver scripts; these are not shipped with the repository, so the checks that depend on ground truth cannot be run with this repository alone); on the host side it is given by the environment variable `DM_UIMSG=<path>`, and by default nothing is recorded.
## Comparison rules
Implemented by `dm/verify/uicmp.py`: `uicmp.py <ground-truth uimsg.jsonl> <host uimsg.jsonl> [--until <arg>]`, exit code 0 = identical.
1. Each side's sequence is taken as `(cat_h, act_h, arg)`.
2. Messages in the exemption table (see below) are removed first, then **adjacent, fully identical messages are folded into one**: only whether a message appears is compared, not how many times.
3. If the folded sequences are identical entry by entry, the two sides match; otherwise the position of the first difference is reported, together with 3 entries before and after that position on each side.
4. The coverage (how much this comparison actually covered) is reported as well: the entry counts before / after folding, and the number of distinct categories.
`--until <arg>`: both sides are truncated at the first occurrence of that payload (inclusive), so only the same segment of the flow is compared.
## Exemption table
Exemptions are registered in `EXEMPT` in `uicmp.py`; for every entry added, the reason must be stated here.
| Action | Payload | Reason |
|---|---|---|
| OpenPanel / ClosePanel | SaveIndicatorPanel | A timing race. `0x2442ac` sets the "saving" flag to 1 and then clears it to 0, less than 1 millisecond apart; only if a frame happens to fall inside this window does `0xb14e00` start showing the save indicator, after which `0xad42d4` keeps it shown for a minimum duration by wall clock, resending OpenPanel every frame during that time. Whether it appears depends on frame rate and luck, and is not comparable between the two sides. `LoadPanel SaveIndicatorPanel` is not exempt and is compared as usual |
Run requirement: save copies must always be writable. A read-only copy would make the save-writing step not happen, deviating from a real device.
## Cursor payload (used by the driver, not part of the comparison)
`+4` / `+8` at the payload pointer of `InputMessage:MouseMove` are two `u32` cursor coordinates. The driver script reads them, and in a ground-truth run's `events.jsonl` this UI event gets an extra `cursor: [x, y]`; `uimsg.jsonl` still has only the six fields above, and the comparison definition is unchanged.
A driver-script plan (an action sequence that a ground-truth run advances by game data) can use the cursor as a confirmation condition:
- `press <key> cursor:x:y:r released`: after the key is sent, a new cursor message must be seen landing within radius `r` of the target, and the last `ControllerActionBegin/End` must be End, before moving on to the next step.
- `assert cursor:x:y:r`: only checks the current cursor position, without requiring further movement.
Cursor coordinates vary with the window size and the page you are on; coordinates measured on one page cannot be extrapolated to other pages.
+62
View File
@@ -0,0 +1,62 @@
# UI 消息流格式
English: [ui_message_stream.md](ui_message_stream.md)
游戏界面的每一次变化(开面板、关面板、切页、移动光标……)都由游戏自己发一条 UI 消息。把一局里的 UI 消息按先后记成一个文件,就能比较两边的界面流程是否一致:一边是**真值**(用打了补丁的 Ryujinx 模拟器跑原版游戏得到的参照数据),一边是**宿主**(`dm/host` 的 `dmhost`,在 Mac 上执行改写后的游戏程序)。本页定义这个文件的格式与对照规则。
## 采集点
- 游戏所有 UI 消息都经 UI 总线对象 `*(main + 0x2f05458)` 的虚函数 `+0x28` 投递;在 3.3.94012 的 `main` 里,实现函数是 `main + 0xb1dc60`(以运行时读虚表为准,不写死)。
- 入口处:`x0` = 总线对象,`x1` → 消息头 `{+0x00 u64 类别哈希, +0x08 u64 动作哈希, +0x10 u64 载荷指针}`。
- 哈希是 FNV-1a 64(偏移基 `0xcbf29ce484222325`,乘数 `0x100000001b3`),对原字串逐字节算。例:`PanelManager` = `0x7127a406e0b6452c`。
- 同一虚函数偶有非消息调用(`x1` 不是可读指针):不输出。
## 每条一行 JSON
UTF-8,`\n` 结尾,字段顺序固定:
```
{"seq":N,"cat_h":"0x7127a406e0b6452c","act_h":"0x...","arg":"MainMenuPanel","cat":"PanelManager","act":"OpenExclusivePanel"}
```
| 字段 | 必填 | 含义 |
|---|---|---|
| seq | 是 | 本局第几条(从 0 起,只数输出的消息) |
| cat_h / act_h | 是 | 类别 / 动作哈希,`0x` + 16 位小写十六进制。**对照只用这两个与 arg** |
| arg | 是 | 载荷指针指向的 C 串(≤ 64 字节,以 0 截断;须全为可打印 ASCII 或 UTF-8 高位字节),否则 `null` |
| cat / act | 否 | 名字,只供人读:用 `main` 只读区 `[0x1b79000, 0x2056000)` 里全部 ≥ 3 字节可打印串的 FNV-1a 反查;查不到就省略 |
- 不输出时间、帧号、线程号、指针值:这些两边不可比。
- 文件位置:真值侧是 `<局目录>/uimsg.jsonl`(模拟器驱动脚本写;这些脚本不随仓库提供,所以依赖真值的检查在仓库外跑不了);宿主侧用环境变量 `DM_UIMSG=<路径>` 指定,缺省不记。
## 对照规则
由 `dm/verify/uicmp.py` 实现:`uicmp.py <真值 uimsg.jsonl> <宿主 uimsg.jsonl> [--until <arg>]`,退出码 0 = 一致。
1. 两边各自按 `(cat_h, act_h, arg)` 取序列。
2. 先剔除豁免表里的消息(见下),再把**相邻完全相同的消息折叠为一条**:只比是否出现,不比条数。
3. 折叠后逐条相同即一致;否则报第一处不同的位置,以及两边该位置前后各 3 条。
4. 同时报射程(这次比较实际覆盖了多少):折叠前 / 后条数、不同类别数。
`--until <arg>`:两边都截到第一次出现该载荷(含)为止,只比同一段流程。
## 豁免表
豁免登记在 `uicmp.py` 的 `EXEMPT` 里;每加一条都要在这里写明理由。
| 动作 | 载荷 | 理由 |
|---|---|---|
| OpenPanel / ClosePanel | SaveIndicatorPanel | 时序竞态。`0x2442ac` 把「存档中」标志置 1 再清 0,间隔不到 1 毫秒;只有恰好有一帧落在这个窗口里,`0xb14e00` 才开始显示存档指示,随后 `0xad42d4` 按墙钟的最短时长保持显示,期间每帧重发 OpenPanel。出不出现取决于帧率与运气,两边不可比。`LoadPanel SaveIndicatorPanel` 不在豁免之列,照常对照 |
跑法要求:存档副本一律可写。只读副本会让写存档那一步不发生,偏离真机。
## 光标载荷(驱动用,不进对照)
`InputMessage:MouseMove` 的载荷指针指向的 `+4` / `+8` 是两个 `u32` 光标坐标。驱动脚本读出它们,真值局的 `events.jsonl` 里这条 UI 事件会多一个 `cursor: [x, y]`;`uimsg.jsonl` 仍只有上面六个字段,对照口径不变。
驱动脚本的计划(真值局按游戏数据推进的动作序列)可以拿光标当确认条件:
- `press <键> cursor:x:y:r released`:发键后要见到新的光标消息落在目标半径 `r` 内,并且最后一条 `ControllerActionBegin/End` 是 End,才进入下一步。
- `assert cursor:x:y:r`:只核当前光标位置,不要求再移动。
光标坐标随窗口尺寸与所在页面而变,某一页量到的坐标不能外推到别的页面。
+34
View File
@@ -0,0 +1,34 @@
# UI 消息流对照(格式与规则见 dm/verify/ui_message_stream.md):两份 uimsg.jsonl,按 (cat_h, act_h, arg) 比,相邻相同折叠。
# 用法:uicmp.py <真值 uimsg.jsonl> <宿主 uimsg.jsonl> [--until <arg>] 退出码 0 = 一致
# --until:两边都截到第一次出现该载荷(含)为止,比同一段流程(如不按键只到选角主菜单 MainMenuButtonRibbon)
# UI message stream comparison (format and rules in dm/verify/ui_message_stream.md): two uimsg.jsonl files compared by (cat_h, act_h, arg), with adjacent duplicates collapsed.
# Usage: uicmp.py <ground truth uimsg.jsonl> <host uimsg.jsonl> [--until <arg>] exit code 0 = match
# --until: both sides are cut at the first occurrence of that payload (inclusive), comparing the same stretch of flow (e.g. with no key presses only up to the character select main menu MainMenuButtonRibbon)
import sys, json
UNTIL = sys.argv[sys.argv.index('--until') + 1] if '--until' in sys.argv else None
# 登记在案的豁免(格式与证据见 ui_message_stream.md「豁免表」):(动作名, 载荷)
# Registered exemptions (format and evidence in the 「豁免表」(exemption table) section of ui_message_stream.md): (action name, payload)
EXEMPT = {('OpenPanel', 'SaveIndicatorPanel'), ('ClosePanel', 'SaveIndicatorPanel')}
EXEMPT_H = {('0x723d40e52f74e229', 'SaveIndicatorPanel')} # OpenPanel 的哈希;ClosePanel 按名字核 | Hash of OpenPanel; ClosePanel is checked by name
def exempt(r): return (r.get('act'), r.get('arg')) in EXEMPT or (r['act_h'], r.get('arg')) in EXEMPT_H
def load(p):
raw = [json.loads(l) for l in open(p, encoding='utf-8') if l.strip()]
seq = [r for r in raw if not exempt(r)]
load.dropped = getattr(load, 'dropped', 0) + len(raw) - len(seq)
if UNTIL:
k = next((i for i, r in enumerate(seq) if r.get('arg') == UNTIL), None)
if k is None: print(f'{p} 里没有 {UNTIL}'); sys.exit(2)
seq = seq[:k + 1]
keys = [(r['cat_h'], r['act_h'], r.get('arg')) for r in seq]
names = {(r['cat_h'], r['act_h'], r.get('arg')): f"{r.get('cat', r['cat_h'])}:{r.get('act', r['act_h'])}:{r.get('arg')}" for r in seq}
fold = [k for i, k in enumerate(keys) if i == 0 or k != keys[i - 1]]
return keys, fold, names
a, fa, na = load(sys.argv[1]); b, fb, nb = load(sys.argv[2]); names = {**nb, **na}
n = next((i for i, (x, y) in enumerate(zip(fa, fb)) if x != y), None)
if n is None and len(fa) != len(fb): n = min(len(fa), len(fb))
print(f'射程:真值 {len(a)} 条(折叠后 {len(fa)}),宿主 {len(b)} 条(折叠后 {len(fb)}),类别 {len({k[0] for k in fa + fb})} 种;豁免剔除 {load.dropped} 条')
if n is None: print('UICMP 一致'); sys.exit(0)
print(f'UICMP 不一致:折叠后第 {n} 条起')
for lab, f in (('真值', fa), ('宿主', fb)):
print(f' {lab}:'); [print(f" {'>>' if i == n else ' '} {i} {names.get(f[i], f[i])}") for i in range(max(0, n - 3), min(len(f), n + 4))]
sys.exit(1)