Initial public release
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
# dm/tools: tool index
|
||||
|
||||
中文: [README.zh-CN.md](README.zh-CN.md)
|
||||
|
||||
Three kinds of things live here. The first you will use when following the front page or the docs; the second is the measurement and regression scaffolding we use during development, published as is; the third is a set of one-off probes written when the game program was first analysed, kept for the record.
|
||||
|
||||
## What you will use
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `patch_nso.py` | The program rewriter: rewrites the few instructions in the game program that cannot run unchanged under Apple's kernel and leaves everything else byte-for-byte intact. Called by `setup.sh` |
|
||||
| `extract_game.sh` | Extracts the two parts this project needs (program files and resources) from your own game package into the workspace |
|
||||
| `d2rm_pack.py` | Produces a playable install package without Xcode by building your own game files into the "shell"; see [docs/NO_XCODE.md](../../docs/NO_XCODE.md) |
|
||||
| `guest_dylib.py` | Writes the rewritten game program as an Apple-format dynamic library (pure Python, byte-identical output on every system); called by `d2rm_pack.py` |
|
||||
| `winlf/` | Makes the packaging tool chain use `\n` line endings on Windows, so packages made on different systems match |
|
||||
| `product.sh` | The identifier of the current rewrite output lives in one place (`dm/PRODUCT`); scripts get paths through this |
|
||||
| `dmx.py` | A minimal read-only reader for the game's resource storage: list files, fetch a file |
|
||||
| `casc_overlay.py` | Builds the overlay at build time: points chosen resource paths at our new content without touching the original archives |
|
||||
| `astc_pack.py` | Supplement pack for older devices: converts BC-format game textures offline into ASTC, which those devices support |
|
||||
| `gen_bright_levels.py` | Generates the level table used by the 3D brightness boost (built from your game files) |
|
||||
| `tact_bootlist.py` | Generates the startup prefetch list: resource blocks needed before character select, decoded ahead of time at launch |
|
||||
|
||||
## Measurement and regression scaffolding
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `host_savecmp.sh` | Byte-for-byte save comparison: the host replays a game, saves, and the save is compared with a reference |
|
||||
| `save_txn_regress.sh` | Determinism regression for save transactions |
|
||||
| `host_war13.sh` | Host replay of one fixed case, compared tick by tick and by save |
|
||||
| `l3reg.py`, `l3seg.sh`, `l3run.sh`, `test_l3reg.py` | Long-run memory regression: fits the growth of memory and handles against game ticks and extrapolates to a long session |
|
||||
| `frameprobe.sh` | Comparison measurement of frame pacing stability |
|
||||
| `conc_watch.sh` | Concurrency check for timed runs: a timing taken while other heavy work was running is discarded |
|
||||
| `sampagg.py`, `lockalign.py` | Aggregation of sampling logs; call-chain statistics for lock-holding threads |
|
||||
| `hle_inventory.py` | Inventory of the host's system service implementations (full / simplified / stub) |
|
||||
| `sdis.py`, `sideeff.py` | Disassemble one function; walk the call graph for a function's side effects |
|
||||
| `blackcols.py` | Checks a screenshot for fully black columns (whether the picture fills the screen) |
|
||||
| `guirun.sh` | Starts a program inside the graphical session and collects its output |
|
||||
| `mini_sync.sh` | Syncs the workspace to a second Mac for heavy runs (the target is set in the local config) |
|
||||
|
||||
## One-off probes from the early analysis
|
||||
|
||||
`nso.py` (splits the game program into segments), `fn.py` (function boundaries from the unwind table), `sweep.py` (linear instruction sweep), `x18.py` and `cat18.py` (find and classify instructions using x18, a register Apple reserves), `xref_sdk.py` (cross-references of system library functions), `tp.c` (checks how the thread pointer register behaves under Apple's kernel). They were written before the rewrite approach was settled and depend on intermediate files from that time; they are not guaranteed to run as they are. The basis of the rewrite approach is in [dm/README.md](../README.md) and [dm/verify/README.md](../verify/README.md).
|
||||
@@ -0,0 +1,42 @@
|
||||
# dm/tools:工具索引
|
||||
|
||||
English: [README.md](README.md)
|
||||
|
||||
这个目录里的东西分三类。第一类是你照着首页或说明页做事时会用到的;第二类是我们开发时用的测量与回归脚手架,一并放出来;第三类是最早分析游戏程序时写的一次性探针,留作记录。
|
||||
|
||||
## 你会用到的
|
||||
|
||||
| 文件 | 做什么 |
|
||||
|---|---|
|
||||
| `patch_nso.py` | 程序改写器:把游戏程序里在苹果内核下不能原样执行的少数指令改写掉,其余逐字节保持原样。`setup.sh` 会调它 |
|
||||
| `extract_game.sh` | 从你自己的游戏包里取出本项目要的两部分(程序文件与资源),放进工作区 |
|
||||
| `d2rm_pack.py` | 不用 Xcode 出可玩的安装包:把你自己的游戏文件做进「壳」,见 [docs/NO_XCODE.zh-CN.md](../../docs/NO_XCODE.zh-CN.md) |
|
||||
| `guest_dylib.py` | 把改写后的游戏程序写成一个苹果格式的动态库(纯 Python,各系统产出逐字节相同);`d2rm_pack.py` 调它 |
|
||||
| `winlf/` | Windows 上让做包工具链统一用 `\n` 换行,保证各系统做出的包一致 |
|
||||
| `product.sh` | 当前改写产物的代号只写在一处(`dm/PRODUCT`),各脚本经它取路径 |
|
||||
| `dmx.py` | 游戏资源存储的最小读取器(只读):列文件、取文件 |
|
||||
| `casc_overlay.py` | 构建时生成覆盖层:让指定的资源路径指向我们新做的内容,不改动原资源档案 |
|
||||
| `astc_pack.py` | 旧机型补充包:把游戏贴图里的 BC 格式离线转成这些机型支持的 ASTC |
|
||||
| `gen_bright_levels.py` | 生成「3D 画面加亮」用的关卡表(构建时从你的游戏文件现做) |
|
||||
| `tact_bootlist.py` | 生成启动预取清单:进选角页之前会用到的资源块,开局时提前解好 |
|
||||
|
||||
## 测量与回归脚手架
|
||||
|
||||
| 文件 | 做什么 |
|
||||
|---|---|
|
||||
| `host_savecmp.sh` | 存档逐字节对拍:宿主回放一局后存盘,与真值存档比较 |
|
||||
| `save_txn_regress.sh` | 存档事务的确定性回归 |
|
||||
| `host_war13.sh` | 一个固定用例的宿主回放,逐拍与存档对拍 |
|
||||
| `l3reg.py`、`l3seg.sh`、`l3run.sh`、`test_l3reg.py` | 长时间运行的内存回归:按游戏拍数回归内存与句柄的增长斜率,外推到长局 |
|
||||
| `frameprobe.sh` | 帧节奏稳定性的对照量测 |
|
||||
| `conc_watch.sh` | 计时轮次的并发检测:有别的重活在跑的计时一律作废 |
|
||||
| `sampagg.py`、`lockalign.py` | 采样日志的汇总;持锁线程的调用链统计 |
|
||||
| `hle_inventory.py` | 宿主各系统服务实现的盘点(完整 / 简化 / 空实现) |
|
||||
| `sdis.py`、`sideeff.py` | 反汇编一个函数;沿调用图找一个函数的副作用 |
|
||||
| `blackcols.py` | 截图里有没有整列纯黑(画面铺没铺满的检查) |
|
||||
| `guirun.sh` | 在图形会话里起一个程序并收集它的输出 |
|
||||
| `mini_sync.sh` | 把工作区同步到第二台 Mac 上跑重活(目标机在本机配置里填) |
|
||||
|
||||
## 早期分析用的一次性探针
|
||||
|
||||
`nso.py`(拆游戏程序的段)、`fn.py`(从异常表取函数边界)、`sweep.py`(线性扫指令)、`x18.py` 与 `cat18.py`(找出并归类用到苹果保留寄存器 x18 的指令)、`xref_sdk.py`(系统库函数的交叉引用)、`tp.c`(验证线程指针寄存器在苹果内核下的行为)。它们是定下改写方案之前写的,依赖当时的中间文件,不保证能直接跑;改写方案的依据在 [dm/README.zh-CN.md](../README.zh-CN.md) 与 [dm/verify/README.zh-CN.md](../verify/README.zh-CN.md)。
|
||||
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python3
|
||||
"""老机型补充包:把游戏贴图里的 BC3 离线转成 ASTC 4x4(A15 / A16 等显卡不支持 BC 格式的机型用;采用离线转换、不在运行时转)。
|
||||
玩家用自己的游戏文件(Switch 版 RomFS)在 Mac 上生成,仓库里不放任何原版衍生产物。
|
||||
|
||||
做法:
|
||||
- .texture 文件头第 4 字节是游戏自己的格式码,游戏按 main+0x1df0c24 的表映射到 NVN 格式:0x3d → 0x44 BC3、0x3e → 0x48 BC3 sRGB、
|
||||
0x5f → 0x79 ASTC 4x4、0x51 → 0x87 ASTC 4x4 sRGB。游戏原生认 ASTC,所以只换格式码,翻译层照常按 NVN 的 ASTC 建贴图。
|
||||
- BC3 与 ASTC 4x4 都是 4x4 像素一块、每块 16 字节,块线性排布只取决于块网格与块字节数 ⇒ 数据区逐块原地转码,不用解排布。
|
||||
数据区 = 文件头 mip 表首项指向处(偏移 40 的 32 位值 + 40)到文件尾;块与块互不依赖,所以把块拼成一张大图交给 astcenc 编,再按序拆回。
|
||||
- 三类参数:颜色图(0x3e,sRGB)按 sRGB 编;法线图(_NRM,R 恒 255、B 恒 0、G = Y、A = X)与材质图等线性图按四通道线性编。
|
||||
法线图不改通道摆放(不做亮度 + 透明度那种重排),R / B 常量在 ASTC 端点里是精确的,着色器怎么取都与原样一致。
|
||||
- 游戏建贴图时的格式不读 .texture 文件头,而是读 data/hd/texture_desc_cache.json(每张贴图一条:format 61 / 62 = 0x3d / 0x3e,
|
||||
另有内嵌的低分辨率缩略图 thumbnailBase64 = 几级小 mip 的 BC3 块,先上传顶着)。所以这份缓存也一起改:转过的贴图 format 改成 95 / 81,
|
||||
缩略图逐块转 ASTC(缩略图头:mip 数、表起点相对偏移,然后每级一对 (大小, 相对偏移),偏移都从偏移字段自己算——
|
||||
照游戏 main+0x16c2d5c 的读法;第一级数据在 48 字节处,各级首尾相接到文件尾);改好的缓存也放进补充包。
|
||||
- 每张贴图算转码结果与 BC3 解码真值的峰值信噪比(PSNR,四通道合算),写 quality.tsv。
|
||||
BC1 / BC4 / BC5 / BC6H 不在这里转(量小),由翻译层在不支持 BC 的机型上运行时解压。
|
||||
|
||||
完整流程(产物目录 D):
|
||||
1. astc_pack.py <RomFS> D/work 转码(Mac 全核约 7 分钟)
|
||||
2. casc_overlay.py pack <RomFS> D/pack D/work/repl.tsv 0-8 写补充包数据档 00-00000008.data + 条目表 pack_index.tsv
|
||||
3. astc_pack.py finalize D/pack 算大小与 SHA-256:pack.json(随 App 打包用来校验)、
|
||||
D/pack/Legacy Device Pack/{manifest.json, data/00-00000008.data}(下载站与「文件」拷贝用的目录,数据档是硬链接)
|
||||
4. 出 App 包时 DM_ASTC_PACK=D/pack(gen_romfs_overlay.py 据此出 ASTC 版覆盖层)
|
||||
用法:astc_pack.py <RomFS> <输出目录> [--astcenc 路径] [--preset thorough] [--limit N] [--only 路径子串]
|
||||
产物:<输出目录>/files/<逻辑路径>(转好的 .texture)、repl.tsv(逻辑路径<TAB>文件,给 casc_overlay.py)、quality.tsv、summary.txt
|
||||
astcenc:ARM 开源编码器(Apache 2.0),从源码编(cmake -DASTCENC_ISA_NEON=ON),路径用 --astcenc 或环境变量 ASTCENC 给。
|
||||
Legacy Device Pack: converts the BC3 in the game textures to ASTC 4x4 offline (for devices such as A15 / A16 whose GPU does not support BC formats; conversion is done offline, not at runtime).
|
||||
Players generate it on a Mac from their own game files (the Switch version's RomFS); no output derived from the original game is kept in the repository.
|
||||
How it works:
|
||||
- Byte 4 of the .texture file header is the game's own format code, which the game maps to an NVN format through the table at main+0x1df0c24: 0x3d → 0x44 BC3, 0x3e → 0x48 BC3 sRGB,
|
||||
0x5f → 0x79 ASTC 4x4, 0x51 → 0x87 ASTC 4x4 sRGB. The game natively recognizes ASTC, so only the format code is swapped and the translation layer creates the texture as NVN ASTC as usual.
|
||||
- BC3 and ASTC 4x4 are both 4x4 pixels per block and 16 bytes per block, and the linear block layout depends only on the block grid and the bytes per block ⇒ the data area is transcoded in place block by block, with no need to undo the layout.
|
||||
Data area = from where the first entry of the header's mip table points (the 32-bit value at offset 40, + 40) to the end of the file; blocks are independent of one another, so the blocks are stitched into one big image, handed to astcenc to encode, then split back in order.
|
||||
- Three kinds of parameters: color maps (0x3e, sRGB) are encoded as sRGB; normal maps (_NRM, R always 255, B always 0, G = Y, A = X) and linear maps such as material maps are encoded as four-channel linear.
|
||||
The channel placement of normal maps is not changed (no luminance + alpha style rearrangement); the R / B constants are exact in the ASTC endpoints, so however the shader samples them the result matches the original.
|
||||
- When the game creates a texture it does not read the format from the .texture file header but from data/hd/texture_desc_cache.json (one record per texture: format 61 / 62 = 0x3d / 0x3e,
|
||||
plus an embedded low-resolution thumbnail thumbnailBase64 = the BC3 blocks of a few small mip levels, uploaded first as a stand-in). So this cache is edited too: the format of converted textures becomes 95 / 81,
|
||||
and thumbnails are converted to ASTC block by block (thumbnail header: mip count, relative offset of the table start, then one (size, relative offset) pair per level, every offset counted from the offset field itself --
|
||||
following the way the game reads it at main+0x16c2d5c; the first level's data is at byte 48, and the levels follow one another end to end up to the end of the file); the edited cache also goes into the Legacy Device Pack.
|
||||
- For every texture the peak signal-to-noise ratio (PSNR, all four channels together) between the transcoded result and the BC3 decoded ground truth is computed and written to quality.tsv.
|
||||
BC1 / BC4 / BC5 / BC6H are not converted here (small volume); the translation layer decompresses them at runtime on devices that do not support BC.
|
||||
Full flow (build output directory D):
|
||||
1. astc_pack.py <RomFS> D/work transcode (about 7 minutes on all cores of a Mac)
|
||||
2. casc_overlay.py pack <RomFS> D/pack D/work/repl.tsv 0-8 write the Legacy Device Pack data archive 00-00000008.data + entry table pack_index.tsv
|
||||
3. astc_pack.py finalize D/pack compute sizes and SHA-256: pack.json (bundled with the App for verification),
|
||||
D/pack/Legacy Device Pack/{manifest.json, data/00-00000008.data} (the directory used for the download site and for copying via 「文件」(Files); the data archive is a hard link)
|
||||
4. When building the App package set DM_ASTC_PACK=D/pack (gen_romfs_overlay.py uses it to produce the ASTC version of the overlay)
|
||||
Usage: astc_pack.py <RomFS> <output dir> [--astcenc path] [--preset thorough] [--limit N] [--only path substring]
|
||||
Output: <output dir>/files/<logical path> (converted .texture), repl.tsv (logical path<TAB>file, for casc_overlay.py), quality.tsv, summary.txt
|
||||
astcenc: ARM's open-source encoder (Apache 2.0), built from source (cmake -DASTCENC_ISA_NEON=ON); its path is given with --astcenc or the environment variable ASTCENC."""
|
||||
import argparse, os, re, struct, subprocess, sys, tempfile, time
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, '..', 'ios', 'tools'))
|
||||
import touch_layout # _read_entry:按 build_manifest.psv 一行读出解压后的文件内容 | _read_entry: reads the decompressed file content for one line of build_manifest.psv
|
||||
|
||||
CODE_ASTC = {0x3d: 0x5f, 0x3e: 0x51} # 游戏格式码:BC3 → ASTC 4x4、BC3 sRGB → ASTC 4x4 sRGB | Game format codes: BC3 → ASTC 4x4, BC3 sRGB → ASTC 4x4 sRGB
|
||||
BATCH_BLOCKS = 1 << 22 # 每批约 400 万块(6700 万像素,RGBA 256 MiB) | About 4 million blocks per batch (67 million pixels, 256 MiB of RGBA)
|
||||
ROW_BLOCKS = 1024 # 拼图每行 1024 块(宽 4096 像素) | The stitched image has 1024 blocks per row (4096 pixels wide)
|
||||
|
||||
|
||||
def bc3_decode(raw):
|
||||
"""BC3 块 → (块数, 16, 4) uint8,像素按块内行优先。颜色块在 BC3 里一律按四色模式解。 | BC3 blocks → (block count, 16, 4) uint8, pixels in row-major order within each block. In BC3 the color block is always decoded in four-color mode."""
|
||||
b = np.frombuffer(raw, np.uint8).reshape(-1, 16)
|
||||
n = len(b)
|
||||
a0 = b[:, 0].astype(np.int32); a1 = b[:, 1].astype(np.int32)
|
||||
abits = np.zeros(n, np.uint64)
|
||||
for i in range(6): abits |= b[:, 2 + i].astype(np.uint64) << np.uint64(8 * i)
|
||||
k = np.arange(8, dtype=np.int32)
|
||||
p8 = np.where(k == 0, a0[:, None], np.where(k == 1, a1[:, None], ((8 - k) * a0[:, None] + (k - 1) * a1[:, None] + 3) // 7))
|
||||
p6 = np.where(k == 0, a0[:, None], np.where(k == 1, a1[:, None], np.where(k == 6, 0, np.where(k == 7, 255, ((6 - k) * a0[:, None] + (k - 1) * a1[:, None] + 2) // 5))))
|
||||
apal = np.where((a0 > a1)[:, None], p8, p6)
|
||||
aidx = ((abits[:, None] >> (np.uint64(3) * np.arange(16, dtype=np.uint64))) & np.uint64(7)).astype(np.int64)
|
||||
alpha = np.take_along_axis(apal, aidx, 1)
|
||||
c0 = b[:, 8].astype(np.int32) | (b[:, 9].astype(np.int32) << 8); c1 = b[:, 10].astype(np.int32) | (b[:, 11].astype(np.int32) << 8)
|
||||
def rgb(c): r, g, bl = (c >> 11) & 31, (c >> 5) & 63, c & 31; return np.stack([(r << 3) | (r >> 2), (g << 2) | (g >> 4), (bl << 3) | (bl >> 2)], -1)
|
||||
e0, e1 = rgb(c0), rgb(c1)
|
||||
cpal = np.stack([e0, e1, (2 * e0 + e1 + 1) // 3, (e0 + 2 * e1 + 1) // 3], 1) # (n, 4, 3)
|
||||
cbits = b[:, 12].astype(np.uint32) | (b[:, 13].astype(np.uint32) << 8) | (b[:, 14].astype(np.uint32) << 16) | (b[:, 15].astype(np.uint32) << 24)
|
||||
cidx = ((cbits[:, None] >> (np.uint32(2) * np.arange(16, dtype=np.uint32))) & np.uint32(3)).astype(np.int64)
|
||||
col = np.take_along_axis(cpal, cidx[:, :, None].repeat(3, 2), 1)
|
||||
return np.concatenate([col, alpha[:, :, None]], -1).astype(np.uint8)
|
||||
|
||||
|
||||
def blocks_to_image(px):
|
||||
n = len(px); rows = (n + ROW_BLOCKS - 1) // ROW_BLOCKS
|
||||
pad = np.zeros((rows * ROW_BLOCKS - n, 16, 4), np.uint8)
|
||||
a = np.concatenate([px, pad]).reshape(rows, ROW_BLOCKS, 4, 4, 4).transpose(0, 2, 1, 3, 4).reshape(rows * 4, ROW_BLOCKS * 4, 4)
|
||||
return a
|
||||
|
||||
|
||||
def image_to_blocks(img, n):
|
||||
rows = img.shape[0] // 4
|
||||
return img.reshape(rows, 4, ROW_BLOCKS, 4, 4).transpose(0, 2, 1, 3, 4).reshape(-1, 16, 4)[:n]
|
||||
|
||||
|
||||
def encode_batch(enc, preset, srgb, px, tmp):
|
||||
"""px (n,16,4) → (ASTC 块字节 n*16, 解码回来的像素 (n,16,4)) | px (n,16,4) → (ASTC block bytes n*16, pixels decoded back (n,16,4))"""
|
||||
n = len(px); src, out, dec = (os.path.join(tmp, f) for f in ('in.png', 'out.astc', 'dec.png'))
|
||||
Image.fromarray(blocks_to_image(px), 'RGBA').save(src, compress_level=1)
|
||||
prof = '-cs' if srgb else '-cl'
|
||||
subprocess.run([enc, prof, src, out, '4x4', '-' + preset, '-silent'], check=True)
|
||||
a = open(out, 'rb').read()
|
||||
assert a[:4] == bytes.fromhex('13aba15c') and a[4:7] == bytes((4, 4, 1)), 'astcenc 输出头不对'
|
||||
w = int.from_bytes(a[7:10], 'little'); h = int.from_bytes(a[10:13], 'little')
|
||||
assert w == ROW_BLOCKS * 4 and h % 4 == 0
|
||||
blocks = np.frombuffer(a[16:], np.uint8).reshape(h // 4, ROW_BLOCKS, 16).reshape(-1, 16)[:n].tobytes()
|
||||
subprocess.run([enc, '-ds' if srgb else '-dl', out, dec, '-silent'], check=True)
|
||||
back = image_to_blocks(np.asarray(Image.open(dec).convert('RGBA')), n)
|
||||
return blocks, back
|
||||
|
||||
|
||||
def psnr(a, b):
|
||||
mse = float(np.mean((a.astype(np.float64) - b.astype(np.float64)) ** 2))
|
||||
return 99.0 if mse == 0 else 10 * np.log10(255.0 ** 2 / mse)
|
||||
|
||||
|
||||
def finalize(packdir):
|
||||
import hashlib, json
|
||||
idx = open(os.path.join(packdir, 'pack_index.tsv'), encoding='utf-8').readline().rstrip('\n').split('\t')
|
||||
assert idx[0] == '# pack', 'pack_index.tsv 首行不对'
|
||||
name = idx[1]; src = os.path.join(packdir, name); h = hashlib.sha256()
|
||||
with open(src, 'rb') as f:
|
||||
for b in iter(lambda: f.read(64 << 20), b''): h.update(b)
|
||||
info = {'name': name, 'size': os.path.getsize(src), 'sha256': h.hexdigest()}
|
||||
json.dump(info, open(os.path.join(packdir, 'pack.json'), 'w'), ensure_ascii=False, indent=1)
|
||||
root = os.path.join(packdir, '老机型补充包'); os.makedirs(os.path.join(root, 'data'), exist_ok=True)
|
||||
dst = os.path.join(root, 'data', name)
|
||||
if os.path.exists(dst): os.remove(dst)
|
||||
os.link(src, dst)
|
||||
json.dump({'files': [info]}, open(os.path.join(root, 'manifest.json'), 'w'), ensure_ascii=False, indent=1)
|
||||
print(f'astc_pack finalize:{name} {info["size"]} 字节 sha256 {info["sha256"]}')
|
||||
|
||||
|
||||
def desc_cache(o, converted, tmp, repl):
|
||||
"""改 data/hd/texture_desc_cache.json:转过的贴图 format 61 → 95、62 → 81,缩略图逐块转 ASTC | Edit data/hd/texture_desc_cache.json: for converted textures format 61 → 95 and 62 → 81, thumbnails converted to ASTC block by block"""
|
||||
import base64, json
|
||||
logical = 'data/hd/texture_desc_cache.json'
|
||||
row = next(f for f in (l.rstrip('\n').split('|') for l in open(os.path.join(o.romfs, 'data', 'build_manifest.psv'), encoding='utf-8')) if len(f) >= 11 and f[9].split(':', 1)[-1].lower() == logical)
|
||||
J = json.loads(touch_layout._read_entry(o.romfs, row))
|
||||
jobs = {False: [], True: []} # sRGB 分开:[(条目, 缩略图字节, [(块起点, 块数)…], 解码像素)] | Split by sRGB: [(entry, thumbnail bytes, [(block start, block count)...], decoded pixels)]
|
||||
nconv = 0
|
||||
for e in J:
|
||||
p = e['filename'].lower()
|
||||
if p not in converted or e['format'] not in (61, 62): continue
|
||||
srgb = converted[p]
|
||||
if (e['format'] == 62) != srgb: sys.exit(f'astc_pack:{p} 缓存里的格式 {e["format"]} 与文件头不一致')
|
||||
e['format'] = 81 if srgb else 95; nconv += 1
|
||||
t = base64.b64decode(e['thumbnailBase64']) if e.get('thumbnailBase64') else b''
|
||||
if not t: continue
|
||||
n = struct.unpack_from('<I', t, 0)[0]; tab = 4 + struct.unpack_from('<i', t, 4)[0]; regs = []; px = []
|
||||
for i in range(n):
|
||||
size = struct.unpack_from('<I', t, tab + 8 * i)[0]; rf = tab + 8 * i + 4; start = rf + struct.unpack_from('<i', t, rf)[0]
|
||||
if size % 16 or start < tab + 8 * n or start + size > len(t): sys.exit(f'astc_pack:{p} 缩略图第 {i} 级(大小 {size},起点 {start})不是表后的整块')
|
||||
regs.append((start, size // 16)); px.append(bc3_decode(t[start:start + size]))
|
||||
jobs[srgb].append((e, t, regs, np.concatenate(px)))
|
||||
for srgb, items in jobs.items():
|
||||
if not items: continue
|
||||
blocks, _ = encode_batch(o.astcenc, o.preset, srgb, np.concatenate([it[3] for it in items]), tmp)
|
||||
at = 0
|
||||
for e, t, regs, px in items:
|
||||
nt = bytearray(t)
|
||||
for start, nb in regs: nt[start:start + nb * 16] = blocks[at * 16:(at + nb) * 16]; at += nb
|
||||
e['thumbnailBase64'] = base64.b64encode(bytes(nt)).decode()
|
||||
dst = os.path.join(o.out, 'files', logical); os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
open(dst, 'w', encoding='utf-8').write(json.dumps(J, ensure_ascii=False, separators=(',', ':')))
|
||||
repl.write(f'{logical}\t{dst}\n')
|
||||
print(f'astc_pack:贴图描述缓存改了 {nconv} 条(缩略图 {sum(len(v) for v in jobs.values())} 张转 ASTC)')
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) == 3 and sys.argv[1] == 'finalize': finalize(sys.argv[2]); return
|
||||
ap = argparse.ArgumentParser(); ap.add_argument('romfs'); ap.add_argument('out')
|
||||
ap.add_argument('--astcenc', default=os.environ.get('ASTCENC')); ap.add_argument('--preset', default='thorough')
|
||||
ap.add_argument('--limit', type=int, default=0); ap.add_argument('--only', default='')
|
||||
o = ap.parse_args()
|
||||
if not o.astcenc or not os.access(o.astcenc, os.X_OK): sys.exit('astc_pack:找不到 astcenc(--astcenc 或环境变量 ASTCENC)')
|
||||
rows = [l.rstrip('\n').split('|') for l in open(os.path.join(o.romfs, 'data', 'build_manifest.psv'), encoding='utf-8')]
|
||||
rows = [f for f in rows if len(f) >= 11 and f[9].lower().endswith('.texture') and o.only in f[9].lower()]
|
||||
seen = set(); todo = []
|
||||
for f in rows:
|
||||
p = f[9].split(':', 1)[-1].lower()
|
||||
if p not in seen: seen.add(p); todo.append((p, f))
|
||||
if o.limit: todo = todo[:o.limit]
|
||||
os.makedirs(os.path.join(o.out, 'files'), exist_ok=True)
|
||||
t0 = time.time(); stat = {'跳过非 BC3': 0, '转码': 0, '块数': 0}
|
||||
pend = {False: [], True: []} # 按 sRGB 分两批:[(路径, 原字节, 数据起点, 解码像素)] | Two batches split by sRGB: [(path, original bytes, data start, decoded pixels)]
|
||||
qual = open(os.path.join(o.out, 'quality.tsv'), 'w'); qual.write('逻辑路径\t类\t宽\t高\t块数\tPSNR\n')
|
||||
repl = open(os.path.join(o.out, 'repl.tsv'), 'w')
|
||||
tmp = tempfile.mkdtemp(prefix='astc_pack_'); converted = {}
|
||||
|
||||
def flush(srgb):
|
||||
items = pend[srgb]
|
||||
if not items: return
|
||||
px = np.concatenate([it[3] for it in items])
|
||||
blocks, back = encode_batch(o.astcenc, o.preset, srgb, px, tmp)
|
||||
at = 0
|
||||
for p, b, start, dec in items:
|
||||
n = len(dec); nb = bytearray(b); nb[4] = CODE_ASTC[b[4]]; nb[start:] = blocks[at * 16:(at + n) * 16]
|
||||
dst = os.path.join(o.out, 'files', p); os.makedirs(os.path.dirname(dst), exist_ok=True); open(dst, 'wb').write(nb)
|
||||
repl.write(f'{p}\t{dst}\n'); converted[p] = srgb
|
||||
w, h = struct.unpack_from('<II', b, 8)
|
||||
cls = 'sRGB 颜色' if srgb else ('法线' if p.endswith('_nrm.texture') else '线性')
|
||||
qual.write(f'{p}\t{cls}\t{w}\t{h}\t{n}\t{psnr(dec, back[at:at + n]):.2f}\n')
|
||||
at += n
|
||||
pend[srgb] = []
|
||||
print(f'astc_pack:已转 {stat["转码"]} 张、{stat["块数"]} 块,用时 {time.time() - t0:.0f} 秒', flush=True)
|
||||
|
||||
for i, (p, f) in enumerate(todo):
|
||||
b = touch_layout._read_entry(o.romfs, f)
|
||||
if len(b) < 48 or b[4] not in CODE_ASTC: stat['跳过非 BC3'] += 1; continue
|
||||
start = 40 + struct.unpack_from('<I', b, 40)[0]
|
||||
if start >= len(b) or (len(b) - start) % 16: sys.exit(f'astc_pack:{p} 数据区不是 16 字节整块(起点 {start},文件 {len(b)} 字节)')
|
||||
dec = bc3_decode(b[start:]); srgb = b[4] == 0x3e
|
||||
pend[srgb].append((p, b, start, dec)); stat['转码'] += 1; stat['块数'] += len(dec)
|
||||
if sum(len(x[3]) for x in pend[srgb]) >= BATCH_BLOCKS: flush(srgb)
|
||||
flush(False); flush(True); qual.close()
|
||||
desc_cache(o, converted, tmp, repl)
|
||||
repl.close()
|
||||
s = f'astc_pack:贴图 {len(todo)} 张,转码 {stat["转码"]} 张({stat["块数"]} 块),跳过非 BC3 {stat["跳过非 BC3"]} 张;档 {o.preset};墙钟 {time.time() - t0:.0f} 秒'
|
||||
open(os.path.join(o.out, 'summary.txt'), 'w').write(s + '\n'); print(s)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
# 两侧黑柱检查:统计截图里「整列纯黑」(所有像素 RGB 都 ≤ 阈值)的列数,分左半 / 右半报;用于宽屏黑柱回归
|
||||
# 用法:blackcols.py <png> [阈值=4] 退出码 0 = 无整列纯黑
|
||||
# Side black-bar check: counts the columns in a screenshot that are "entirely pure black" (every pixel's RGB ≤ threshold), reported separately for the left half / right half; used for the widescreen black-bar regression
|
||||
# Usage: blackcols.py <png> [threshold=4] exit code 0 = no entirely black column
|
||||
import sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
a = np.asarray(Image.open(sys.argv[1]).convert('RGB')).astype(np.int16)
|
||||
th = int(sys.argv[2]) if len(sys.argv) > 2 else 4
|
||||
black = (a <= th).all(axis=2).all(axis=0)
|
||||
h, w = a.shape[:2]; left = int(black[:w // 2].sum()); right = int(black[w // 2:].sum())
|
||||
runs = []; i = 0
|
||||
while i < w:
|
||||
if black[i]:
|
||||
j = i
|
||||
while j + 1 < w and black[j + 1]: j += 1
|
||||
runs.append((i, j)); i = j + 1
|
||||
else: i += 1
|
||||
print(f'{sys.argv[1]}:{w}x{h},整列纯黑 左 {left} 列、右 {right} 列,区段 {runs[:6]}')
|
||||
sys.exit(1 if left + right else 0)
|
||||
@@ -0,0 +1,551 @@
|
||||
#!/usr/bin/env python3
|
||||
"""构建期改写 Switch 静态 CASC:让指定逻辑路径指向新内容(原生方式,不用 D2R mod、运行时零改动)。
|
||||
|
||||
用法:casc_overlay.py <RomFS> <输出目录> <替换表.tsv>
|
||||
替换表每行「逻辑路径<TAB>新文件」。输出目录 = 覆盖层:改动文件实写,其余逐文件软链接原件;空表 ⇒ 全部链接、逐字节等于原件。
|
||||
|
||||
格式(对原版实算核过,游戏实际读取以 DM_FSLOG 为准):
|
||||
- 游戏只读 data/.build.config 与 data/NN-MMMMMMMM.data;*.psv 清单是提取工具产物,游戏不读(这里只借它查路径 → 旧 EKey,
|
||||
再在 TVFS 容器文件表里按该 EKey 唯一命中定位条目,命中数 ≠ 1 即报错)。
|
||||
- .build.config 的 vfs-root(154 字节小 TVFS)按 EKey 引用 vfs-1(全量 TVFS);vfs-2 与 vfs-root 同键。改文件 ⇒ 新内容、新 vfs-1、
|
||||
新 vfs-root 都写进一个新数据档,再改 .build.config 的 vfs-root / vfs-1 / vfs-2 三行及其 -size。
|
||||
- EKey(16 字节,key-layout 8 8 40)= MD5(存储头)[:9] + 块号 + 档号 + 40 位偏移;存储头:BLTE 为其头部,裸 zlib / 原样为整段。
|
||||
- 按条目规格编码:z = 裸 zlib(级别 9 可逐字节复现原件)、n = 原样、b:… = BLTE(块校验 = MD5(编码块,含模式字节))。
|
||||
- TVFS 容器文件表条目(flags 0x0a):EKey(16) + 编码长(4) + 规格序号(1) + 内容长(4)。
|
||||
- 新增路径:替换表里逻辑路径前加「+」(如 +data/hd/items/weapon/zswg/axe__the_gnasher.json)。只支持「已有目录下新开一个子目录、里面放文件」:
|
||||
新子目录名的首字母不许与该目录现有子项相同(路径树是压缩前缀树,兄弟项首字母互异),按字节序插在兄弟间;新文件在容器文件表 / 文件表末尾各追加一条,
|
||||
祖先目录的尺寸与表头偏移随之更新。写完把整棵路径树重新解析一遍,核「原有路径与文件表位置一个不变 + 新路径都在」。
|
||||
- 路径树单项格式(对原版 13 万条路径核过):[0 = 前置分隔符] [长度 + 名字片段] [0 = 后置分隔符] [FF + 值 4 字节];
|
||||
名字后既不是 0 也不是 FF = 隐含分隔符、名字没完(下一项接着拼);值最高位 = 目录,低 31 位 = 尺寸(目录内容止 = 值之后 + 尺寸 − 4),否则 = 文件表内偏移。
|
||||
原版里 baal、endgame2 两处目录的分隔符写法与此不同(兄弟项共用首项的前置分隔符),新增路径不往这类目录里插。
|
||||
- 独立数据档(老机型补充包):`pack` 子命令把一批替换文件按各自条目的编码规格写进指定档号的数据档,并出条目表
|
||||
(逻辑路径、EKey、编码长、内容长);生成覆盖层时 `--prebuilt 条目表` 让这些路径的 TVFS 条目直接指向那个数据档,内容不再复制进覆盖层的新档。
|
||||
覆盖层自己的新档里,其余替换按原顺序写、索引放最后,所以有没有 --prebuilt,同一批替换在新档里的偏移不变(预取清单照常命中)。
|
||||
Controller/HUDPanelHD.json 的 HealthBall x 141→441,标准存档、不加 -mod 进局,血球右移、HUD 其余不变、无【红】;
|
||||
EKey 或块校验算错时游戏读到新 vfs-root 即退出(有校验)。
|
||||
Build-time rewrite of the Switch static CASC: makes the given logical paths point to new content (the native way, no D2R mod, zero runtime changes).
|
||||
Usage: casc_overlay.py <RomFS> <output dir> <replacement-table.tsv>
|
||||
Each line of the replacement table is "logical path<TAB>new file". Output dir = overlay: changed files are actually written, the rest are symlinked file by file to the originals; empty table ⇒ everything linked, byte-for-byte equal to the originals.
|
||||
Format (computed and verified against the original game; what the game actually reads is determined by DM_FSLOG):
|
||||
- The game reads only data/.build.config and data/NN-MMMMMMMM.data; the *.psv manifests are output of the extraction tool and the game does not read them (here they are only borrowed to look up path → old EKey,
|
||||
then the entry is located in the TVFS container file table by a unique hit on that EKey; a hit count ≠ 1 is an error).
|
||||
- The vfs-root in .build.config (a small 154-byte TVFS) references vfs-1 (the full TVFS) by EKey; vfs-2 has the same key as vfs-root. Changing a file ⇒ the new content, the new vfs-1 and
|
||||
the new vfs-root are all written into one new data archive, then the three lines vfs-root / vfs-1 / vfs-2 in .build.config and their -size are changed.
|
||||
- EKey (16 bytes, key-layout 8 8 40) = MD5(storage header)[:9] + chunk number + archive number + 40-bit offset; storage header: for BLTE its header, for raw zlib / as is the whole segment.
|
||||
- Encode by entry spec: z = raw zlib (level 9 reproduces the original byte for byte), n = as is, b:... = BLTE (block checksum = MD5(encoded block, including the mode byte)).
|
||||
- TVFS container file table entry (flags 0x0a): EKey(16) + encoded length(4) + spec index(1) + content length(4).
|
||||
- Adding paths: prefix the logical path in the replacement table with "+" (e.g. +data/hd/items/weapon/zswg/axe__the_gnasher.json). Only "open one new subdirectory under an existing directory and put files in it" is supported:
|
||||
the first letter of the new subdirectory name must not equal that of any existing child of that directory (the path tree is a compressed prefix tree, sibling items have distinct first letters), and it is inserted among the siblings in byte order; each new file appends one record at the end of the container file table / file table,
|
||||
and the sizes of the ancestor directories and the header offsets are updated accordingly. After writing, the whole path tree is parsed again to verify "no existing path or file table position changed + all new paths present".
|
||||
- Format of a single path tree item (verified against the original game's 130 thousand paths): [0 = leading separator] [length + name fragment] [0 = trailing separator] [FF + 4-byte value];
|
||||
if what follows the name is neither 0 nor FF = implicit separator, the name is unfinished (the next item continues it); top bit of the value = directory, low 31 bits = size (directory content end = after the value + size − 4), otherwise = offset within the file table.
|
||||
In the original game the directories baal and endgame2 write their separators differently (sibling items share the first item's leading separator); added paths are not inserted into such directories.
|
||||
- Standalone data archive (Legacy Device Pack): the `pack` subcommand writes a batch of replacement files into the data archive with the given archive number using each entry's own encoding spec, and produces an entry table
|
||||
(logical path, EKey, encoded length, content length); when generating the overlay, `--prebuilt entry-table` makes the TVFS entries of those paths point directly at that data archive, and the content is no longer copied into the overlay's new archive.
|
||||
In the overlay's own new archive the remaining replacements are written in the original order with the index last, so with or without --prebuilt the offsets of the same batch of replacements in the new archive do not change (the prefetch list still hits as usual).
|
||||
Controller/HUDPanelHD.json HealthBall x 141→441, standard save, entering a run without -mod: the health globe moves right, the rest of the HUD is unchanged, no 【红】 (red);
|
||||
when the EKey or block checksum is computed wrong the game exits as soon as it reads the new vfs-root (it is checksummed).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
|
||||
def die(message):
|
||||
raise SystemExit(f"casc_overlay.py: {message}")
|
||||
|
||||
|
||||
def norm_path(value):
|
||||
value = value.strip().replace("\\", "/")
|
||||
while value.lower().startswith("data:"):
|
||||
value = value[5:]
|
||||
return value.lstrip("/").lower()
|
||||
|
||||
|
||||
def read_replacements(filename):
|
||||
result = {}
|
||||
with open(filename, encoding="utf-8") as stream:
|
||||
for number, line in enumerate(stream, 1):
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
fields = line.rstrip("\n").split("\t")
|
||||
if len(fields) != 2:
|
||||
die(f"{filename}:{number}: expected path<TAB>file")
|
||||
add = fields[0].startswith("+")
|
||||
logical, replacement = ("+" if add else "") + norm_path(fields[0].lstrip("+")), Path(fields[1])
|
||||
if not logical or logical in result:
|
||||
die(f"{filename}:{number}: duplicate or empty logical path")
|
||||
if not replacement.is_file():
|
||||
die(f"{filename}:{number}: replacement is not a file: {replacement}")
|
||||
result[logical] = replacement
|
||||
return result
|
||||
|
||||
|
||||
def link_tree(source, output, skip=()):
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for entry in source.iterdir():
|
||||
if entry.name in skip:
|
||||
continue
|
||||
target = output / entry.name
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
link_tree(entry, target)
|
||||
else:
|
||||
target.symlink_to(entry.resolve())
|
||||
|
||||
|
||||
def read_manifest(source):
|
||||
result = {}
|
||||
filename = source / "data" / "build_manifest.psv"
|
||||
if not filename.is_file():
|
||||
die(f"missing {filename}; TVFS lookup needs the extraction manifest")
|
||||
with filename.open(encoding="utf-8") as stream:
|
||||
for line in stream:
|
||||
fields = line.rstrip("\n").split("|")
|
||||
if len(fields) < 11 or fields[0].startswith("#"):
|
||||
continue
|
||||
path = norm_path(fields[9])
|
||||
if path and path not in result:
|
||||
result[path] = fields
|
||||
return result
|
||||
|
||||
|
||||
def read_data_file(data_dir, ekey, encoded_size):
|
||||
chunk, archive = ekey[9], ekey[10]
|
||||
filename = data_dir / f"{chunk:02d}-{archive:08d}.data"
|
||||
with filename.open("rb") as stream:
|
||||
stream.seek(int.from_bytes(ekey[11:16], "big"))
|
||||
raw = stream.read(encoded_size)
|
||||
if raw[:4] != b"BLTE":
|
||||
die(f"expected BLTE at {filename}:{int.from_bytes(ekey[11:16], 'big'):#x}")
|
||||
header_size = struct.unpack(">I", raw[4:8])[0]
|
||||
block_count = int.from_bytes(raw[9:12], "big")
|
||||
position, output = header_size, bytearray()
|
||||
for index in range(block_count):
|
||||
encoded, decoded = struct.unpack(">II", raw[12 + index * 24:20 + index * 24])
|
||||
block = raw[position:position + encoded]
|
||||
if block[:1] == b"N":
|
||||
content = block[1:]
|
||||
elif block[:1] == b"Z":
|
||||
content = zlib.decompress(block[1:])
|
||||
else:
|
||||
die(f"unsupported BLTE block mode {block[:1]!r}")
|
||||
if len(content) != decoded:
|
||||
die("BLTE decoded length mismatch")
|
||||
output.extend(content)
|
||||
position += encoded
|
||||
return bytes(output)
|
||||
|
||||
|
||||
def blte_encode(content, block_size=256 * 1024):
|
||||
blocks = []
|
||||
for start in range(0, len(content), block_size):
|
||||
block = content[start:start + block_size]
|
||||
blocks.append((b"Z" + zlib.compress(block, 9), block))
|
||||
if not blocks:
|
||||
blocks.append((b"N", b""))
|
||||
header_size = 12 + 24 * len(blocks)
|
||||
header = bytearray(b"BLTE" + struct.pack(">I", header_size) + b"\x0f" + len(blocks).to_bytes(3, "big"))
|
||||
for encoded, block in blocks:
|
||||
header.extend(struct.pack(">II", len(encoded), len(block)))
|
||||
header.extend(hashlib.md5(encoded).digest()) # 块校验 = MD5(编码后的块,含模式字节);对原版 vfs-root / vfs-1 实算核过 | Block checksum = MD5(encoded block, including the mode byte); computed and verified against the original game's vfs-root / vfs-1
|
||||
return bytes(header) + b"".join(encoded for encoded, _ in blocks)
|
||||
|
||||
|
||||
def available_location(data_dir):
|
||||
used = set()
|
||||
for entry in data_dir.glob("??-????????.data"):
|
||||
try:
|
||||
used.add((int(entry.name[:2]), int(entry.name[3:11])))
|
||||
except ValueError:
|
||||
continue
|
||||
for chunk in range(256):
|
||||
for archive in range(1, 0x100000000):
|
||||
if (chunk, archive) not in used:
|
||||
return chunk, archive
|
||||
die("no unused data-file location")
|
||||
|
||||
|
||||
def config_values(filename):
|
||||
lines = filename.read_text(encoding="utf-8").splitlines(keepends=True)
|
||||
values = {}
|
||||
for line in lines:
|
||||
if " = " in line and not line.startswith("#"):
|
||||
key, value = line.rstrip("\n").split(" = ", 1)
|
||||
values[key] = value
|
||||
return lines, values
|
||||
|
||||
|
||||
def replace_config(lines, key, value):
|
||||
prefix = key + " = "
|
||||
return [prefix + value + "\n" if line.startswith(prefix) else line for line in lines]
|
||||
|
||||
|
||||
def path_entry(tvfs, pos):
|
||||
"""路径树单项 → (下一项起点, 前置分隔符, 名字, 后置分隔符 0 无 / 1 显式 / 2 隐含, 值或 None) | Single path tree item → (next item start, leading separator, name, trailing separator 0 none / 1 explicit / 2 implicit, value or None)"""
|
||||
pre = post = 0
|
||||
name = b""
|
||||
value = None
|
||||
if tvfs[pos] == 0:
|
||||
pre, pos = 1, pos + 1
|
||||
if tvfs[pos] != 0xFF:
|
||||
length = tvfs[pos]
|
||||
name, pos = bytes(tvfs[pos + 1:pos + 1 + length]), pos + 1 + length
|
||||
if tvfs[pos] == 0:
|
||||
post, pos = 1, pos + 1
|
||||
if tvfs[pos] == 0xFF:
|
||||
value, pos = struct.unpack(">I", tvfs[pos + 1:pos + 5])[0], pos + 5
|
||||
else:
|
||||
post = 2
|
||||
return pos, pre, name, post, value
|
||||
|
||||
|
||||
def walk_paths(tvfs, start, end, prefix=b"", parents=()):
|
||||
"""逐项产出 (项起点, 到本项为止的路径, 值, 目录内容 (起, 止) 或 None, 祖先目录项起点) | Yields per item (item start, path up to this item, value, directory content (start, end) or None, ancestor directory item starts)"""
|
||||
pos, base = start, prefix
|
||||
while pos < end:
|
||||
entry = pos
|
||||
pos, pre, name, post, value = path_entry(tvfs, pos)
|
||||
prefix = prefix + (b"/" if pre else b"") + name + (b"/" if post else b"")
|
||||
if value is None:
|
||||
continue
|
||||
if value & 0x80000000:
|
||||
folder_end = pos + (value & 0x7FFFFFFF) - 4
|
||||
yield entry, prefix, value, (pos, folder_end), parents
|
||||
yield from walk_paths(tvfs, pos, folder_end, prefix, parents + (entry,))
|
||||
pos = folder_end
|
||||
else:
|
||||
yield entry, prefix, value, None, parents
|
||||
prefix = base
|
||||
|
||||
|
||||
def trie_bytes(names):
|
||||
"""一个目录里的文件 {名字 bytes: 文件表偏移} → 压缩前缀树编码(兄弟项首字母互异);返回 (字节, 最大嵌套层数) | Files in one directory {name bytes: file table offset} → compressed prefix tree encoding (sibling items have distinct first letters); returns (bytes, maximum nesting depth)"""
|
||||
out, depth = bytearray(), 0
|
||||
groups = {}
|
||||
for name in sorted(names):
|
||||
groups.setdefault(name[:1], []).append(name)
|
||||
for _, group in sorted(groups.items()):
|
||||
if len(group) == 1:
|
||||
name = group[0]
|
||||
out += bytes((len(name),)) + name + b"\xff" + struct.pack(">I", names[name])
|
||||
continue
|
||||
common = group[0]
|
||||
for name in group[1:]:
|
||||
while not name.startswith(common):
|
||||
common = common[:-1]
|
||||
if any(name == common for name in group):
|
||||
die("新增路径:一个文件名是另一个的前缀,前缀树编码不了: " + common.decode())
|
||||
sub, sub_depth = trie_bytes({name[len(common):]: names[name] for name in group})
|
||||
out += bytes((len(common),)) + common + b"\xff" + struct.pack(">I", 0x80000000 | (len(sub) + 4)) + sub
|
||||
depth = max(depth, sub_depth + 1)
|
||||
if any(len(name) > 0xFE for name in names):
|
||||
die("新增路径:名字片段超过 254 字节")
|
||||
return out, depth
|
||||
|
||||
|
||||
def offset_field_size(size):
|
||||
return 1 if size <= 0xFF else 2 if size <= 0xFFFF else 3 if size <= 0xFFFFFF else 4
|
||||
|
||||
|
||||
def add_paths(tvfs, additions):
|
||||
"""additions:{逻辑路径 str: (EKey 16 字节, 编码长, 规格序号, 内容长)} → 加好路径的新 TVFS(bytearray) | additions: {logical path str: (EKey 16 bytes, encoded length, spec index, content length)} → new TVFS with the paths added (bytearray)"""
|
||||
path_off, path_size, vfs_off, vfs_size, cft_off, cft_size = struct.unpack(">IIIIII", tvfs[12:36])
|
||||
est_off, est_size = struct.unpack(">II", tvfs[38:46])
|
||||
if not (path_off + path_size == est_off and est_off + est_size == cft_off and cft_off + cft_size == vfs_off and vfs_off + vfs_size == len(tvfs)):
|
||||
die("TVFS 各表不是首尾相接的(头 / 路径树 / 规格表 / 容器文件表 / 文件表),不认识这种布局")
|
||||
before = {path: value for _, path, value, folder, _ in walk_paths(tvfs, path_off, path_off + path_size) if folder is None}
|
||||
nodes = {path: (entry, folder, parents) for entry, path, value, folder, parents in walk_paths(tvfs, path_off, path_off + path_size) if folder}
|
||||
cft_field = offset_field_size(cft_size)
|
||||
if offset_field_size(cft_size + 25 * len(additions)) != cft_field:
|
||||
die("新增路径会让容器文件表偏移字段变宽,要重写全部文件表条目(没实现)")
|
||||
vfs_entry = 1 + 4 + 4 + cft_field
|
||||
new_cft, new_vfs = bytearray(), bytearray()
|
||||
groups = {} # (父目录, 新子目录) → {文件名: 文件表偏移} | (parent directory, new subdirectory) → {file name: file table offset}
|
||||
for number, (logical, (ekey, encoded, espec, content)) in enumerate(sorted(additions.items())):
|
||||
parts = logical.encode().rsplit(b"/", 2)
|
||||
if len(parts) != 3:
|
||||
die("新增路径须是「已有目录/新子目录/文件」: " + logical)
|
||||
parent, folder, name = parts[0] + b"/", parts[1], parts[2]
|
||||
groups.setdefault((parent, folder), {})[name] = vfs_size + number * vfs_entry
|
||||
new_cft += ekey + struct.pack(">I", encoded) + bytes((espec,)) + struct.pack(">I", content)
|
||||
new_vfs += b"\x01" + struct.pack(">II", 0, content) + (cft_size + number * 25).to_bytes(cft_field, "big")
|
||||
path = bytearray(tvfs[path_off:path_off + path_size]) # 以下位置都相对路径树起点 | All positions below are relative to the start of the path tree
|
||||
grown = {} # 祖先目录项起点(相对)→ 增量 | Ancestor directory item start (relative) → delta
|
||||
inserts = []
|
||||
max_depth = struct.unpack(">H", tvfs[36:38])[0]
|
||||
for (parent, folder), names in sorted(groups.items()):
|
||||
if parent.lower() not in {key.lower() for key in nodes}:
|
||||
die("新增路径:父目录在路径树里不是一个目录项: " + parent.decode())
|
||||
entry, (start, end), parents = next(nodes[key] for key in nodes if key.lower() == parent.lower())
|
||||
if any(key.lower().startswith(parent.lower() + folder.lower()) for key in list(before) + list(nodes)):
|
||||
die("新增路径:子目录已存在或与已有名字同前缀: " + (parent + folder).decode())
|
||||
sub, depth = trie_bytes(names)
|
||||
block = bytes((len(folder),)) + folder + b"\x00\xff" + struct.pack(">I", 0x80000000 | (len(sub) + 4)) + sub
|
||||
at, pos, cont = end, start, False
|
||||
while pos < end: # 父目录的直接子项:首字母互异、按字节序;插在第一个首字母更大的前面(名字没完的续项不算新子项) | Direct children of the parent directory: first letters all differ, in byte order; insert before the first one with a larger first letter (a continuation item whose name is unfinished does not count as a new child)
|
||||
child = pos
|
||||
pos, pre, name, post, value = path_entry(tvfs, pos)
|
||||
first, was_cont, cont = (b"/" if pre else name[:1]), cont, value is None
|
||||
if was_cont:
|
||||
if value is not None and value & 0x80000000:
|
||||
pos = pos + (value & 0x7FFFFFFF) - 4
|
||||
continue
|
||||
if first == folder[:1]:
|
||||
die("新增路径:新子目录首字母与已有子项冲突: " + (parent + folder).decode())
|
||||
if first > folder[:1] and at == end:
|
||||
at = child
|
||||
if value is not None and value & 0x80000000:
|
||||
pos = pos + (value & 0x7FFFFFFF) - 4
|
||||
inserts.append((at - path_off, block))
|
||||
for ancestor in parents + (entry,):
|
||||
grown[ancestor - path_off] = grown.get(ancestor - path_off, 0) + len(block)
|
||||
max_depth = max(max_depth, len(parents) + 2 + depth)
|
||||
for rel, delta in grown.items(): # 祖先目录尺寸(项内位置不受插入影响:插入点都在各自目录内容里,晚于值字段) | Ancestor directory sizes (positions inside an item are not affected by insertion: every insertion point is inside its own directory's content, after the value field)
|
||||
value_at = path_entry(path, rel)[0] - 4
|
||||
value = struct.unpack(">I", path[value_at:value_at + 4])[0]
|
||||
path[value_at:value_at + 4] = struct.pack(">I", 0x80000000 | ((value & 0x7FFFFFFF) + delta))
|
||||
for rel, block in sorted(inserts, reverse=True):
|
||||
path[rel:rel] = block
|
||||
head = bytearray(tvfs[:path_off])
|
||||
est = tvfs[est_off:est_off + est_size]
|
||||
cft = tvfs[cft_off:cft_off + cft_size] + new_cft
|
||||
vfs = tvfs[vfs_off:vfs_off + vfs_size] + new_vfs
|
||||
n_path_off = path_off
|
||||
n_est_off = n_path_off + len(path)
|
||||
n_cft_off = n_est_off + len(est)
|
||||
n_vfs_off = n_cft_off + len(cft)
|
||||
head[12:36] = struct.pack(">IIIIII", n_path_off, len(path), n_vfs_off, len(vfs), n_cft_off, len(cft))
|
||||
head[36:38] = struct.pack(">H", max_depth)
|
||||
head[38:42] = struct.pack(">I", n_est_off)
|
||||
result = head + path + est + cft + vfs
|
||||
after = {p: v for _, p, v, folder, _ in walk_paths(result, n_path_off, n_path_off + len(path)) if folder is None}
|
||||
added = {p: v for p, v in after.items() if p not in before}
|
||||
if any(after.get(p) != v for p, v in before.items()):
|
||||
die("新增路径自检:原有路径或其文件表位置变了")
|
||||
if sorted(p.decode().lower() for p in added) != sorted(additions):
|
||||
die(f"新增路径自检:解析出来的新路径与要加的不一致({len(added)} / {len(additions)})")
|
||||
return result
|
||||
|
||||
|
||||
def set_cft_sizes(tvfs, pos, encoded_size, content_size):
|
||||
"""TVFS 容器文件表条目(本构建 flags=0x0a:带编码规格表、无 CKey):EKey(16) + 编码长(4) + 规格序号(1) + 内容长(4)。
|
||||
规格序号宽度 = 表示规格表大小所需字节数(vfs-root 表 12 字节、vfs-1 表 13 字节 ⇒ 1),序号原样保留。
|
||||
TVFS container file table entry (this build has flags=0x0a: with encoding spec table, no CKey): EKey(16) + encoded length(4) + spec index(1) + content length(4).
|
||||
Spec index width = number of bytes needed to represent the spec table size (vfs-root table 12 bytes, vfs-1 table 13 bytes ⇒ 1); the index is kept as is."""
|
||||
est_size = struct.unpack(">I", tvfs[42:46])[0]
|
||||
idx = 1 if est_size <= 0xff else 2 if est_size <= 0xffff else 3 if est_size <= 0xffffff else 4
|
||||
tvfs[pos + 16:pos + 20] = struct.pack(">I", encoded_size)
|
||||
tvfs[pos + 20 + idx:pos + 24 + idx] = struct.pack(">I", content_size)
|
||||
|
||||
|
||||
def cft_position(vfs_content, cft_offset, cft_end, manifest, logical):
|
||||
"""逻辑路径 → 它在 TVFS 容器文件表里的条目位置(按旧 EKey 唯一命中) | Logical path → the position of its entry in the TVFS container file table (unique hit by the old EKey)"""
|
||||
row = manifest.get(logical)
|
||||
if row is None:
|
||||
die("path not found in build_manifest.psv: " + logical)
|
||||
old_ekey = bytes.fromhex(row[6])
|
||||
matches = []
|
||||
search_at = cft_offset
|
||||
while True:
|
||||
position = vfs_content.find(old_ekey, search_at, cft_end)
|
||||
if position < 0:
|
||||
break
|
||||
matches.append(position)
|
||||
search_at = position + 1
|
||||
if len(matches) != 1:
|
||||
die(f"CFT key match count for {logical}: {len(matches)}")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def load_vfs1(source):
|
||||
data_dir = source / "data"
|
||||
lines, values = config_values(data_dir / ".build.config")
|
||||
vfs_key, vfs_ekey = values["vfs-1"].split()
|
||||
vfs_decoded_size, vfs_encoded_size = map(int, values["vfs-1-size"].split())
|
||||
vfs_content = bytearray(read_data_file(data_dir, bytes.fromhex(vfs_ekey), vfs_encoded_size))
|
||||
if len(vfs_content) != vfs_decoded_size or vfs_content[:4] != b"TVFS":
|
||||
die("vfs-1 is not a valid TVFS manifest")
|
||||
return vfs_content
|
||||
|
||||
|
||||
def encode_by_espec(content, espec):
|
||||
# 按条目规格编码(对原版实算):z = 裸 zlib(级别 9 可逐字节复现原件)、n = 原样、b:… = BLTE 容器
|
||||
# Encode by entry spec (computed and checked against the original game): z = raw zlib (level 9 reproduces the original byte for byte), n = as is, b:... = BLTE container
|
||||
return zlib.compress(content, 9) if espec == "z" else content if espec == "n" else blte_encode(content)
|
||||
|
||||
|
||||
def ekey_for(encoded, chunk, archive, offset):
|
||||
header_size = struct.unpack(">I", encoded[4:8])[0] if encoded[:4] == b"BLTE" else len(encoded)
|
||||
return hashlib.md5(encoded[:header_size]).digest()[:9] + bytes((chunk, archive)) + offset.to_bytes(5, "big") # EKey 前 9 字节 = MD5(BLTE 头),后 7 字节 = 块号 / 档号 / 偏移(key-layout 8 8 40) | First 9 bytes of EKey = MD5(BLTE header), last 7 bytes = chunk number / archive number / offset (key-layout 8 8 40)
|
||||
|
||||
|
||||
def write_pack(source, output, replacements, location):
|
||||
"""独立数据档:replacements 逐条按其 TVFS 条目的编码规格写进 output/<块号>-<档号>.data,出条目表 output/pack_index.tsv。
|
||||
location = (块号, 档号),须是原 RomFS 里没用过的位置。各条编码互不依赖,用多进程并行压缩
|
||||
Standalone data archive: writes each of replacements into output/<chunk number>-<archive number>.data using the encoding spec of its TVFS entry, and produces the entry table output/pack_index.tsv.
|
||||
location = (chunk number, archive number), which must be a location not used in the original RomFS. The entries are encoded independently, so compression runs in parallel across multiple processes"""
|
||||
import concurrent.futures as cf
|
||||
chunk, archive = location
|
||||
data_dir = source / "data"
|
||||
name = f"{chunk:02d}-{archive:08d}.data"
|
||||
if (data_dir / name).exists():
|
||||
die(f"pack location {name} already exists in source RomFS")
|
||||
vfs_content = load_vfs1(source)
|
||||
manifest = read_manifest(source)
|
||||
cft_offset, cft_size = struct.unpack(">II", vfs_content[28:36])
|
||||
est_off, est_size = struct.unpack(">II", vfs_content[38:46])
|
||||
especs = bytes(vfs_content[est_off:est_off + est_size]).split(b"\0")
|
||||
items = []
|
||||
for logical, replacement in replacements.items():
|
||||
if logical.startswith("+"):
|
||||
die("pack 不支持新增路径: " + logical)
|
||||
pos = cft_position(vfs_content, cft_offset, cft_offset + cft_size, manifest, logical)
|
||||
items.append((logical, replacement, especs[vfs_content[pos + 20]].decode()))
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
offset = 0
|
||||
with (output / name).open("wb") as data, (output / "pack_index.tsv").open("w", encoding="utf-8") as index, cf.ProcessPoolExecutor() as pool:
|
||||
index.write(f"# pack\t{name}\n")
|
||||
for (logical, _, _), (encoded, decoded_size) in zip(items, pool.map(_encode_one, [(str(r), e) for _, r, e in items], chunksize=16)):
|
||||
ekey = ekey_for(encoded, chunk, archive, offset)
|
||||
data.write(encoded)
|
||||
index.write(f"{logical}\t{ekey.hex()}\t{len(encoded)}\t{decoded_size}\n")
|
||||
offset += len(encoded)
|
||||
print(f"pack: {len(items)} file(s) → {name}, {offset} bytes")
|
||||
|
||||
|
||||
def _encode_one(job):
|
||||
path, espec = job
|
||||
content = Path(path).read_bytes()
|
||||
return encode_by_espec(content, espec), len(content)
|
||||
|
||||
|
||||
def read_prebuilt(filename):
|
||||
result = {}
|
||||
for line in Path(filename).read_text(encoding="utf-8").splitlines():
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
logical, ekey, encoded_size, decoded_size = line.split("\t")
|
||||
result[norm_path(logical)] = (bytes.fromhex(ekey), int(encoded_size), int(decoded_size))
|
||||
return result
|
||||
|
||||
|
||||
def rewrite_tvfs(source, output, replacements, prebuilt=None):
|
||||
data_dir = source / "data"
|
||||
config = data_dir / ".build.config"
|
||||
lines, values = config_values(config)
|
||||
if "vfs-1" not in values or "vfs-1-size" not in values:
|
||||
die(f"missing vfs-1 in {config}")
|
||||
vfs_key, vfs_ekey = values["vfs-1"].split()
|
||||
vfs_decoded_size, vfs_encoded_size = map(int, values["vfs-1-size"].split())
|
||||
vfs_content = bytearray(read_data_file(data_dir, bytes.fromhex(vfs_ekey), vfs_encoded_size))
|
||||
if len(vfs_content) != vfs_decoded_size or vfs_content[:4] != b"TVFS":
|
||||
die("vfs-1 is not a valid TVFS manifest")
|
||||
|
||||
manifest = read_manifest(source)
|
||||
cft_offset, cft_size = struct.unpack(">II", vfs_content[28:36])
|
||||
cft_end = cft_offset + cft_size
|
||||
if cft_end > len(vfs_content):
|
||||
die("unsupported TVFS CFT bounds")
|
||||
|
||||
updates = []
|
||||
adds = {k[1:]: v for k, v in replacements.items() if k.startswith("+")}
|
||||
replacements = {k: v for k, v in replacements.items() if not k.startswith("+")}
|
||||
for logical, replacement in replacements.items():
|
||||
updates.append((cft_position(vfs_content, cft_offset, cft_end, manifest, logical), replacement.read_bytes()))
|
||||
prebuilt_pos = [(cft_position(vfs_content, cft_offset, cft_end, manifest, logical), entry) for logical, entry in (prebuilt or {}).items()]
|
||||
|
||||
new_chunk, new_archive = available_location(data_dir)
|
||||
new_data = bytearray()
|
||||
|
||||
def append(content, espec="b:256K*=z"):
|
||||
encoded = encode_by_espec(content, espec)
|
||||
offset = len(new_data)
|
||||
new_data.extend(encoded)
|
||||
return ekey_for(encoded, new_chunk, new_archive, offset), len(content), len(encoded)
|
||||
|
||||
est_off, est_size = struct.unpack(">II", vfs_content[38:46])
|
||||
especs = bytes(vfs_content[est_off:est_off + est_size]).split(b"\0")
|
||||
for pos, content in updates:
|
||||
espec = especs[vfs_content[pos + 20]].decode() # 规格序号 1 字节(规格表 13 字节) | Spec index is 1 byte (spec table is 13 bytes)
|
||||
ekey, decoded_size, encoded_size = append(content, espec)
|
||||
vfs_content[pos:pos + 9] = ekey[:9]
|
||||
vfs_content[pos + 9:pos + 16] = ekey[9:]
|
||||
set_cft_sizes(vfs_content, pos, encoded_size, decoded_size)
|
||||
for pos, (ekey, encoded_size, decoded_size) in prebuilt_pos: # 独立数据档里已写好的条目:只改指向,不复制内容 | Entries already written in the standalone data archive: only repoint them, do not copy the content
|
||||
vfs_content[pos:pos + 16] = ekey
|
||||
set_cft_sizes(vfs_content, pos, encoded_size, decoded_size)
|
||||
|
||||
if adds:
|
||||
espec_index = next((i for i, e in enumerate(especs) if e == b"z"), 0) # 新文件用裸 zlib(与原版小文件同) | New files use raw zlib (same as small files in the original game)
|
||||
encoded_adds = {}
|
||||
for logical, replacement in adds.items():
|
||||
if logical in manifest:
|
||||
die("新增路径已存在(应作替换): " + logical)
|
||||
ekey, decoded_size, encoded_size = append(replacement.read_bytes(), especs[espec_index].decode())
|
||||
encoded_adds[logical] = (ekey, encoded_size, espec_index, decoded_size)
|
||||
vfs_content = add_paths(vfs_content, encoded_adds)
|
||||
new_vfs_ekey, new_vfs_decoded, new_vfs_encoded = append(bytes(vfs_content))
|
||||
# 游戏只从 .build.config 取 vfs-root(DM_FSLOG 实测),vfs-root 的 CFT 再按 EKey 引用 vfs-1
|
||||
# ⇒ vfs-root 里指向 vfs-1 的条目也要换成新键,vfs-root 本身写进新档;vfs-2 与 vfs-root 同键,一起改
|
||||
# The game takes only vfs-root from .build.config (measured with DM_FSLOG), and the CFT of vfs-root in turn references vfs-1 by EKey
|
||||
# ⇒ the entry in vfs-root that points to vfs-1 must also be changed to the new key, and vfs-root itself is written into the new archive; vfs-2 has the same key as vfs-root and is changed along with it
|
||||
root_ckey, root_ekey = values["vfs-root"].split()
|
||||
root_decoded_size, root_encoded_size = map(int, values["vfs-root-size"].split())
|
||||
root = bytearray(read_data_file(data_dir, bytes.fromhex(root_ekey), root_encoded_size))
|
||||
if len(root) != root_decoded_size or root[:4] != b"TVFS":
|
||||
die("vfs-root is not a valid TVFS manifest")
|
||||
old_vfs = bytes.fromhex(vfs_ekey)
|
||||
hits = [i for i in range(len(root) - 15) if root[i:i + 16] == old_vfs]
|
||||
if len(hits) != 1:
|
||||
die(f"vfs-root 里 vfs-1 键命中 {len(hits)} 次(期望 1)")
|
||||
pos = hits[0]
|
||||
root[pos:pos + 16] = new_vfs_ekey
|
||||
set_cft_sizes(root, pos, new_vfs_encoded, new_vfs_decoded)
|
||||
new_root_ekey, new_root_decoded, new_root_encoded = append(bytes(root))
|
||||
data_name = f"{new_chunk:02d}-{new_archive:08d}.data"
|
||||
(output / "data" / data_name).write_bytes(new_data)
|
||||
new_config = replace_config(lines, "vfs-1", hashlib.md5(bytes(vfs_content)).hexdigest() + " " + new_vfs_ekey.hex())
|
||||
new_config = replace_config(new_config, "vfs-1-size", f"{new_vfs_decoded} {new_vfs_encoded}")
|
||||
root_value = hashlib.md5(bytes(root)).hexdigest() + " " + new_root_ekey.hex()
|
||||
for key in ("vfs-root", "vfs-2"):
|
||||
if values.get(key) == values["vfs-root"]:
|
||||
new_config = replace_config(new_config, key, root_value)
|
||||
new_config = replace_config(new_config, key + "-size", f"{new_root_decoded} {new_root_encoded}")
|
||||
(output / "data" / ".build.config").write_text("".join(new_config), encoding="utf-8")
|
||||
for entry in data_dir.iterdir():
|
||||
if entry.name not in {".build.config", data_name}:
|
||||
(output / "data" / entry.name).symlink_to(entry.resolve())
|
||||
print(f"overlay: {len(updates)} replacement(s), {len(adds)} addition(s), {len(prebuilt_pos)} prebuilt, TVFS rewritten, data={data_name}")
|
||||
|
||||
|
||||
def make_overlay(source, output, replacements, prebuilt=None):
|
||||
if output.exists():
|
||||
die(f"output already exists: {output}")
|
||||
link_tree(source, output, {"data"})
|
||||
(output / "data").mkdir()
|
||||
if not replacements and not prebuilt:
|
||||
for entry in (source / "data").iterdir():
|
||||
(output / "data" / entry.name).symlink_to(entry.resolve())
|
||||
print("empty replacement table: linked all source files")
|
||||
return
|
||||
rewrite_tvfs(source, output, replacements, prebuilt)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) == 6 and argv[1] == "pack": # pack <RomFS> <输出目录> <替换表.tsv> <块号-档号> | pack <RomFS> <output dir> <replacement-table.tsv> <chunk number-archive number>
|
||||
chunk, archive = (int(x) for x in argv[5].split("-"))
|
||||
write_pack(Path(argv[2]).resolve(), Path(argv[3]).resolve(), read_replacements(argv[4]), (chunk, archive))
|
||||
return
|
||||
prebuilt = None
|
||||
if len(argv) == 6 and argv[4] == "--prebuilt":
|
||||
prebuilt = read_prebuilt(argv[5]); argv = argv[:4]
|
||||
if len(argv) != 4:
|
||||
die("usage: casc_overlay.py <RomFS> <output-dir> <replacements.tsv> [--prebuilt pack_index.tsv] | pack <RomFS> <out> <replacements.tsv> <chunk-archive>")
|
||||
make_overlay(Path(argv[1]).resolve(), Path(argv[2]).resolve(), read_replacements(argv[3]), prebuilt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,22 @@
|
||||
import pickle,glob,collections,sys,struct
|
||||
from capstone import *
|
||||
img=open('main.bin','rb').read()
|
||||
r=[x for f in glob.glob('x18_*.pkl') for x in pickle.load(open(f,'rb'))]
|
||||
md=Cs(CS_ARCH_ARM64,CS_MODE_ARM);md.detail=True
|
||||
c=collections.Counter();ex={}
|
||||
for a,sz,*_ in r:
|
||||
for ins in md.disasm(img[a:a+sz],a):
|
||||
r_,w_=ins.regs_access()
|
||||
names={ins.reg_name(x) for x in list(r_)+list(w_)}
|
||||
if not names&{'x18','w18'}: continue
|
||||
m=ins.mnemonic
|
||||
usesp='sp' in names or 'wsp' in names
|
||||
wb='!' in ins.op_str or (m.startswith(('ldr','str','ldp','stp')) and '], #' in ins.op_str)
|
||||
k=m.split('.')[0]
|
||||
if m in('br','blr','cbz','cbnz','tbz','tbnz','adr','adrp') or (m=='ldr' and '[' not in ins.op_str): k='CTRL/PCREL:'+m
|
||||
elif usesp and wb: k='SP+WB:'+m
|
||||
elif usesp and 'sp' in {ins.reg_name(x) for x in w_}: k='SPWRITE:'+m
|
||||
elif usesp: k='SPBASE'
|
||||
else: k='plain'
|
||||
c[k]+=1; ex.setdefault(k,f'{ins.address:x} {m} {ins.op_str}')
|
||||
for k,v in c.most_common(): print(v,k,ex[k])
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/bash
|
||||
# 计时轮次的并发检测(规矩:有并发的计时轮次一律作废)。
|
||||
# 机理:Apple GPU 按利用率调频。别的进程同时用 GPU 会把频率抬高,被测进程反而变快
|
||||
# (选角页串行化计时:单独三局 5.89–6.02 ms,旁边并发 2.9 个宿主时 3.11 ms),读数不可比。
|
||||
# 用法:conc_watch.sh <被测 pid> <记录文件> [进程名=dmhost]
|
||||
# 在被测进程起来后立即调用(它在前台阻塞到被测进程退出);每秒记一行「时刻 别的同名进程数 负载」。
|
||||
# 结束打一行:CONC OK 采样 N 秒 别的进程 最多 0 → 本轮有效(退出码 0)
|
||||
# CONC RED 采样 N 秒 别的进程 最多 M 均 X → 本轮作废(退出码 1)
|
||||
# 只排除被测 pid 自身;同名的其他进程(含别的工作树起的局)一律算并发。
|
||||
# Concurrency detection for timed rounds (rule: any timed round with concurrency is void).
|
||||
# Mechanism: the Apple GPU scales its frequency by utilization. Other processes using the GPU at the same time raise the frequency, and the process under test actually gets faster
|
||||
# (serialized timing of the character select page: 5.89–6.02 ms for three runs alone, 3.11 ms with 2.9 concurrent hosts alongside), so the readings are not comparable.
|
||||
# Usage: conc_watch.sh <pid under test> <record file> [process name=dmhost]
|
||||
# Call it right after the process under test is up (it blocks in the foreground until the process under test exits); every second it records one line "time, number of other same-name processes, load".
|
||||
# At the end it prints one line: CONC OK 采样 N 秒 别的进程 最多 0 (sampled N seconds, other processes max 0) → this round is valid (exit code 0)
|
||||
# CONC RED 采样 N 秒 别的进程 最多 M 均 X (sampled N seconds, other processes max M avg X) → this round is void (exit code 1)
|
||||
# Only the pid under test itself is excluded; all other processes of the same name (including runs started from other worktrees) count as concurrency.
|
||||
set -u
|
||||
P=${1:?被测 pid}; F=${2:?记录文件}; NAME=${3:-dmhost}
|
||||
kill -0 "$P" 2>/dev/null || { echo "CONC RED 被测进程 $P 不存在(起晚了或已退出)"; exit 1; }
|
||||
: > "$F" || { echo "CONC RED 记录文件 $F 写不了"; exit 1; }
|
||||
while kill -0 "$P" 2>/dev/null; do
|
||||
n=$(ps -A -o pid=,comm= | awk -v me="$P" -v nm="$NAME" '$1 != me { c = $2; sub(".*/", "", c); if (c == nm) k++ } END { print k + 0 }')
|
||||
echo "$(date +%s) $n $(sysctl -n vm.loadavg | awk '{print $2}')" >> "$F"
|
||||
sleep 1
|
||||
done
|
||||
awk -v f="$F" '{ n++; s += $2; if ($2 > m) m = $2 } END {
|
||||
if (!n) { print "CONC RED 没采到样本(被测进程不到 1 秒就退出)"; exit 1 }
|
||||
if (m > 0) { printf "CONC RED 采样 %d 秒 别的进程 最多 %d 均 %.1f → 本轮作废(%s)\n", n, m, s / n, f; exit 1 }
|
||||
printf "CONC OK 采样 %d 秒 别的进程 最多 0 → 本轮有效\n", n }' "$F"
|
||||
Executable
+222
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env python3
|
||||
# 不用 Xcode 出可玩的安装包:把你自己的游戏文件做进「壳」。
|
||||
# 壳(D2RMobile-shell.ipa)是一个不含任何游戏内容、没有签名的安装包;本工具用你的游戏文件在你的电脑上生成它缺的全部内容
|
||||
# (改写后的游戏程序、着色器库、覆盖层、界面素材、几张数据表),放进去,写出一个新的安装包。之后用自签工具整包签名装机。
|
||||
# 游戏文件只在本机读,不上传;做出来的安装包里有游戏内容,请只自己用,不要分发。
|
||||
# 用法:d2rm_pack.py <壳.ipa> <游戏文件目录> <输出.ipa>
|
||||
# 游戏文件目录 = Switch 版 3.3.94012 的 Update 目录,里面有 ExeFS/{main,sdk} 与 RomFS/data/…(怎么从自己的游戏导出)
|
||||
# 工作目录(缓存与中间产物,约 12 GB):环境变量 DM_ROOT,缺省 ~/dm-work;每一步做过就跳过
|
||||
# 需要:Python 3.9+ 与 pillow numpy lz4 capstone unicorn;C 编译器(clang 或 gcc,解贴图的小段 C 用);.NET SDK(编着色器翻译工具);
|
||||
# spirv-cross;苹果的 Metal 着色器编译器(Mac 上随 Xcode)。缺什么本工具开头会逐项报。
|
||||
# 它做的事与「./setup.sh + dm/ios/run.sh build 的生成部分」相同,只是最后不调 Xcode 构建,而是把产物放进壳里。
|
||||
# Build a playable install package without Xcode: put your own game files into the "shell".
|
||||
# The shell (D2RMobile-shell.ipa) is an unsigned install package with no game content at all; this tool uses your game files to generate, on your computer, everything it lacks
|
||||
# (the rewritten game program, shader libraries, overlay, UI assets, a few data tables), puts it in, and writes out a new install package. Afterwards sign the whole package with a sideloading tool and install it.
|
||||
# The game files are only read locally and never uploaded; the resulting install package contains game content, so please use it only yourself and do not distribute it.
|
||||
# Usage: d2rm_pack.py <shell.ipa> <game files directory> <output.ipa>
|
||||
# game files directory = the Update directory of Switch version 3.3.94012, containing ExeFS/{main,sdk} and RomFS/data/... (how to export it from your own game)
|
||||
# working directory (cache and intermediate outputs, about 12 GB): environment variable DM_ROOT, default ~/dm-work; every step already done is skipped
|
||||
# Requires: Python 3.9+ with pillow numpy lz4 capstone unicorn; a C compiler (clang or gcc, for the small piece of C that decodes textures); the .NET SDK (to build the shader translation tool);
|
||||
# spirv-cross; Apple's Metal shader compiler (on a Mac it comes with Xcode). This tool reports whatever is missing item by item at the start.
|
||||
# What it does is the same as "./setup.sh + the generation part of dm/ios/run.sh build", except that at the end it does not invoke an Xcode build but puts the build outputs into the shell.
|
||||
import hashlib, os, re, runpy, shutil, subprocess, sys, time, zipfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); DM = os.path.dirname(HERE); IOS = os.path.join(DM, 'ios'); GT = os.path.join(DM, 'gfx', 'tools')
|
||||
ROOT = os.path.abspath(os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work'))
|
||||
PY = sys.executable
|
||||
WINLF = os.path.join(HERE, 'winlf'); runpy.run_path(os.path.join(WINLF, 'sitecustomize.py')) # Windows 上统一用 \n 换行(见该目录的说明):本进程在这里加载,子脚本经 PYTHONPATH 自动加载 | Use LF line endings on Windows (see the note in that directory): loaded here for this process, and automatically through PYTHONPATH for child scripts
|
||||
MODS = ['main', 'sdk']
|
||||
|
||||
|
||||
def say(s): print('[%s] %s' % (time.strftime('%H:%M:%S'), s), flush=True)
|
||||
|
||||
|
||||
def die(s): sys.exit('[x] ' + s) # 不用 ✗:中文 Windows 的控制台(GBK)打不出来,会在报错的地方再抛一个编码异常 | no ✗: the console of Chinese Windows (GBK) cannot print it, and would raise another encoding exception at the point of the error report
|
||||
|
||||
|
||||
def run(cmd, env=None, cwd=None, log=None, what=None):
|
||||
e = dict(os.environ, DM_ROOT=ROOT, PYTHONUTF8='1', PYTHONPATH=os.pathsep.join(filter(None, [WINLF, os.environ.get('PYTHONPATH')]))); e.update(env or {}) # 子脚本一律按 UTF-8 读写与打印(Windows 缺省是本地编码,读我们的源文件、打 ✓ 都会出错) | child scripts always read, write and print in UTF-8 (the Windows default is the local encoding, and both reading our source files and printing ✓ would fail)
|
||||
r = subprocess.run(cmd, env=e, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
if log: open(log, 'wb').write(r.stdout)
|
||||
if r.returncode: die('%s 没成功(退出码 %d):%s%s' % (what or cmd[0], r.returncode, r.stdout.decode('utf-8', 'replace').strip().splitlines()[-1:] or '', ';完整输出 ' + log if log else ''))
|
||||
return r.stdout.decode('utf-8', 'replace')
|
||||
|
||||
|
||||
def step(name, done, fn):
|
||||
if done(): say('%s:已有,跳过' % name); return
|
||||
t0 = time.time(); say(name); fn()
|
||||
if not done(): die('%s 做完了但没看到产物' % name)
|
||||
say('%s 完成(%d 秒)' % (name, time.time() - t0))
|
||||
|
||||
|
||||
def read_shell(ipa):
|
||||
try: z = zipfile.ZipFile(ipa)
|
||||
except zipfile.BadZipFile: die('这个文件不是安装包(解不开):%s' % ipa)
|
||||
apps = sorted({n.split('/')[1] for n in z.namelist() if n.startswith('Payload/') and n.count('/') >= 2 and n.split('/')[1].endswith('.app')})
|
||||
if len(apps) != 1: die('壳里的 App 不是恰好一个:%s' % apps)
|
||||
base = 'Payload/%s/' % apps[0]
|
||||
try:
|
||||
manifest = [l.strip() for l in z.read(base + 'dm/shell_manifest.txt').decode().splitlines() if l.strip()]
|
||||
info = dict(l.strip().split('=', 1) for l in z.read(base + 'dm/shell_info.txt').decode().splitlines() if '=' in l)
|
||||
except KeyError: die('这不是壳:里面没有 dm/shell_manifest.txt / dm/shell_info.txt(%s)' % ipa)
|
||||
exe = next((n for n in z.namelist() if n == base + apps[0][:-4]), None)
|
||||
return z, base, manifest, info, exe
|
||||
|
||||
|
||||
def check_env(game):
|
||||
bad = []
|
||||
for m in ('PIL', 'numpy', 'lz4', 'capstone', 'unicorn'):
|
||||
try: __import__(m)
|
||||
except Exception: bad.append('Python 包 %s:%s -m pip install pillow numpy lz4 capstone unicorn' % (m, PY))
|
||||
if not (shutil.which('clang') or shutil.which('gcc') or shutil.which('cc')): bad.append('C 编译器(clang 或 gcc)')
|
||||
dotnet = shutil.which('dotnet') or (os.path.expanduser('~/.dotnet/dotnet') if os.path.exists(os.path.expanduser('~/.dotnet/dotnet')) else None)
|
||||
if not dotnet: bad.append('.NET SDK(dotnet):https://dotnet.microsoft.com/download')
|
||||
if not shutil.which('spirv-cross'): bad.append('spirv-cross:https://github.com/KhronosGroup/SPIRV-Cross')
|
||||
for f in ('ExeFS/main', 'ExeFS/sdk', 'RomFS/data/build_manifest.psv'):
|
||||
if not os.path.isfile(os.path.join(game, f)): bad.append('游戏文件 %s(在 %s 下没找到)' % (f, game))
|
||||
if bad: die('还缺 %d 项:\n - %s' % (len(bad), '\n - '.join(bad)))
|
||||
return dotnet
|
||||
|
||||
|
||||
def have_metal(): # 这台机器上有没有苹果的 Metal 着色器编译器(只有装了 Xcode 的 Mac 有) | whether this machine has Apple's Metal shader compiler (only a Mac with Xcode installed has it)
|
||||
if sys.platform != 'darwin': return False
|
||||
try: return subprocess.run(['xcrun', '-sdk', 'iphoneos', 'metal', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
|
||||
except FileNotFoundError: return False
|
||||
|
||||
|
||||
def src_digest(d):
|
||||
"""翻译出的全部着色器源码的摘要(换行归一)。出壳时算一次随壳走,使用者机器上翻译完再算一次比对:
|
||||
着色器翻译工具 spirv-cross 换个版本,翻出来的源码就可能不同(实测最新源码版与 1.4.357.0 差 231 个着色器),对不上就停下来说清楚
|
||||
'''Digest of all translated shader sources (line endings normalized). Computed once when the shell is built and shipped with it, then computed again
|
||||
on the user's machine after translation and compared: a different spirv-cross version may translate shaders differently (the latest source
|
||||
and 1.4.357.0 differ in 231 shaders), so on a mismatch we stop and say why'''"""
|
||||
h = hashlib.sha256()
|
||||
for f in sorted(x for x in os.listdir(d) if x.endswith('_b.metal')):
|
||||
h.update(f.encode()); h.update(hashlib.sha256(open(os.path.join(d, f), 'rb').read().replace(b'\r\n', b'\n')).digest())
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) == 3 and sys.argv[1] == '--src-digest': print(src_digest(sys.argv[2])); return # 出壳脚本用 | used by the shell build script
|
||||
if len(sys.argv) != 4: sys.exit(__doc__ or '用法:d2rm_pack.py <壳.ipa> <游戏文件目录> <输出.ipa>')
|
||||
shell, game, out_ipa = (os.path.abspath(x) for x in sys.argv[1:])
|
||||
for st in (sys.stdout, sys.stderr):
|
||||
try: st.reconfigure(errors='replace')
|
||||
except Exception: pass
|
||||
if not os.path.isfile(shell): die('没有这个壳文件:%s' % shell)
|
||||
if not os.path.isdir(game): die('没有这个游戏文件目录:%s' % game)
|
||||
z, base, manifest, info, exe = read_shell(shell)
|
||||
P = open(os.path.join(DM, 'PRODUCT')).readline().strip()
|
||||
if info.get('PRODUCT') != P: die('壳与这份源码不是同一版:壳要的产物代号是 %s,这份源码是 %s。请用与壳同一个发布版本的源码' % (info.get('PRODUCT'), P))
|
||||
chain = info.get('CHAIN') or die('壳的版本信息里没有着色器链版本')
|
||||
dotnet = check_env(game)
|
||||
# 着色器最后一步:有苹果的编译器就在电脑上编成库;没有(Windows / Linux / 没装 Xcode 的 Mac)就把源码放进安装包,手机上用到时现编。
|
||||
# D2RM_NO_METAL=1 强制走后一种(有编译器的机器上试这条路用)
|
||||
# Last step for shaders: if Apple's compiler is present, compile them into libraries on the computer; if not (Windows / Linux / a Mac without Xcode), put the source into the install package and compile on the device when first used.
|
||||
# D2RM_NO_METAL=1 forces the latter (for trying this path on a machine that has the compiler)
|
||||
nometal = os.environ.get('D2RM_NO_METAL') == '1' or not have_metal()
|
||||
gt = (lambda script, *a: [PY, os.path.join(GT, 'nometal_run.py'), os.path.join(GT, script), *a]) if nometal else (lambda script, *a: [PY, os.path.join(GT, script), *a])
|
||||
if nometal: say('这台机器不调苹果的着色器编译器:着色器以源码放进安装包,首次启动时在手机上编(第一次进游戏会多等一会儿)')
|
||||
romfs = os.path.join(game, 'RomFS'); stage = os.path.join(ROOT, 'build', 'pack', 'stage'); shutil.rmtree(stage, ignore_errors=True); os.makedirs(os.path.join(stage, 'dm'))
|
||||
say('壳 %s:产物代号 %s,着色器链 %s,要补 %d 项' % (os.path.basename(shell), P, chain, len(manifest)))
|
||||
|
||||
# 一、改写游戏程序(与 tools/product.sh build 的 touch 那一种相同)
|
||||
# 1. Rewrite the game program (same as the touch variant of tools/product.sh build)
|
||||
out = os.path.join(ROOT, 'build', 'cache', 'dm', 'out', P + '-touch'); os.makedirs(out, exist_ok=True)
|
||||
def patch():
|
||||
for m in MODS: run([PY, os.path.join(HERE, 'patch_nso.py'), os.path.join(game, 'ExeFS', m), out, m], env={'DM_RULESET': 'touch-run-v4'}, log=os.path.join(out, m + '.patch.log'), what='改写 ' + m)
|
||||
step('改写游戏程序', lambda: all(os.path.isfile(os.path.join(out, m + '.patched.bin')) and os.path.isfile(os.path.join(out, m + '.gates.tsv')) for m in MODS), patch)
|
||||
|
||||
# 二、界面素材与几张数据表(与 ios/run.sh build 开头相同)
|
||||
# 2. UI assets and a few data tables (same as the beginning of ios/run.sh build)
|
||||
say('从游戏文件生成界面素材(输入没变会自己跳过)')
|
||||
run([PY, os.path.join(IOS, 'tools', 'gen_assets.py'), romfs], cwd=IOS, env={'DM_ROMFS_SRC': romfs}, log=os.path.join(stage, 'gen_assets.log'), what='生成界面素材')
|
||||
for name, gen in (('dm_vault_tab.h', 'gen_vault_table.py'), ('dm_hud_exp.h', 'gen_hud_exp.py')):
|
||||
txt = run([PY, os.path.join(IOS, 'tools', gen), romfs], what='生成 ' + name)
|
||||
with open(os.path.join(DM, 'host', name), 'w', encoding='utf-8') as f: f.write(txt)
|
||||
sys.path.insert(0, os.path.join(IOS, 'tools')); import shell_stubs
|
||||
say('数据表:经验 %d、部位 %d、仓库条目 %d、套装 %d、技能索引 %d' % shell_stubs.data(DM, os.path.join(stage, 'dm', 'derived.tsv')))
|
||||
hud = os.path.join(IOS, 'Gen', 'assets', 'NativeHUD')
|
||||
for d, src in (('hud_v4_ui', os.path.join(hud, 'v4', 'hud_v4_ui')), ('mapgoal', os.path.join(hud, 'mapgoal')), ('mercslots', os.path.join(hud, 'mercslots'))):
|
||||
if d + '/' in manifest: shutil.copytree(src, os.path.join(stage, d))
|
||||
ta = os.path.join(IOS, 'Sources', 'TouchArt')
|
||||
for f in sorted(os.listdir(ta)):
|
||||
if f in manifest: shutil.copyfile(os.path.join(ta, f), os.path.join(stage, f))
|
||||
|
||||
# 三、覆盖层
|
||||
# 3. Overlay
|
||||
say('生成覆盖层')
|
||||
run([PY, os.path.join(IOS, 'tools', 'gen_romfs_overlay.py'), romfs, os.path.join(stage, 'romfs_overlay')], cwd=IOS, env={'DM_ROMFS_SRC': romfs}, log=os.path.join(stage, 'gen_overlay.log'), what='生成覆盖层')
|
||||
for d in ('romfs_overlay_astc', 'romfs_overlay_astc_variants'): shutil.rmtree(os.path.join(stage, d), ignore_errors=True)
|
||||
|
||||
# 四、着色器:取包 → 翻译工具 → 翻译并编成 Metal 库(与 setup.sh 相同)
|
||||
# 4. Shaders: extract the shader packs from the game resources → translation tool → translate and compile into Metal libraries (same as setup.sh)
|
||||
packs = os.path.join(ROOT, 'build', 'cache', 'dm', 'dmsh')
|
||||
def get_packs():
|
||||
os.makedirs(packs, exist_ok=True); e = {'DMX_ROOT': os.path.join(romfs, 'data')}
|
||||
for line in run([PY, os.path.join(HERE, 'dmx.py'), 'list', 'data:data/hd/shaders/*.bin'], env=e, what='列着色器包').splitlines():
|
||||
p = line.split('\t')[0]
|
||||
if p: run([PY, os.path.join(HERE, 'dmx.py'), 'get', p, os.path.join(packs, os.path.basename(p))], env=e, what='取着色器包 ' + p)
|
||||
step('取着色器包(162 个)', lambda: os.path.isdir(packs) and len(os.listdir(packs)) == 162, get_packs)
|
||||
xl = os.path.join(ROOT, 'build', 'gfx', 'dmsh_xlate')
|
||||
step('编译着色器翻译工具', lambda: os.path.isfile(os.path.join(xl, 'dmsh_xlate')) or os.path.isfile(os.path.join(xl, 'dmsh_xlate.exe')),
|
||||
lambda: run([dotnet, 'publish', os.path.join(GT, 'dmsh_xlate'), '-c', 'Release', '-o', xl, '-v', 'quiet'], what='编译着色器翻译工具'))
|
||||
chk = lambda: subprocess.run(gt('dmsh_chain.py', '--check-tools'), env=dict(os.environ, DM_ROOT=ROOT, PYTHONUTF8='1'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
|
||||
if not chk(): # 本机工具与仓库登记的不同是正常的:按本机工具重新登记(会改写仓库里三个随工具变的文件,不要提交它们) | it is normal for the local tools to differ from what the repository registers: re-register by the local tools (this rewrites the three tool-dependent files in the repository; do not commit them)
|
||||
say('本机工具与仓库登记的不同:按本机工具重新登记翻译链')
|
||||
run(gt('dmsh_chain.py', '--update-lock'), what='登记翻译链'); run(gt('dmsh_chain.py', '--header'), what='写翻译链版本')
|
||||
local = run(gt('dmsh_chain.py'), what='取翻译链版本').strip().splitlines()[-1]
|
||||
ios_out = os.path.join(ROOT, 'build', 'ios', 'dmsh_b'); mac_cache = os.path.join(ROOT, 'build', 'cache', 'metal_shader_cache')
|
||||
step('翻译全部着色器(首次约 8 分钟)', lambda: os.path.isfile(os.path.join(mac_cache, 'b-' + local, '_b_build.json')) and os.path.isdir(os.path.join(ios_out, 'b-' + local)) and any(f.endswith('_b.metallib') for f in os.listdir(os.path.join(ios_out, 'b-' + local))), # 完成标记写在 Mac 侧缓存目录里 | the completion marker is written in the Mac-side cache directory
|
||||
lambda: run(gt('dmsh_build.py', packs, mac_cache), env={'IOSOUT': ios_out, 'J': os.environ.get('J', '6'), 'MAIN': os.path.join(game, 'ExeFS', 'main')}, log=os.path.join(stage, 'shaders.log'), what='翻译着色器'))
|
||||
lib = os.path.join(stage, 'msl', 'b-' + chain); os.makedirs(os.path.dirname(lib)); shutil.copytree(os.path.join(ios_out, 'b-' + local), lib) # 目录名用壳认的那个版本 | the directory name uses the version the shell recognizes
|
||||
if local != chain: # 每个着色器的说明里也记着链版本,壳逐个核对(对不上拒绝加载,真机实测撞到):一并改成壳认的那个 | each shader's description also records the chain version, and the shell checks them one by one (a mismatch is refused, hit in real-device testing): change them all to the one the shell recognizes
|
||||
old, new, n = ('"chain": "%s"' % local).encode(), ('"chain": "%s"' % chain).encode(), 0
|
||||
for f in os.listdir(lib):
|
||||
if f.endswith('.json'):
|
||||
b = open(os.path.join(lib, f), 'rb').read()
|
||||
if old in b: open(os.path.join(lib, f), 'wb').write(b.replace(old, new)); n += 1
|
||||
if not n: die('着色器说明里没找到链版本 %s(格式变了?)' % local)
|
||||
got = src_digest(os.path.join(mac_cache, 'b-' + local))
|
||||
if info.get('SHADER_SRC') and got != info['SHADER_SRC']:
|
||||
die('这台机器翻译出的着色器与壳要的不一样(摘要 %s,壳要 %s)。最常见的原因是 spirv-cross 版本不同:请换成 %s(见 docs 里的说明),'
|
||||
'然后删掉 %s 重跑。不一样的着色器装到手机上可能画错,所以不往下做' % (got, info['SHADER_SRC'], info.get('SPIRV_CROSS', '说明里写的那个版本'), os.path.join(mac_cache, 'b-' + local)))
|
||||
c1 = os.path.join(stage, 'dm', 'c1_full.tsv')
|
||||
run([PY, os.path.join(GT, 'c1_guard.py'), os.path.join(mac_cache, 'b-' + local), c1], what='出着色器下标清单')
|
||||
if local != chain:
|
||||
t = open(c1, encoding='utf-8').read(); open(c1, 'w', encoding='utf-8').write(t.replace('b-' + local, 'b-' + chain, 1))
|
||||
say('着色器库按本机工具出(链版本 %s),放进壳认的目录名 b-%s' % (local, chain))
|
||||
|
||||
# 五、游戏程序写成动态库 + 装载表
|
||||
# 5. Write the game program as a dynamic library + load table
|
||||
import guest_dylib
|
||||
fw, n = guest_dylib.write(out, os.path.join(stage, 'Frameworks'), MODS); say('游戏程序动态库:%d 字节' % n)
|
||||
for f in [m + s for m in MODS for s in ('.fixups.tsv', '.gates.tsv')] + ['bootlist.tsv', 'main.cuts.tsv']:
|
||||
if os.path.isfile(os.path.join(out, f)): shutil.copyfile(os.path.join(out, f), os.path.join(stage, 'dm', f))
|
||||
|
||||
# 自检:壳按链版本找着色器——目录名、下标清单的首行、每个着色器说明里的版本,三处都必须是壳认的那个(任何一处不是,壳都会拒绝加载)
|
||||
# Self-check: the shell finds shaders by chain version -- the directory name, the first line of the index list, and the version in each shader's description must all three be the one the shell recognizes (if any one is not, the shell refuses to load)
|
||||
js = [f for f in os.listdir(lib) if f.endswith('.json')]; want = ('"chain": "%s"' % chain).encode()
|
||||
wrong = [f for f in js if want not in open(os.path.join(lib, f), 'rb').read()]
|
||||
if not js or wrong: die('着色器说明里的链版本与壳要的 %s 不一致:%d / %d 个不对%s' % (chain, len(wrong), len(js), ',如 ' + wrong[0] if wrong else ''))
|
||||
if ('b-' + chain) not in open(c1, encoding='utf-8').readline(): die('着色器下标清单首行的链版本不是壳要的 %s' % chain)
|
||||
say('自检:%d 个着色器说明、下标清单、目录名的链版本都是壳要的 %s;翻译出的源码摘要 %s%s' % (len(js), chain, got, '与壳一致' if info.get('SHADER_SRC') else '(这个壳没带摘要,没比)'))
|
||||
|
||||
# 六、照壳的清单核对一项不缺,再放进去
|
||||
# 6. Check against the shell's manifest that nothing is missing, then put it in
|
||||
miss = [m for m in manifest if not (os.path.isdir(os.path.join(stage, m)) if m.endswith('/') else os.path.isfile(os.path.join(stage, m)))]
|
||||
if miss: die('有 %d 项没做出来:%s' % (len(miss), '、'.join(miss)))
|
||||
tmp = out_ipa + '.part'; added = 0
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as o:
|
||||
for i in z.infolist(): o.writestr(i, z.read(i.filename))
|
||||
for m in manifest:
|
||||
src = os.path.join(stage, m)
|
||||
files = [os.path.join(d, f) for d, _, fs in sorted(os.walk(src)) for f in sorted(fs)] if m.endswith('/') else [src]
|
||||
for f in files:
|
||||
zi = zipfile.ZipInfo(base + os.path.relpath(f, stage).replace(os.sep, '/'), date_time=(2026, 1, 1, 0, 0, 0)); zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = (0o755 if os.path.basename(f) == 'Guest' else 0o644) << 16; o.writestr(zi, open(f, 'rb').read()); added += 1
|
||||
os.replace(tmp, out_ipa)
|
||||
say('好了:%s(%.0f MB,放进去 %d 个文件)。下一步:用自签工具给它签名装机(见 docs 里的说明);这个安装包里有游戏内容,请只自己用' % (out_ipa, os.path.getsize(out_ipa) / 1048576, added))
|
||||
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Switch D2R RomFS 存储最小提取器(只读)。
|
||||
|
||||
存储布局(实测):
|
||||
build_manifest.psv 每行 = FileId|KeyLayout|Chunk|Archive|CKey|CSize|EKey|ESize|Encoding|Path|Flags
|
||||
数据文件 = <Chunk:02d>-<Archive:08d>.data
|
||||
偏移 = EKey 末 5 字节(大端 40 位;key-layout-0 = 8 8 40 1 → EKey[9]=Chunk, EKey[10]=Archive, EKey[11:16]=偏移)
|
||||
编码 n → 原样 CSize 字节
|
||||
z → 一整段 zlib(无 BLTE 头)
|
||||
b:..*=.. → 标准 BLTE 容器('BLTE' + 头长 + 0x0F + 块数 + {esize,csize,md5}×N,每块首字节 N/Z)
|
||||
校验 md5(解出内容) == CKey
|
||||
用法:
|
||||
dmx.py get <Path> <out> 取单个文件(Path 用清单 Path 列,或去掉 'data:' 前缀,大小写不敏感)
|
||||
dmx.py list [glob] 列 Path\tCSize
|
||||
Minimal extractor for Switch D2R RomFS storage (read-only).
|
||||
Storage layout (measured):
|
||||
build_manifest.psv each line = FileId|KeyLayout|Chunk|Archive|CKey|CSize|EKey|ESize|Encoding|Path|Flags
|
||||
data file = <Chunk:02d>-<Archive:08d>.data
|
||||
offset = last 5 bytes of EKey (big-endian 40 bits; key-layout-0 = 8 8 40 1 → EKey[9]=Chunk, EKey[10]=Archive, EKey[11:16]=offset)
|
||||
encoding n → CSize bytes as is
|
||||
z → one whole zlib segment (no BLTE header)
|
||||
b:..*=.. → standard BLTE container ('BLTE' + header length + 0x0F + block count + {esize,csize,md5}×N, first byte of each block N/Z)
|
||||
check md5(decoded content) == CKey
|
||||
Usage:
|
||||
dmx.py get <Path> <out> fetch a single file (Path uses the manifest's Path column, or with the 'data:' prefix removed; case-insensitive)
|
||||
dmx.py list [glob] list Path\\tCSize
|
||||
"""
|
||||
import fnmatch, hashlib, os, struct, sys, zlib
|
||||
|
||||
ROOT = os.environ.get("DMX_ROOT", "~/Diablo II Resurrected - 提取内容/Update/RomFS/data")
|
||||
_IDX = None
|
||||
_FH = {}
|
||||
|
||||
|
||||
def index():
|
||||
global _IDX
|
||||
if _IDX is None:
|
||||
_IDX = {}
|
||||
with open(os.path.join(ROOT, "build_manifest.psv"), encoding="utf-8") as f:
|
||||
next(f)
|
||||
for line in f:
|
||||
if line.startswith("#"):
|
||||
continue
|
||||
c = line.rstrip("\n").split("|")
|
||||
if len(c) < 11:
|
||||
continue
|
||||
_IDX[c[9].lower()] = c
|
||||
return _IDX
|
||||
|
||||
|
||||
def lookup(path):
|
||||
idx = index()
|
||||
k = path.lower().replace("\\", "/")
|
||||
for cand in (k, "data:" + k, "data:data/" + k):
|
||||
if cand in idx:
|
||||
return idx[cand]
|
||||
raise KeyError(path)
|
||||
|
||||
|
||||
def _fh(chunk, arch):
|
||||
key = (chunk, arch)
|
||||
if key not in _FH:
|
||||
_FH[key] = open(os.path.join(ROOT, f"{chunk:02d}-{arch:08d}.data"), "rb")
|
||||
return _FH[key]
|
||||
|
||||
|
||||
def _block(b):
|
||||
m = b[:1]
|
||||
if m == b"N":
|
||||
return b[1:]
|
||||
if m == b"Z":
|
||||
return zlib.decompress(b[1:])
|
||||
raise ValueError(f"未知 BLTE 块模式 {m!r}")
|
||||
|
||||
|
||||
def read_row(c):
|
||||
chunk, arch, csize, esize, enc = int(c[2]), int(c[3]), int(c[5]), int(c[7]), c[8]
|
||||
ekey = bytes.fromhex(c[6])
|
||||
off = int.from_bytes(ekey[11:16], "big")
|
||||
assert ekey[9] == chunk and ekey[10] == arch, (c[9], ekey.hex())
|
||||
f = _fh(chunk, arch)
|
||||
f.seek(off)
|
||||
raw = f.read(esize)
|
||||
if raw[:4] == b"BLTE":
|
||||
hlen = struct.unpack(">I", raw[4:8])[0]
|
||||
n = int.from_bytes(raw[9:12], "big")
|
||||
pos, out = hlen, []
|
||||
for i in range(n):
|
||||
es, cs = struct.unpack(">II", raw[12 + 24 * i:20 + 24 * i])
|
||||
out.append(_block(raw[pos:pos + es]))
|
||||
pos += es
|
||||
data = b"".join(out)
|
||||
elif enc == "n":
|
||||
data = raw
|
||||
elif enc == "z":
|
||||
data = zlib.decompress(raw)
|
||||
else:
|
||||
raise ValueError(f"未知编码 {enc}")
|
||||
if len(data) != csize or hashlib.md5(data).hexdigest() != c[4]:
|
||||
raise ValueError(f"校验失败 {c[9]} len={len(data)} csize={csize}")
|
||||
return data
|
||||
|
||||
|
||||
def get(path):
|
||||
return read_row(lookup(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1] == "get":
|
||||
d = get(sys.argv[2])
|
||||
open(sys.argv[3], "wb").write(d)
|
||||
print(len(d), "bytes, md5 ok")
|
||||
elif sys.argv[1] == "list":
|
||||
pat = sys.argv[2].lower() if len(sys.argv) > 2 else "*"
|
||||
for k, c in index().items():
|
||||
if fnmatch.fnmatch(k, pat):
|
||||
print(f"{c[9]}\t{c[5]}")
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
# 从你自己的游戏包里取出本项目要的两部分(更新后的程序文件与资源),放进工作区。
|
||||
# 用法:extract_game.sh <游戏包 .xci 或 .nsp> <prod.keys>
|
||||
# 游戏包:你自己导出的《暗黑破坏神 II:狱火重生》Switch 版,里面要同时有本体与 3.3.94012 的更新(.xci 常见的「1G+1U」)。
|
||||
# prod.keys:从你自己的主机导出的密钥文件。两样都只在本机读,不拷贝、不上传。
|
||||
# 产物:$DM_ROOT/data/switch/3.3.94012/Update/{ExeFS,RomFS}(DM_ROOT 缺省 ~/dm-work)。已有这个目录时不覆盖。
|
||||
# 需要:hactool(开源的 Switch 文件解包工具,https://github.com/SciresM/hactool ,按它的说明 make 出来)。
|
||||
# 放进 PATH,或用 HACTOOL=<路径> 指给本脚本。磁盘要留出约 20 GB(中间文件 9 GB,做完自动删)。
|
||||
# Extract the two parts this project needs (the updated program files and the assets) from your own copy of the game and put them into the workspace.
|
||||
# Usage: extract_game.sh <game dump .xci or .nsp> <prod.keys>
|
||||
# Game dump: your own dump of the Switch version of Diablo II: Resurrected; it must contain both the base game and the 3.3.94012 update (the common "1G+1U" form for .xci).
|
||||
# prod.keys: the key file dumped from your own console. Both are only read on this machine; nothing is copied or uploaded.
|
||||
# Output: $DM_ROOT/data/switch/3.3.94012/Update/{ExeFS,RomFS} (DM_ROOT defaults to ~/dm-work). An existing directory is not overwritten.
|
||||
# Requires: hactool (an open-source tool for unpacking Switch files, https://github.com/SciresM/hactool ; build it with make following its instructions).
|
||||
# Put it on PATH, or point this script at it with HACTOOL=<path>. Keep about 20 GB of disk free (9 GB of intermediate files, deleted automatically when done).
|
||||
set -u
|
||||
[ $# -eq 2 ] || { sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
|
||||
PKG=$1; KEYS=$2; DM_ROOT=${DM_ROOT:-$HOME/dm-work}; OUT=$DM_ROOT/data/switch/3.3.94012/Update
|
||||
die() { echo "✗ $*" >&2; exit 1; }
|
||||
HT=${HACTOOL:-$(command -v hactool || true)}; [ -n "$HT" ] && [ -x "$HT" ] || die "没找到 hactool:装好后放进 PATH,或设 HACTOOL=<路径>(见本文件开头)"
|
||||
[ -f "$PKG" ] || die "没有这个游戏包:$PKG"; [ -f "$KEYS" ] || die "没有这个密钥文件:$KEYS"
|
||||
[ ! -e "$OUT" ] || die "已有 $OUT,不覆盖。要重做先自己把它移走"
|
||||
ht() { "$HT" -k "$KEYS" --disablekeywarns --suppresskeys "$@"; }
|
||||
T=$DM_ROOT/build/cache/dm/extract.$$; mkdir -p "$T/nca" || die "建不了中间目录 $T"; trap 'rm -rf "$T"' EXIT
|
||||
say() { echo "[$(date +%T)] $*"; }
|
||||
|
||||
say "拆游戏包(约 9 GB)"
|
||||
case "$PKG" in
|
||||
*.xci|*.XCI) ht -t xci --securedir="$T/nca" "$PKG" > "$T/unpack.log" 2>&1 || die "游戏包拆不开(密钥不对或文件损坏),日志 $T/unpack.log:$(tail -1 "$T/unpack.log")";;
|
||||
*.nsp|*.NSP) ht -t pfs0 --outdir="$T/nca" "$PKG" > "$T/unpack.log" 2>&1 || die "游戏包拆不开(密钥不对或文件损坏):$(tail -1 "$T/unpack.log")";;
|
||||
*) die "只认 .xci 或 .nsp";;
|
||||
esac
|
||||
|
||||
# 找出本体与更新的程序内容:按每个内容文件自己报的类型与程序号认,不靠文件名。
|
||||
# 更新的程序内容报的也是本体的程序号;区别是它的资源段是「补丁」格式(BKTR),要叠在本体上才读得出
|
||||
# Find the program content of the base game and of the update: identify them by the type and program id each content file reports, not by file name.
|
||||
# The update's program content also reports the base game's program id; the difference is that its asset section is in "patch" format (BKTR) and can only be read when layered on top of the base game
|
||||
BASE=; UPD=
|
||||
for f in "$T"/nca/*.nca; do
|
||||
case "$f" in *.cnmt.nca) continue;; esac
|
||||
info=$(ht -t nca "$f" 2>&1)
|
||||
echo "$info" | grep -q "Content Type: *Program" || continue
|
||||
echo "$info" | grep -q "^Title ID: *0100726014352000" || continue
|
||||
if echo "$info" | grep -q "BKTR"; then UPD=$f; else BASE=$f; fi
|
||||
done
|
||||
[ -n "$BASE" ] || die "游戏包里没找到这个游戏的本体"
|
||||
[ -n "$UPD" ] || die "游戏包里没有更新:本项目要 3.3.94012 的更新,只有本体不行"
|
||||
|
||||
say "取程序文件与资源(约 9 GB)"
|
||||
mkdir -p "$OUT.part" || die "建不了 $OUT.part"
|
||||
ht -t nca --basenca="$BASE" --exefsdir="$OUT.part/ExeFS" --romfsdir="$OUT.part/RomFS" "$UPD" > "$T/extract.log" 2>&1 || { rm -rf "$OUT.part"; die "更新内容取不出来:$(tail -1 "$T/extract.log")"; }
|
||||
|
||||
# 版本核对:三个程序文件的校验值必须是 3.3.94012 的
|
||||
# Version check: the checksums of the three program files must be those of 3.3.94012
|
||||
ok=1
|
||||
while read -r want name; do
|
||||
got=$(shasum -a 256 "$OUT.part/ExeFS/$name" 2> /dev/null | cut -c1-64)
|
||||
if [ "$got" = "$want" ]; then echo " ✓ $name"; else echo " ✗ $name 不是 3.3.94012 的(${got:-文件不在})"; ok=0; fi
|
||||
done <<SUMS
|
||||
55fd909bb7230b002357e5b0d8499c11f06888f345c49e69eb4734df44a27d0e main
|
||||
1c9f198a91c0bcfee5cf8f5b53fb941895e91334dfb766ce79fc68576797f017 sdk
|
||||
67a38fcf89cd13e040a021eb3d157072f38ebf6680a907874c35c7b231b5d4e2 subsdk0
|
||||
SUMS
|
||||
[ -f "$OUT.part/RomFS/data/build_manifest.psv" ] || { echo " ✗ 资源里没有 data/build_manifest.psv"; ok=0; }
|
||||
[ "$ok" = 1 ] || { rm -rf "$OUT.part"; die "版本不对:游戏包里的更新不是 3.3.94012"; }
|
||||
mv "$OUT.part" "$OUT" || die "改名到 $OUT 没成"
|
||||
say "好了:$OUT。接着在仓库根目录运行 ./setup.sh"
|
||||
@@ -0,0 +1,26 @@
|
||||
import struct,collections
|
||||
img=open('main.bin','rb').read()
|
||||
m=struct.unpack_from('<I',img,4)[0]
|
||||
assert img[m:m+4]==b'MOD0',img[m:m+4]
|
||||
dyn,bs,be,ehs,ehe,mo=[m+x for x in struct.unpack_from('<6i',img,m+4)]
|
||||
print('eh_frame_hdr',hex(ehs),hex(ehe))
|
||||
ver,ptrenc,cntenc,tblenc=img[ehs:ehs+4]
|
||||
# eh_frame_ptr (enc), fde_count (enc), table
|
||||
def rd(o,enc,base):
|
||||
fmt=enc&0xf; app=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+=base
|
||||
return v,sz
|
||||
o=ehs+4
|
||||
_,s=rd(o,ptrenc,ehs);o+=s
|
||||
n,s=rd(o,cntenc,ehs);o+=s
|
||||
starts=[]
|
||||
for i in range(n):
|
||||
a,s=rd(o,tblenc,ehs);o+=s
|
||||
b,s=rd(o,tblenc,ehs);o+=s
|
||||
starts.append(a)
|
||||
starts=sorted(set(starts))
|
||||
print('FDE functions',len(starts),'text end',hex(0x1b786a0))
|
||||
import pickle;pickle.dump(starts,open('starts.pkl','wb'))
|
||||
# x18 / x16/x17 usage per function via capstone regs_access is slow; quick: decode register fields roughly with capstone detail on all text
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
# 帧稳 Mac 对照(mini 上跑):产品节奏(不开 DM_DETCLOCK,display 模式 60 Hz)回放营地 / 野外,逐帧读 nvn.tsv,
|
||||
# 统计局内 CPU 帧(出帧工作 − 取图等待 − 出图队列等待)超 16.7 ms 的次数,并按 上传 / 建管线建库 / 其它 归因。
|
||||
# 用法:frameprobe.sh <camp1|wild1> <局号> 环境:MINI_ROOT、DM_OUT(mini_sync.sh 的目录)
|
||||
# Frame-stability Mac comparison (run on the second Mac): replays camp / wilderness at product pacing (DM_DETCLOCK off, display mode 60 Hz), reads nvn.tsv frame by frame,
|
||||
# counts how many in-run CPU frames (present work − image acquire wait − present queue wait) exceed 16.7 ms, and attributes them to upload / pipeline and library creation / other.
|
||||
# Usage: frameprobe.sh <camp1|wild1> <run number> Environment: MINI_ROOT, DM_OUT (the directory of mini_sync.sh)
|
||||
set -u
|
||||
scene=$1; k=$2; mini=${MINI_ROOT:?}; out=${DM_OUT:-$mini/out/$(bash "$(dirname "$0")/product.sh" name keypage)}; bin=$mini/src/dm/host/dmhost
|
||||
tr=$mini/data/switch/truth_runs/$scene; run=$mini/frameprobe/${scene}_$k; rm -rf "$run"; mkdir -p "$run"
|
||||
cp -R "$mini/data/switch/save_ref_warlock/0000000000000001/0" "$run/save0"
|
||||
if [ "$scene" = camp1 ]; then c2s=$tr/c2s_to_E.jsonl; n=122; keys='A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame'
|
||||
else c2s=$tr/c2s_to_arrive.jsonl; n=215; keys='A@OpenPanel:MainMenuButtonRibbon>FrontEndNavigation:ToGame,A@DM:Tick:133#>OpenPanel:WaypointsPanelExpansion,DOWN@DM:Tick:142#,A@DM:Tick:150#>ClosePanel:WaypointsPanelExpansion'; fi
|
||||
(cd "$(dirname "$bin")" && timeout 110 env DM_SAVE="$run/save0" DM_GAME_SEED=0x12345678 DM_FIXED_TIME=1790000000 DM_TICKS_N=$((n+1)) \
|
||||
DM_C2S_REPLAY="$c2s" DM_TICKS="$run/ticks.jsonl" DM_KEYS="$keys" DM_PRESENT_HZ=60 DM_PRESENT_INTERVAL=display DM_UIMSG=1 \
|
||||
DM_NVN_TSV="$run/nvn.tsv" DM_NVN_FRAMES=0 ./dmhost "$out" main sdk > "$run/host.log" 2>&1); echo "rc=$?"
|
||||
python3 - "$run" "$scene" "$k" <<'PY'
|
||||
import re, sys, collections
|
||||
run, scene, k = sys.argv[1:]
|
||||
iv, o, first = [], None, None
|
||||
for l in open(run + "/host.log", errors="replace"):
|
||||
m = re.match(r"\[dm\] UIMSG \[([\d.]+)s\] PanelManager (OpenPanel|UnloadPanel) LoadScreenPanel", l)
|
||||
if not m: continue
|
||||
t = float(m.group(1))
|
||||
if m.group(2) == "OpenPanel": o = t; first = t if first is None else first
|
||||
elif o is not None: iv.append((o, t)); o = None
|
||||
if o is not None: iv.append((o, 1e9))
|
||||
F = collections.defaultdict(dict)
|
||||
for l in open(run + "/nvn.tsv"):
|
||||
p = l.rstrip("\n").split("\t")
|
||||
if len(p) == 3 and p[0].isdigit():
|
||||
try: F[int(p[0])][p[1]] = float(p[2])
|
||||
except ValueError: pass
|
||||
game = [f for f, d in sorted(F.items()) if "@t_s" in d and first is not None and d["@t_s"] > first and not any(a <= d["@t_s"] <= b for a, b in iv)]
|
||||
over = collections.Counter(); worst = []
|
||||
for f in game:
|
||||
d = F[f]; cpu = d.get("@work_ms", 0) - d.get("@wait_ms", 0) - d.get("@pq_wait_ms", 0)
|
||||
if cpu > 16.7:
|
||||
src = "上传" if d.get("@upload_ms", 0) > 4 else "建管线建库" if d.get("@pso_new", 0) + d.get("@lib_new", 0) > 0 else "其它"
|
||||
over[src] += 1; worst.append((round(cpu, 1), f, src, round(d.get("@upload_ms", 0), 1), int(d.get("@pso_new", 0) + d.get("@lib_new", 0)), round(d.get("@sub_cpu_ms", 0), 1)))
|
||||
cpus = sorted(F[f].get("@work_ms", 0) - F[f].get("@wait_ms", 0) - F[f].get("@pq_wait_ms", 0) for f in game)
|
||||
p99 = cpus[int(0.99 * (len(cpus) - 1))] if cpus else 0
|
||||
print(f"FRAMEPROBE {scene} 局{k} 局内帧 {len(game)} 超16.7ms {sum(over.values())} {dict(over)} CPU中位 {cpus[len(cpus)//2] if cpus else 0:.1f} p99 {p99:.1f} 读取撤下 {len(iv)}")
|
||||
for w in sorted(worst, reverse=True)[:5]: print(" 最慢", w, "(CPU ms, 帧, 归因, 上传ms, 新建管线库, 提交CPU ms)")
|
||||
PY
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
# 生成 dm/host/dm_bright_levels.inc:每个关卡号 → 原版画面随不随昼夜(3D 画面加亮的「室内」判据)。全部从原版数据推,不手列地图:
|
||||
# 关卡的 biome:预设类(DrlgType 2)取 LvlPrest 里本关卡的预设文件 → hd/env/preset/<路径>.json 的 biomeFilename,多数票;
|
||||
# 野外类(DrlgType 3)取 LvlTypes 本关卡类型的图块目录 → 该目录下预设 json 的 biomeFilename,多数票;迷宫类(DrlgType 1)不用(规则里一律 k=4)。
|
||||
# 随不随昼夜:biome 的 _day 与 _night 画面配置(hd/env/vis)去掉 name / id 后内容是否相同。
|
||||
# 用法:gen_bright_levels.py <原版 RomFS(Update)> > dm/host/dm_bright_levels.inc
|
||||
# 构建时由 dm/host/Makefile 调,直接读玩家自己的游戏文件;生成的表不进仓库(同 dm_vault_tab.h、dm_hud_exp.h)。
|
||||
# Generates dm/host/dm_bright_levels.inc: each level id → whether the original game's picture follows day and night (the "indoor" criterion for 3D picture brightening). Everything is derived from the original game's data, no maps are listed by hand:
|
||||
# A level's biome: for preset levels (DrlgType 2) take this level's preset files in LvlPrest → biomeFilename of hd/env/preset/<path>.json, majority vote;
|
||||
# for wilderness levels (DrlgType 3) take the tile directory of this level's type in LvlTypes → biomeFilename of the preset json files under that directory, majority vote; maze levels (DrlgType 1) are not used (the rule gives them k=4 across the board).
|
||||
# Whether it follows day and night: whether the biome's _day and _night picture configs (hd/env/vis) have the same content after removing name / id.
|
||||
# Usage: gen_bright_levels.py <original game RomFS (Update)> > dm/host/dm_bright_levels.inc
|
||||
# Called by dm/host/Makefile at build time, reading the player's own game files directly; the generated table is not committed to the repo (same as dm_vault_tab.h, dm_hud_exp.h).
|
||||
import csv, io, json, os, re, sys, collections
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'ios', 'tools'))
|
||||
import touch_layout
|
||||
if len(sys.argv) != 2: sys.exit('用法:gen_bright_levels.py <原版 RomFS(Update)>')
|
||||
romfs = sys.argv[1]
|
||||
# 游戏文件清单读一遍建索引(要读上千个小 json,逐个线性查清单太慢):小写路径 → 清单行
|
||||
# Read the game file list once and build an index (over a thousand small json files have to be read, and a linear search of the list for each one is too slow): lowercase path → list line
|
||||
IDX = {}
|
||||
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
f = line.rstrip('\n').split('|')
|
||||
if len(f) >= 11: IDX.setdefault(f[9].lower().split(':', 1)[-1], f)
|
||||
def rd(path):
|
||||
f = IDX.get(path.lower())
|
||||
if f is None: raise SystemExit('gen_bright_levels:游戏文件里没有 %s(RomFS 版本不对?要 3.3.94012)' % path)
|
||||
return touch_layout._read_entry(romfs, f)
|
||||
ENV = 'data/hd/env/'
|
||||
def ls(prefix): # 清单里直接在这个目录下的文件名(保留原大小写) | file names in the list that sit directly under this directory (original case kept)
|
||||
out = []
|
||||
for k, f in IDX.items():
|
||||
if k.startswith(prefix) and '/' not in k[len(prefix):]: out.append(f[9].split(':', 1)[-1][len(prefix):])
|
||||
return out
|
||||
def tsv(name):
|
||||
r = list(csv.reader(io.StringIO(rd('data/global/excel/' + name).decode('utf-8', 'replace')), delimiter='\t')); return r[0], r[1:]
|
||||
def biome_of_json(path):
|
||||
try: return os.path.basename(json.loads(rd(path)).get('biomeFilename', '')).replace('.json', '')
|
||||
except (SystemExit, Exception): return ''
|
||||
def norm(path):
|
||||
def strip(o):
|
||||
if isinstance(o, dict): return {k: strip(v) for k, v in o.items() if k not in ('name', 'id')}
|
||||
if isinstance(o, list): return [strip(v) for v in o]
|
||||
return o
|
||||
return json.dumps(strip(json.loads(rd(path))), sort_keys=True)
|
||||
varies = {}
|
||||
for f in ls(ENV + 'biome/'):
|
||||
s = rd(ENV + 'biome/' + f).decode('utf-8', 'replace'); vis = re.findall(r'"visualDataFilename"\s*:\s*"data/hd/env/(vis/[^"]+)"', s)
|
||||
d = [v for v in vis if v.endswith('_day.json')]; n = [v for v in vis if v.endswith('_night.json')]
|
||||
if d and n and (ENV + d[0]).lower() in IDX and (ENV + n[0]).lower() in IDX: varies[f[:-5]] = norm(ENV + d[0]) != norm(ENV + n[0])
|
||||
def preset_json(ds1): # Act1/Town/TownN1.ds1 → hd/env/preset/act1/town/townN1.json(目录与文件名都不分大小写) | Act1/Town/TownN1.ds1 → hd/env/preset/act1/town/townN1.json (directory and file names are both case-insensitive)
|
||||
parts = ds1.replace('\\', '/').split('/'); p = ENV + 'preset/' + '/'.join(x.lower() for x in parts[:-1]) + '/' + parts[-1].rsplit('.', 1)[0].lower() + '.json'
|
||||
return p if p.lower() in IDX else None
|
||||
def dir_biome(rel): # 图块目录(如 Act1/Outdoors)→ 该目录下预设 json 的多数 biome | Tile directory (e.g. Act1/Outdoors) → the majority biome of the preset json files under that directory
|
||||
d = ENV + 'preset/' + '/'.join(x.lower() for x in rel.replace('\\', '/').split('/')) + '/'
|
||||
c = collections.Counter(biome_of_json(d + f) for f in ls(d) if f.lower().endswith('.json'))
|
||||
return c.most_common(1)[0][0] if c else ''
|
||||
lh, lv = tsv('Levels.txt'); ph, pv = tsv('LvlPrest.txt'); th, tv = tsv('LvlTypes.txt')
|
||||
iid, iname, idt, ilt, iact = lh.index('Id'), lh.index('Name'), lh.index('DrlgType'), lh.index('LevelType'), lh.index('Act')
|
||||
pl, pf = ph.index('LevelId'), [ph.index(f'File{k}') for k in range(1, 7)]
|
||||
types = {r[th.index('Id')]: r for r in tv if len(r) > 1}
|
||||
out = []
|
||||
for r in lv:
|
||||
if len(r) <= ilt or not r[iid].strip().isdigit(): continue
|
||||
lid, dt = int(r[iid]), r[idt].strip()
|
||||
if not dt.isdigit(): dt = '0'
|
||||
c = collections.Counter()
|
||||
if dt == '2':
|
||||
for p in pv:
|
||||
if len(p) > pf[-1] and p[pl].strip() == str(lid):
|
||||
for k in pf:
|
||||
j = preset_json(p[k]) if p[k] not in ('', '0') else None
|
||||
if j: c[biome_of_json(j)] += 1
|
||||
elif dt == '3':
|
||||
t = types.get(r[ilt].strip())
|
||||
if t:
|
||||
for k in range(2, len(t)):
|
||||
m = re.match(r'(Act\d|Expansion)[/\\]([A-Za-z]+)[/\\]', t[k] or '')
|
||||
if m: c[dir_biome(m.group(1) + '/' + m.group(2))] += 1
|
||||
c.pop('', None)
|
||||
b = c.most_common(1)[0][0] if c else ''
|
||||
out.append((lid, r[iname], dt, int(r[iact] or 0), b, int(varies[b]) if b in varies else -1))
|
||||
print('// 由 dm/tools/gen_bright_levels.py 在构建时从玩家自己的游戏文件(Levels / LvlPrest / LvlTypes 与 hd/env 画面配置)生成,勿手改,不进仓库。')
|
||||
print('// 每行:关卡号、幕号(Levels.txt Act,0 起)、DrlgType(1 迷宫 2 预设 3 野外)、原版画面随不随昼夜(1 随 / 0 不随 / -1 未找到 biome)——biome、关卡名')
|
||||
for lid, name, dt, act, b, v in out: print(f'{{ {lid}, {act}, {dt or 0}, {v} }}, // {b or "(无)"},{name}')
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
# 把改写后的模块映像直接写成一个苹果格式的动态库 Guest.framework/Guest:只装段,没有符号,没有代码之外的任何东西。
|
||||
# 只用 Python 标准库,不调用编译器、链接器或任何苹果工具,在 macOS / Linux / Windows 上产出逐字节相同的文件。
|
||||
# 给谁用:壳安装包(ios/tools/shell_build.sh)不含游戏程序;使用者用自己的游戏文件改写出模块映像后,由 d2rm_pack.py 调本脚本
|
||||
# 写出这个库、放进安装包的 Frameworks/,再用自签工具整包签名。宿主的装载器(host/loader.c 的 DM_SHELL 分支)加载它并按节名取段。
|
||||
#
|
||||
# 节的布局与内嵌做法(ios/tools/gen_embed.py)一致,装载器不用分两套:
|
||||
# __TEXT,__dm<名>x0 原 text:[0, 圆整16K(TEXT_END))
|
||||
# __DM<名>W,__img 可写段:[圆整16K(TEXT_END), PATCH_OFF)
|
||||
# __TEXT,__dm<名>x1 补丁区:[PATCH_OFF, 圆整16K(文件尾))
|
||||
# 文件格式上要注意的三点(都是真机 / Mac 上实测出来的):
|
||||
# · 必须声明依赖 /usr/lib/libSystem.B.dylib,否则系统拒绝加载(「must link with at least libSystem.dylib」);
|
||||
# · 每个节按 16K 对齐、整页大小:装载器用 vm_remap 按整页取;
|
||||
# · __LINKEDIT 放在最后并留在文件末尾:签名工具把签名追加在它后面。
|
||||
# 用法:guest_dylib.py <产物目录> <输出目录> <模块名...> 输出 <输出目录>/Guest.framework/{Guest,Info.plist}
|
||||
# Write the rewritten module images directly as one Apple-format dynamic library Guest.framework/Guest: it holds only segments, no symbols, and nothing other than the code.
|
||||
# Uses only the Python standard library, calls no compiler, linker or any Apple tool, and produces byte-for-byte identical files on macOS / Linux / Windows.
|
||||
# Who it is for: the shell install package (ios/tools/shell_build.sh) contains no game program; after users rewrite the module images from their own game files, d2rm_pack.py calls this script
|
||||
# to write this library and put it into the install package's Frameworks/, and then the whole package is signed with a sideloading tool. The host's loader (the DM_SHELL branch of host/loader.c) loads it and fetches the segments by section name.
|
||||
# The section layout matches the embedded approach (ios/tools/gen_embed.py), so the loader does not need two variants:
|
||||
# __TEXT,__dm<name>x0 original text: [0, round16K(TEXT_END))
|
||||
# __DM<name>W,__img writable segment: [round16K(TEXT_END), PATCH_OFF)
|
||||
# __TEXT,__dm<name>x1 patch area: [PATCH_OFF, round16K(end of file))
|
||||
# Three points to note about the file format (all found by measurement on a real device / Mac):
|
||||
# · a dependency on /usr/lib/libSystem.B.dylib must be declared, otherwise the system refuses to load it ("must link with at least libSystem.dylib");
|
||||
# · every section is aligned to 16K and is a whole number of pages: the loader takes whole pages with vm_remap;
|
||||
# · __LINKEDIT goes last and stays at the end of the file: the signing tool appends the signature after it.
|
||||
# Usage: guest_dylib.py <build output directory> <output directory> <module name...> writes <output directory>/Guest.framework/{Guest,Info.plist}
|
||||
import hashlib, os, struct, sys
|
||||
|
||||
PG = 0x4000
|
||||
MIN_IOS = 26 << 16 # 与工程的最低系统版本一致(ios/project.yml) | matches the project's minimum system version (ios/project.yml)
|
||||
|
||||
|
||||
def r16(x): return (x + PG - 1) & ~(PG - 1)
|
||||
|
||||
|
||||
def s16(s):
|
||||
b = s.encode(); assert len(b) <= 16, s; return b.ljust(16, b'\0')
|
||||
|
||||
|
||||
def segment(name, addr, size, fileoff, filesize, prot, sects):
|
||||
b = struct.pack('<II16sQQQQiiII', 0x19, 72 + 80 * len(sects), s16(name), addr, size, fileoff, filesize, prot, prot, len(sects), 0)
|
||||
for sn, a, sz, flags in sects:
|
||||
b += struct.pack('<16s16sQQIIIIIIII', s16(sn), s16(name), a, sz, a, 14, 0, 0, flags, 0, 0, 0) # 文件偏移 = 地址;对齐 2^14 | file offset = address; alignment 2^14
|
||||
return b
|
||||
|
||||
|
||||
def dylib_cmd(cmd, name):
|
||||
name += b'\0' * (8 - len(name) % 8)
|
||||
return struct.pack('<IIIIII', cmd, 24 + len(name), 24, 2, 0x10000, 0x10000) + name
|
||||
|
||||
|
||||
def build(out, names):
|
||||
text, wsegs = [], []
|
||||
for n in names:
|
||||
hdr = dict(l[2:].split() for l in open(os.path.join(out, n + '.fixups.tsv')) if l.startswith('# '))
|
||||
te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16)
|
||||
img = open(os.path.join(out, n + '.patched.bin'), 'rb').read(); sz = len(img); a, end = r16(te), r16(sz)
|
||||
assert po % PG == 0 and a <= po <= end, (n, hex(te), hex(po), hex(sz))
|
||||
cut = lambda lo, hi: img[lo:min(hi, sz)].ljust(hi - lo, b'\0')
|
||||
text += [('__dm%sx0' % n, cut(0, a)), ('__dm%sx1' % n, cut(po, end))]
|
||||
wsegs.append(('__DM%sW' % n, cut(a, po)))
|
||||
off = PG; tsects = []; body = b'' # 第一页:文件头与装载命令 | first page: file header and load commands
|
||||
for sn, b in text:
|
||||
tsects.append((sn, off, len(b), 0x80000400)); body += b; off += len(b) # 纯指令节 | pure instructions section
|
||||
cmds = [segment('__TEXT', 0, off, 0, off, 5, tsects)]
|
||||
for sn, b in wsegs:
|
||||
cmds.append(segment(sn, off, len(b), off, len(b), 3, [('__img', off, len(b), 0)])); body += b; off += len(b)
|
||||
strtab = b'\0' * 8
|
||||
uuid = hashlib.sha256(body).digest()[:16] # 由内容定:同样的输入在哪台机器上出的库都逐字节相同 | determined by content: the same input yields a byte-for-byte identical library on whatever machine it is built
|
||||
cmds += [segment('__LINKEDIT', off, PG, off, len(strtab), 1, []),
|
||||
dylib_cmd(0xd, b'@rpath/Guest.framework/Guest'), # LC_ID_DYLIB
|
||||
struct.pack('<II10I', 0x80000022, 48, *([0] * 10)), # LC_DYLD_INFO_ONLY:没有重定位、没有绑定、没有导出 | LC_DYLD_INFO_ONLY: no relocations, no bindings, no exports
|
||||
struct.pack('<IIIIII', 0x2, 24, off, 0, off, len(strtab)), # LC_SYMTAB:0 个符号 | LC_SYMTAB: 0 symbols
|
||||
struct.pack('<II18I', 0xb, 80, *([0] * 18)), # LC_DYSYMTAB
|
||||
struct.pack('<II16s', 0x1b, 24, uuid), # LC_UUID
|
||||
struct.pack('<IIIIII', 0x32, 24, 2, MIN_IOS, MIN_IOS, 0), # LC_BUILD_VERSION:平台 2 = iOS | LC_BUILD_VERSION: platform 2 = iOS
|
||||
dylib_cmd(0xc, b'/usr/lib/libSystem.B.dylib')] # LC_LOAD_DYLIB
|
||||
lc = b''.join(cmds); assert 32 + len(lc) <= PG
|
||||
mh = struct.pack('<IiiIIIII', 0xfeedfacf, 0x0100000c, 0, 6, len(cmds), len(lc), 0x00100085, 0) # arm64、动态库 | arm64, dynamic library
|
||||
return (mh + lc).ljust(PG, b'\0') + body + strtab
|
||||
|
||||
|
||||
INFO_PLIST = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleExecutable</key><string>Guest</string>
|
||||
<key>CFBundleIdentifier</key><string>%s</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
|
||||
<key>CFBundleName</key><string>Guest</string>
|
||||
<key>CFBundlePackageType</key><string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key><string>1.0</string>
|
||||
<key>CFBundleVersion</key><string>1</string>
|
||||
<key>MinimumOSVersion</key><string>26.0</string>
|
||||
<key>CFBundleSupportedPlatforms</key><array><string>iPhoneOS</string></array>
|
||||
</dict></plist>
|
||||
'''
|
||||
|
||||
|
||||
def write(out, dst, names, bundle_id='local.guest'):
|
||||
fw = os.path.join(dst, 'Guest.framework'); os.makedirs(fw, exist_ok=True)
|
||||
data = build(out, names)
|
||||
with open(os.path.join(fw, 'Guest'), 'wb') as f: f.write(data)
|
||||
with open(os.path.join(fw, 'Info.plist'), 'w', encoding='utf-8', newline='\n') as f: f.write(INFO_PLIST % bundle_id)
|
||||
return fw, len(data)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 4: sys.exit(__doc__ or '用法:guest_dylib.py <产物目录> <输出目录> <模块名...>')
|
||||
fw, n = write(sys.argv[1], sys.argv[2], sys.argv[3:])
|
||||
print('%s:%d 字节' % (fw, n))
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
# guirun.sh [-o 标准输出] [-e 标准错误] [-p pid文件] [KEY=VAL ...] -- <程序> [参数…]
|
||||
# 在图形会话里经 LaunchServices 起一个临时 .app,它的入口脚本 exec 目标程序:这样目标的线程才拿得到真实的调度优先档。
|
||||
# 从 ssh / 终端 / launchctl 直接起的进程,界面档与交互档线程一律被系统封顶到普通档,帧时序量出来不真。
|
||||
# open 不带调用方的环境:目标要的变量一律写成 KEY=VAL 传(PATH / HOME 由会话给)。要有人登录着图形会话。
|
||||
# 等目标结束才返回;拿不到目标的退出码(exec 之后没人能 wait 它)⇒ 调用方按目标的输出判结果。-p 文件写目标进程的 pid。
|
||||
# guirun.sh [-o stdout] [-e stderr] [-p pidfile] [KEY=VAL ...] -- <program> [args...]
|
||||
# Launches a temporary .app through LaunchServices inside the GUI session; its entry script execs the target program, which is the only way
|
||||
# the target's threads get their real scheduling priority tier.
|
||||
# For a process launched directly from ssh / a terminal / launchctl, the system clamps every user-interactive and user-initiated thread to the
|
||||
# default tier, so the frame timing measured there is not real.
|
||||
# open does not pass the caller's environment: every variable the target needs must be passed as KEY=VAL (PATH / HOME come from the session).
|
||||
# Someone must be logged in to the GUI session.
|
||||
# Returns only after the target exits; the target's exit code is not available (after exec nobody can wait on it) => the caller judges the
|
||||
# result from the target's output. -p file receives the target process's pid.
|
||||
set -u
|
||||
O=/dev/null; E=/dev/null; P=; ENV=()
|
||||
while [ $# -gt 0 ]; do case $1 in -o) O=$2; shift 2;; -e) E=$2; shift 2;; -p) P=$2; shift 2;; --) shift; break;; *=*) ENV+=(--env "$1"); shift;; *) break;; esac; done
|
||||
[ $# -ge 1 ] || { echo "用法:guirun.sh [-o f] [-e f] [-p pidf] [K=V…] -- <程序> [参数…]" >&2; exit 2; }
|
||||
T=$(mktemp -d "${TMPDIR:-/tmp}/guirun.XXXXXX") || exit 2; A=$T/GuiRun.app; trap 'rm -rf "$T"' EXIT; mkdir -p "$A/Contents/MacOS"
|
||||
PF=${P:-$T/pid}
|
||||
{ printf '#!/bin/bash\necho $$ > %q\ncd %q\n' "$PF" "$PWD"
|
||||
# 图形会话起的进程打开文件软上限只有 256 ⇒ 抬到内核每进程上限;抬不上去就在标准错误里报出来、不起目标
|
||||
# A process launched from the GUI session has a soft open-file limit of only 256 => raise it to the kernel per-process limit;
|
||||
# if it cannot be raised, report that on stderr and do not launch the target
|
||||
printf 'n=$(sysctl -n kern.maxfilesperproc); ulimit -n "$n" || { echo "guirun:ulimit -n $n 失败(软上限仍是 $(ulimit -Sn)),不起目标" >&2; exit 97; }\n'
|
||||
printf '%q ' exec "$@"; echo; } > "$A/Contents/MacOS/run"; chmod +x "$A/Contents/MacOS/run" # 必须 exec:优先档只跟 LaunchServices 起的那个进程,它的子进程又会被封顶 | must exec: the QoS tier applies only to the process LaunchServices itself launched; a child of that process would be clamped again
|
||||
cat > "$A/Contents/Info.plist" <<PL
|
||||
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict><key>CFBundleExecutable</key><string>run</string><key>CFBundleIdentifier</key><string>local.guirun.$$</string><key>CFBundlePackageType</key><string>APPL</string></dict></plist>
|
||||
PL
|
||||
open -n -W --stdout "$O" --stderr "$E" ${ENV[@]+"${ENV[@]}"} "$A" || exit 125
|
||||
@@ -0,0 +1,40 @@
|
||||
# HLE 审计清单:抽 dm/host 下全部 HLE_FORCE / HLE 条目与 libc 直通表、svc 分派,输出 TSV(类别 文件 行 改编名 C 名 理由 函数体行数 体内特征)
|
||||
# 体内特征只是粗筛提示(如「只 return RES_OK」),三类判定(完整 / 简化 / 剪口)须逐条读体后人工定。
|
||||
# 用法:hle_inventory.py [输出 tsv]
|
||||
# HLE audit list: extracts all HLE_FORCE / HLE entries under dm/host plus the libc passthrough table and svc dispatch, and outputs TSV (category, file, line, mangled name, C name, reason, function body line count, body features)
|
||||
# Body features are only a coarse screening hint (e.g. "only return RES_OK"); the three-way classification (full / simplified / cut) must be decided manually after reading each body.
|
||||
# Usage: hle_inventory.py [output tsv]
|
||||
import re, sys, glob, os
|
||||
H = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'host')
|
||||
rows = []
|
||||
def body_of(src, start):
|
||||
i = src.index('{', start); d = 0
|
||||
for j in range(i, len(src)):
|
||||
if src[j] == '{': d += 1
|
||||
elif src[j] == '}':
|
||||
d -= 1
|
||||
if not d: return src[i:j + 1]
|
||||
return ''
|
||||
def feat(b):
|
||||
s = re.sub(r'\s+', ' ', b)
|
||||
f = []
|
||||
if re.fullmatch(r'\{ ?(\(void\)[^;]*; ?)*return (RES_OK|0|RES_FAIL|0x[0-9a-fA-F]+u?|1|true|false); ?\}', s): f.append('只返回常量')
|
||||
if 'RES_FAIL' in s: f.append('含失败返回')
|
||||
if re.search(r'LOG\(|die\(', s): f.append('有日志/中止')
|
||||
if len(s) < 60: f.append('极短')
|
||||
return ','.join(f)
|
||||
for fn in sorted(glob.glob(os.path.join(H, 'hle_*.c'))):
|
||||
src = open(fn, encoding='utf-8').read()
|
||||
for m in re.finditer(r'\bHLE_FORCE\(\s*"([^"]+)"\s*,\s*"((?:[^"\\]|\\.)*)"\s*,\s*([^,]+),\s*(\w+)', src):
|
||||
b = body_of(src, m.end()); rows.append(('FORCE', os.path.basename(fn), src[:m.start()].count('\n') + 1, m.group(1), m.group(4), m.group(2), b.count('\n') + 1, feat(b)))
|
||||
for m in re.finditer(r'(?<![_A-Z])HLE\(\s*"([^"]+)"\s*,\s*([^,]+),\s*(\w+)', src):
|
||||
b = body_of(src, m.end()); rows.append(('HLE', os.path.basename(fn), src[:m.start()].count('\n') + 1, m.group(1), m.group(3), '', b.count('\n') + 1, feat(b)))
|
||||
src = open(os.path.join(H, 'hle_table.c'), encoding='utf-8').read()
|
||||
for n in re.findall(r'\bL\((\w+)\)', src): rows.append(('LIBC', 'hle_table.c', 0, n, n, 'libc 直通', 0, ''))
|
||||
out = sys.argv[1] if len(sys.argv) > 1 else '/dev/stdout'
|
||||
with open(out, 'w', encoding='utf-8') as f:
|
||||
f.write('类别\t文件\t行\t改编名\tC名\t理由\t体行数\t特征\n')
|
||||
for r in rows: f.write('\t'.join(map(str, r)) + '\n')
|
||||
from collections import Counter
|
||||
print('条目', len(rows), Counter(r[0] for r in rows), file=sys.stderr)
|
||||
print('只返回常量 / 极短:', sum(1 for r in rows if '只返回常量' in r[7]), file=sys.stderr)
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/bin/bash
|
||||
# 存档逐字节对拍闸门(宿主侧):宿主回放真值局 → 存盘退出 → 宿主存档 vs 真值 save_after(dm/verify/savecmp.py),并跑负对照。
|
||||
# 用法:host_savecmp.sh <真值局目录> [产物目录]
|
||||
# 真值局目录须有 meta.json(save = 起始存档指纹,game_seed)、c2s.jsonl、ticks.jsonl、save_after/0
|
||||
# 环境:FT=固定墙钟秒(缺省 1790000000);SC=savecmp.py 路径;A_TIME=真值 meta 无 wall 字段时真值侧时间的核对值;KEYS_FRONT=进局键序;KEYS_EXIT=存盘退出键序(缺省按真值 events.jsonl 生成;设为空串 = 不按键)
|
||||
# HSC_WALL=秒:外层退出期限(缺省120);客体看门狗始终早30秒,长真值局显式放宽(不改逻辑拍/退出条件)。
|
||||
# 步骤:
|
||||
# ① 起始存档指纹:data/switch/*/MANIFEST.sha256 的 sha(= dm/verify/savesha.sh 同算法)与 meta.json 的 save 比,找不到即报红退出;
|
||||
# 宿主只拿 0/ 副本,拷完逐文件按 MANIFEST 核 sha。
|
||||
# ② 回放:DM_C2S_REPLAY + DM_GAME_SEED + DM_FIXED_TIME;过文件末拍后宿主客户端自发消息放行,并发合成 UI 消息 DM:ReplayDone(KEYS_EXIT 可等它)。
|
||||
# ③ 判据:savecmp.py 真值 vs 宿主 判绿;负对照 真值 vs 起始存档 必须判红。
|
||||
# Byte-by-byte save comparison gate check (host side): the host replays a ground-truth run → saves and exits → host save vs ground-truth save_after (dm/verify/savecmp.py), and runs a negative control.
|
||||
# Usage: host_savecmp.sh <ground-truth run dir> [build output dir]
|
||||
# The ground-truth run dir must contain meta.json (save = starting save fingerprint, game_seed), c2s.jsonl, ticks.jsonl, save_after/0
|
||||
# Environment: FT=fixed wall-clock seconds (default 1790000000); SC=path of savecmp.py; A_TIME=check value for the ground-truth side time when the ground-truth meta has no wall fields; KEYS_FRONT=key sequence to enter the run; KEYS_EXIT=save-and-exit key sequence (by default generated from the ground-truth events.jsonl; set to the empty string = no key presses)
|
||||
# HSC_WALL=seconds: outer exit deadline (default 120); the guest watchdog always fires 30 seconds earlier, relax it explicitly for long ground-truth runs (logic ticks / exit conditions are not changed).
|
||||
# Steps:
|
||||
# ① Starting save fingerprint: the sha of data/switch/*/MANIFEST.sha256 (= same algorithm as dm/verify/savesha.sh) is compared with save in meta.json; if not found, report a failure and exit;
|
||||
# the host takes only the 0/ copy, and after copying checks the sha of every file against MANIFEST.
|
||||
# ② Replay: DM_C2S_REPLAY + DM_GAME_SEED + DM_FIXED_TIME; after the last tick of the file the host client's own spontaneous messages are let through, and a synthetic UI message DM:ReplayDone is sent (KEYS_EXIT can wait for it).
|
||||
# ③ Criterion: savecmp.py ground truth vs host must pass; the negative control ground truth vs starting save must fail.
|
||||
set -u; HOLD=
|
||||
export LC_ALL=C
|
||||
TR=${1:?真值局目录}; OUT=${2:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/3.3.94012-r12}
|
||||
FT=${FT:-1790000000}
|
||||
X=${DM_ROOT:-$HOME/dm-work}; PY=$X/build/cache/dm/venv/bin/python3; HERE=$(cd "$(dirname "$0")/.." && pwd)
|
||||
R=$X/run/platform; T=$R/hsc_$(basename "$TR")_$(date +%m%d_%H%M%S)_$$; mkdir -p "$T/user" || exit 1 # 每次新目录不覆盖(同名目录 rm -rf 丢了卡死现场) | A new directory every time, never overwritten (rm -rf of a same-name directory lost the diagnostics of a hang)
|
||||
echo "局目录 $T"
|
||||
red() { echo "【红】$*"; exit 2; }
|
||||
WALL=${HSC_WALL:-600}
|
||||
case "$WALL" in ''|*[!0-9]*) red "HSC_WALL 须为大于30的整数秒";; esac
|
||||
WALL=$((10#$WALL)); [ "$WALL" -gt 30 ] || red "HSC_WALL 须大于30秒"
|
||||
WATCH=$((WALL * 3 / 4))
|
||||
echo "期限:宿主无进展看门狗 15 秒、总墙钟兜底 ${WATCH} 秒、退出墙钟 ${WALL} 秒"
|
||||
for f in meta.json c2s.jsonl save_after/0; do [ -e "$TR/$f" ] || red "真值局缺 $f"; done
|
||||
|
||||
# ① 指纹
|
||||
# ① Fingerprint
|
||||
WANT=$($PY -c "import json,sys;m=json.load(open(sys.argv[1]));s=m['save'];print(s[0] if isinstance(s,list) else s)" "$TR/meta.json") || red "meta.json 读不出 save"
|
||||
SEED=$($PY -c "import json,sys;v=json.load(open(sys.argv[1])).get('game_seed');print('' if v is None else v)" "$TR/meta.json")
|
||||
REF=
|
||||
for m in $X/data/switch/*/MANIFEST.sha256; do [ "$(shasum -a 256 "$m" | cut -c1-64)" = "$WANT" ] && { REF=$(dirname "$m"); break; }; done
|
||||
[ -n "$REF" ] || red "起始存档指纹 $WANT 在 data/switch/*/MANIFEST.sha256 里找不到"
|
||||
echo "① 起始存档 ${REF}(指纹 ${WANT:0:12}… 与 meta.json 一致)"
|
||||
cp -R "$REF/0000000000000001/0" "$T/user/0" && chmod -R u+w "$T/user/0" || red "拷存档失败"
|
||||
( cd "$T/user" && grep ' 0000000000000001/0/' "$REF/MANIFEST.sha256" | sed 's| 0000000000000001/| |' | shasum -a 256 -c --quiet ) || red "0/ 副本与 MANIFEST 不符"
|
||||
NF=$(grep -c ' 0000000000000001/0/' "$REF/MANIFEST.sha256"); echo " 0/ 副本 $NF 个文件逐个核 sha 通过"
|
||||
|
||||
# ② 回放
|
||||
# ② Replay
|
||||
K=${KEYS_FRONT:-A@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterDifficultyModal,A@OpenPanel:CharacterDifficultyModal>FrontEndNavigation:ToGame}
|
||||
# 存盘退出键序缺省按真值 events.jsonl 生成:选项页一打开即暂停并存盘,存档状态取决于暂停生效那一拍。
|
||||
# 游玩段末拍 L(kind=play 的 last)按 Plus,L+18 按 R(技能树),局后末拍 E(kind=after_done 的 last_tick)入口按 R(选项页)并 DM_TICK_HOLD=E
|
||||
# 冻结客体时钟直到 ExitGame ⇒ 暂停必落在拍 E(不冻结时 实测拍 N 按键暂停落在 N 或 N+1,取决于下一帧先不先跑一拍),再 A 保存并退出。
|
||||
# 只适用于已转换术士君临的角色(PauseLayoutGarden 缺省光标即「保存并退出」);未转换角色须自给 KEYS_EXIT(加 DpadDown)
|
||||
# The save-and-exit key sequence is by default generated from the ground-truth events.jsonl: the game pauses and saves as soon as the options page opens, and the save state depends on the tick at which the pause takes effect.
|
||||
# Press Plus at the last tick L of the play segment (last of kind=play), press R at L+18 (skill tree), press R (options page) at the entry of the last post-run tick E (last_tick of kind=after_done) with DM_TICK_HOLD=E
|
||||
# freezing the guest clock until ExitGame ⇒ the pause must land on tick E (without freezing, a key press at tick N was measured to pause at N or N+1, depending on whether the next frame runs a tick first), then A to save and exit.
|
||||
# Applies only to characters already converted to Reign of the Warlock (the default cursor of PauseLayoutGarden is 「保存并退出」(Save and Exit)); for unconverted characters KEYS_EXIT must be supplied by the caller (add DpadDown)
|
||||
if [ -z "${KEYS_EXIT+x}" ] && [ -f "$TR/events.jsonl" ]; then
|
||||
KEYS_EXIT=$($PY - "$TR/events.jsonl" <<'PYEOF'
|
||||
import json, sys
|
||||
L = E = None
|
||||
for line in open(sys.argv[1]):
|
||||
try: e = json.loads(line)
|
||||
except ValueError: continue
|
||||
if e.get('kind') == 'play': L = e['last']
|
||||
if e.get('kind') == 'after_done': E = e['last_tick']
|
||||
if L is not None and E is not None:
|
||||
print(f'PLUS@DM:Tick:{L}#>OpenPanel:PlayerInventoryExpansionLayout,R@DM:Tick:{L + 18}#>OpenPanel:SkillsTreePanel,'
|
||||
f'R@DM:Tick:{E}#>OpenPanel:PauseLayout,A@OpenPanel:PauseLayout%1>PausePanelMessage:ExitGame\t{E}')
|
||||
PYEOF
|
||||
)
|
||||
HOLD=${KEYS_EXIT##* }; KEYS_EXIT=${KEYS_EXIT% *}
|
||||
echo "② 退出键序(按真值 events.jsonl 生成):${KEYS_EXIT};DM_TICK_HOLD=$HOLD"
|
||||
fi
|
||||
[ -n "${KEYS_EXIT:-}" ] && K="$K,$KEYS_EXIT"
|
||||
cd "$HERE/host" || exit 1
|
||||
make -s >/dev/null || red "宿主编译失败" # 宿主须是当前源码(未重编的旧宿主假红) | The host must be built from the current source (a stale host that was not rebuilt gives a false failure)
|
||||
mkdir -p "$T/temp"
|
||||
env DM_SAVE="$T/user/0" DM_TEMP="$T/temp" ${SEED:+DM_GAME_SEED=$SEED} ${HOLD:+DM_TICK_HOLD=$HOLD} DM_FIXED_TIME=$FT "DM_KEYS=$K" DM_C2S_REPLAY="$TR/c2s.jsonl" DM_TICKS="$T/ticks.jsonl" DM_C2S_LOG="$T/out.c2s" \
|
||||
DM_UIMSG=1 DM_PRESENT_HZ=60 DM_WATCH_STALL=15 DM_WATCH=$WATCH ./dmhost "$OUT" main sdk > "$T/host.log" 2>&1 &
|
||||
P=$!
|
||||
for i in $(seq 1 $((WALL * 10))); do # 退出判据不变:回到主菜单(第2次MainMenuButtonRibbon);墙钟兜底WALL秒 | Exit criterion unchanged: back at the main menu (2nd MainMenuButtonRibbon); wall-clock fallback of WALL seconds
|
||||
[ "$(grep -c 'OpenPanel MainMenuButtonRibbon' "$T/host.log")" -ge 2 ] && { echo "② 已回到主菜单(第 $((i/10)) 秒)"; break; }
|
||||
kill -0 $P 2>/dev/null || { echo "② 宿主提前退出"; break; }; sleep 0.1
|
||||
done
|
||||
[ "$(grep -c 'OpenPanel MainMenuButtonRibbon' "$T/host.log")" -ge 2 ] || { kill $P 2>/dev/null; grep '【红】看门狗' "$T/host.log" | tail -1; red "${WALL} 秒内没回到主菜单"; }
|
||||
sleep 2; kill $P 2>/dev/null; wait $P 2>/dev/null
|
||||
grep -E 'DM_FIXED_TIME|DM_C2S_REPLAY|hid 脚本步.*(确认|红)|【红】|ExitGame' "$T/host.log" | grep -v 贴图号 | cut -c1-160
|
||||
K6=0; [ -f "$TR/ticks.jsonl" ] && { $PY "$HERE/verify/ryu/selfcmp.py" "$TR/ticks.jsonl" "$T/ticks.jsonl" | tail -8; K6=${PIPESTATUS[0]}; }
|
||||
|
||||
# ③ 判据(时间字段核来源:宿主侧 --b-time=FT;真值侧 meta.json 有 wall_start/wall_end 用 --a-meta,否则须显式给 A_TIME=秒,不给则 savecmp 判「未核」红)
|
||||
# ③ Criterion (time field source check: host side --b-time=FT; on the ground-truth side use --a-meta if meta.json has wall_start/wall_end, otherwise A_TIME=seconds must be given explicitly, and if it is not, savecmp fails with 「未核」(unverified))
|
||||
SC=${SC:-$HERE/verify/savecmp.py}
|
||||
MJ=$TR/meta.json; [ -f "$TR/meta.v2.json" ] && MJ=$TR/meta.v2.json # 补记墙钟区间的版本 | The version with the wall-clock interval recorded afterwards
|
||||
MJ=${META:-$MJ} # 可显式指定 | Can be specified explicitly
|
||||
AT="--a-meta=$MJ"; grep -q wall_start "$MJ" || AT=${A_TIME:+--a-time=$A_TIME}
|
||||
echo "③ 正对照:真值 vs 宿主($SC --b-time=$FT $AT)"; $PY "$SC" "$TR/save_after" "$T/user" --b-time=$FT $AT; G=$?
|
||||
echo "③ 负对照:真值 vs 起始存档"; $PY "$SC" "$TR/save_after" "$REF/0000000000000001" --b-time=$FT $AT; N=$?
|
||||
echo "结论:逐拍退出码 ${K6}、正对照退出码 ${G}(0 = 绿),负对照退出码 ${N}(须非 0)"
|
||||
[ $K6 = 0 ] && [ $G = 0 ] && [ $N != 0 ]
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# 冻结用例war_summon13的宿主回放:服务器命令+客户端真实Y绑定,严格逐拍/存档对拍。
|
||||
# 用法:bash dm/tools/host_war13.sh <war_summon13真值目录> [产物目录=r17]
|
||||
# 这是固定案例输入,不是通用计划翻译器;2558开技能树、2670学会后2683绑定,E从events.jsonl取,只冻结存盘退出。
|
||||
# Host replay of the frozen case war_summon13: server commands + the client's real Y binding, strict tick-by-tick / save comparison.
|
||||
# Usage: bash dm/tools/host_war13.sh <war_summon13 ground-truth dir> [build output dir=r17]
|
||||
# This is a fixed case input, not a general plan translator; the skill tree opens at 2558, the skill is learned at 2670 and then bound at 2683, E is taken from events.jsonl, and only save-and-exit is frozen.
|
||||
set -u
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
TR=${1:?war_summon13真值目录}; OUT=${2:-$(bash "$(dirname "$0")/product.sh" path keypage)}
|
||||
PY=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python
|
||||
export LC_ALL=C HSC_WALL=${HSC_WALL:-180}
|
||||
# 真值未固定墙钟;宿主固定在真值记录起点,savecmp以meta中的来源区间核验,不掩盖其它差异。
|
||||
# The ground truth did not fix the wall clock; the host is fixed at the start of the ground-truth recording, and savecmp verifies against the source interval in meta without masking other differences.
|
||||
FT=$($PY -c 'import json,sys; m=json.load(open(sys.argv[1])); t=m.get("fix_time"); print(int(t if t is not None else m["wall_start"]))' "$TR/meta.json") || exit 2
|
||||
export FT
|
||||
export KEYS_FRONT='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame,PLUS@DM:Tick:2558#>OpenPanel:SkillsTreePanel,ZR@OpenPanel:SkillsTreePanel%0.5,ZR@%0.3,RIGHT@%0.3,UP@%0.3,UP@%0.3,Y@DM:Tick:2683#>OpenPanel:ButtonBindingModal,Y@OpenPanel:ButtonBindingModal%0.5>ClosePanel:ButtonBindingModal,B@ClosePanel:ButtonBindingModal%0.5>ClosePanel:SkillsTreePanel'
|
||||
unset KEYS_EXIT
|
||||
# 不向结果目录复制ctl、不豁免客户端文件;由游戏原绑定/原保存生成,host_savecmp比较全部文件。
|
||||
# Does not copy ctl into the result directory and does not exempt client files; they are produced by the game's original binding / original save, and host_savecmp compares all files.
|
||||
exec bash "$HERE/host_savecmp.sh" "$TR" "$OUT"
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""按游戏拍号回归堆在用、Metal 已分配、句柄、phys_footprint;斜率单位是每 1000 拍。
|
||||
|
||||
外推值是从起局到 target 拍的总增长:
|
||||
斜率/1000 * (target - 段末拍号) + 段末值 - 段首值。
|
||||
Regresses heap in use, Metal allocated, handles and phys_footprint against the game tick number; the slope unit is per 1000 ticks.
|
||||
The extrapolated value is the total growth from run start to the target tick:
|
||||
slope/1000 * (target - segment end tick) + segment end value - segment start value.
|
||||
"""
|
||||
import sys
|
||||
|
||||
|
||||
def fit(rows, index, target):
|
||||
x = [row[0] for row in rows]
|
||||
y = [row[index] for row in rows]
|
||||
mean_x = sum(x) / len(x)
|
||||
mean_y = sum(y) / len(y)
|
||||
denominator = sum((value - mean_x) ** 2 for value in x)
|
||||
slope_per_tick = (
|
||||
sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y)) / denominator
|
||||
if denominator else 0
|
||||
)
|
||||
slope_per_1000 = slope_per_tick * 1000
|
||||
projected_growth = (
|
||||
slope_per_1000 * (target - x[-1]) / 1000 + y[-1] - y[0]
|
||||
)
|
||||
return slope_per_1000, projected_growth
|
||||
|
||||
|
||||
def main(path, target):
|
||||
rows = []
|
||||
for line in open(path):
|
||||
try:
|
||||
_, tick, heap, metal, handles, phys, rss, footprint = line.split()
|
||||
rows.append((int(tick), int(heap), int(metal), int(handles), int(phys), float(rss), float(footprint)))
|
||||
except ValueError:
|
||||
pass
|
||||
if len(rows) < 3:
|
||||
print('REGRESSION samples=%d insufficient' % len(rows))
|
||||
return 4
|
||||
cut = int(len(rows) * .30)
|
||||
kept = rows[cut:] or rows[-1:]
|
||||
heap_slope, heap_growth = fit(kept, 1, target)
|
||||
metal_slope, metal_growth = fit(kept, 2, target)
|
||||
handle_slope, handle_growth = fit(kept, 3, target)
|
||||
phys_slope, phys_growth = fit(kept, 4, target)
|
||||
rss_slope, rss_growth = fit(kept, 5, target)
|
||||
footprint_slope, footprint_growth = fit(kept, 6, target)
|
||||
phys_projected = kept[-1][4] + phys_growth
|
||||
print(
|
||||
'REGRESSION samples=%d kept=%d heap_slope_MB_1000=%.3f '
|
||||
'metal_slope_MB_1000=%.3f handle_slope_1000=%.3f '
|
||||
'heap_projected_MB=%.3f metal_projected_MB=%.3f handle_projected=%.3f '
|
||||
'phys_projected_GB=%.3f phys_growth_MB=%.3f '
|
||||
'rss_reported_MB=%.3f footprint_reported_MB=%.3f'
|
||||
% (
|
||||
len(rows),
|
||||
len(kept),
|
||||
heap_slope / 1048576,
|
||||
metal_slope / 1048576,
|
||||
handle_slope,
|
||||
heap_growth / 1048576,
|
||||
metal_growth / 1048576,
|
||||
handle_growth,
|
||||
phys_projected / 1073741824,
|
||||
phys_growth / 1048576,
|
||||
rss_growth / 1024,
|
||||
footprint_growth / 1048576,
|
||||
)
|
||||
)
|
||||
red = (heap_growth > 256 * 1048576 or metal_growth > 256 * 1048576
|
||||
or phys_projected > 4.5 * 1073741824 or handle_growth > 16)
|
||||
print('METRIC_RED=%d' % red)
|
||||
return 5 if red else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main(sys.argv[1], int(sys.argv[2])))
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# L3 四场景并行;每段独立起档,判定沿用 l3seg.sh。
|
||||
# L3 four scenes in parallel; each segment starts from its own save independently, and the verdict reuses l3seg.sh.
|
||||
set -u
|
||||
set -o pipefail
|
||||
source "$(cd "$(dirname "$0")" && pwd)/../ios/tools/local_env.sh" # 本机配置(不进仓):MINI_SSH = 第二台 Mac 的 ssh 目标 | Local machine config (not in the repository): MINI_SSH = ssh target of the second Mac
|
||||
here=$(cd "$(dirname "$0")/../.." && pwd); remote=${MINI_SSH:?MINI_SSH 必填:第二台 Mac 的 ssh 目标(用户名@主机),放进本机环境或 ~/.config/dm-ios/local.env}; out=${DM_OUT:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/3.3.94012-r28-touch}
|
||||
if [ "${L3_SKIP_SYNC:-0}" != 1 ]; then remote_root=$(timeout 600s "$here/dm/tools/mini_sync.sh" "$out" | tail -1) || exit 1; else remote_root=${MINI_ROOT:?L3_SKIP_SYNC=1 需要 MINI_ROOT=远端同步目录}; fi
|
||||
stamp=$(date +%Y%m%d_%H%M%S); root=${L3_RUN_DIR:-${DM_ROOT:-$HOME/dm-work}/run/l3/$stamp}; mkdir -p "$root"; start=$(date +%s); pids=
|
||||
for spec in 'cvd5 16000' 'camp1 16000' 'wild1 16000' 'war13_v4 16000'; do
|
||||
set -- $spec
|
||||
( timeout 130s ssh -o BatchMode=yes -o ConnectTimeout=5 "$remote" "L3_RUN_DIR='$remote_root/l3/$stamp/$1' MINI_ROOT='$remote_root' DM_OUT='$remote_root/out/$(basename "$out")' L3_TRUTH_ROOT='$remote_root/data/switch/truth_runs' L3_WAR_ROOT='$remote_root/verify/war13_v4' L3_SAVE_ROOT='$remote_root/data/switch' '$remote_root/src/dm/tools/l3seg.sh' '$1' '$2'" >"$root/$1.log" 2>&1 ) & pids="$pids $!"
|
||||
done
|
||||
rc=0; for p in $pids; do wait "$p" || rc=1; done
|
||||
grep -hE 'REGRESSION|METRIC_RED|L3SEG|推进|存档完整性' "$root"/*.log || true
|
||||
if [ "$rc" -eq 0 ] && ! grep -q 'L3SEG .* RED' "$root"/*.log; then result=OK; else result=RED; fi
|
||||
wall=$(( $(date +%s)-start )); echo "L3 $result 用时 $wall 秒"; timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$remote" "pgrep -af dmhost || true" || true; du -sh "$root"; exit 0
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
# L3:去掉前 30% 采样后回归,外推到 216000 拍。
|
||||
# 红线:堆在用或 Metal 外推增长 > 256 MB,或句柄外推增长 > 16;RSS/phys_footprint 只报告。
|
||||
# L3: regress after dropping the first 30% of samples, extrapolate to 216000 ticks.
|
||||
# Failure line: extrapolated growth of heap in use or Metal > 256 MB, or extrapolated handle growth > 16; RSS/phys_footprint are report-only.
|
||||
set -u
|
||||
set -o pipefail
|
||||
scene=${1:-}; ticks=${2:-}
|
||||
case "$scene" in cvd5|camp1|wild1|war13_v4) ;; *) echo '用法:l3seg.sh <cvd5|camp1|wild1|war13_v4> <段长拍数>' >&2; exit 2;; esac
|
||||
case "$ticks" in ''|*[!0-9]*) echo '段长拍数必须是正整数' >&2; exit 2;; esac
|
||||
[ "$ticks" -gt 0 ] || { echo '拍数必须大于 0' >&2; exit 2; }
|
||||
stamp=$(date +%Y%m%d_%H%M%S)_$scene; run=${L3_RUN_DIR:-${DM_ROOT:-$HOME/dm-work}/run/l3/$stamp}; here=$(cd "$(dirname "$0")/.." && pwd)
|
||||
mini=${MINI_ROOT:-${DM_ROOT:-$HOME/dm-work}/run/mini}; bin=${SWHOST:-$mini/src/dm/host/dmhost}; out=${DM_OUT:-$mini/out/$(bash "$(dirname "$0")/product.sh" name touch)}
|
||||
truth_root=${L3_TRUTH_ROOT:-${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs}; war_root=${L3_WAR_ROOT:-${DM_ROOT:-$HOME/dm-work}/run/verify/dm/v4_truth_bootstrap_1002/war13_v4}; save_root=${L3_SAVE_ROOT:-${DM_ROOT:-$HOME/dm-work}/data/switch}
|
||||
case "$scene" in war13_v4) truth=$war_root; save=$save_root/save_ref_warlock_v2/0000000000000001;; cvd5|camp1|wild1) truth=$truth_root/$scene; save=$save_root/save_ref_warlock/0000000000000001;; *) echo "未知场景:$scene" >&2; exit 2;; esac
|
||||
mkdir -p "$run"; [ -x "$bin" ] || { echo "🔴 缺少 mini 宿主:$bin" >&2; exit 1; }; [ -d "$out" ] || { echo "🔴 产物目录不存在:$out" >&2; exit 1; }; [ -f "$truth/c2s.jsonl" ] || { echo "🔴 缺少命令包:$truth/c2s.jsonl" >&2; exit 1; }
|
||||
if [ -f "$truth/meta.json" ]; then ms=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("save",[""])[-1])' "$truth/meta.json"); [ -d "$ms" ] && save=$ms; fi
|
||||
[ -d "$save/0" ] || { echo "🔴 起始存档不存在:$save/0" >&2; exit 1; }
|
||||
mkdir -p "$run/save"; cp -R "$save/0" "$run/save/0" || exit 1
|
||||
awk -v hi="$ticks" 'match($0,/"tick"[[:space:]]*:[[:space:]]*[0-9]+/){t=substr($0,RSTART,RLENGTH);sub(/^[^0-9]*/,"",t);if(t<hi)print}' "$truth/c2s.jsonl" > "$run/c2s.jsonl"
|
||||
seed=0x12345678; fixed=1790000000
|
||||
if [ -f "$truth/meta.json" ]; then seed=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("game_seed",305419896))' "$truth/meta.json"); fixed=$(python3 -c 'import json,sys;v=json.load(open(sys.argv[1])).get("fix_time");print(v if v is not None else 1790000000)' "$truth/meta.json"); fi
|
||||
last=$((ticks-1)); keys="A@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterDifficultyModal,A@OpenPanel:CharacterDifficultyModal>FrontEndNavigation:ToGame,R@DM:Tick:${last}#>OpenPanel:PauseLayout,A@OpenPanel:PauseLayout%1>PausePanelMessage:ExitGame"
|
||||
rss(){ ps -o rss= -p "$1" 2>/dev/null | awk '{print $1+0}'; }; footprint(){ echo 0; } # 不再外部 vmmap——它每秒遍历宿主整个虚拟内存,把宿主拖慢 29%(同负载 A/B:205 → 145 拍/秒);phys_footprint 改由宿主 L3MEM 行用 task_info 自报 | No more external vmmap -- it walks the host's entire virtual memory every second and slows the host down by 29% (A/B under the same load: 205 → 145 ticks/second); phys_footprint is now self-reported by the host's L3MEM line via task_info
|
||||
start=$(date +%s); export DM_SAVE="$run/save/0" DM_C2S_REPLAY="$run/c2s.jsonl" DM_TICKS="$run/ticks.jsonl" DM_TICKS_N="$ticks" DM_PRESENT_HZ=0 DM_DETCLOCK=33333333 DM_WATCH=110 DM_GAME_SEED="$seed" DM_FIXED_TIME="$fixed" DM_KEYS="$keys" DM_SOAK="$run/soak.tsv,1"; [ "${DM_TEST_LEAK:-}" = 1 ] && export DM_TEST_LEAK=1; [ "${DM_TEST_LEAK_GPU:-}" = 1 ] && export DM_TEST_LEAK_GPU=1
|
||||
timeout 115s "$bin" "$out" main sdk >"$run/host.log" 2>&1 & pid=$!; trap 'kill "$pid" 2>/dev/null || true' EXIT INT TERM
|
||||
while kill -0 "$pid" 2>/dev/null; do target=$(pgrep -P "$pid" | head -1); [ -n "$target" ] || target=$pid; if [ -s "$run/ticks.jsonl" ]; then tick=$(tail -1 "$run/ticks.jsonl" | sed -n 's/.*"tick"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p'); [ -n "$tick" ] && printf '%s\t%s\t%s\t%s\n' "$(date +%s)" "$tick" "$(rss "$target")" "$(footprint "$target")" >> "$run/pressure.tsv"; fi; sleep 1; done
|
||||
wait "$pid"; status=$?; wall=$(( $(date +%s)-start )); [ "$wall" -gt 0 ] || wall=1; [ -s "$run/pressure.tsv" ] || { echo '🔴 没有采到进局压力样本'; exit 1; }
|
||||
awk -v p="$run/pressure.tsv" 'BEGIN{while((getline < p)>0){rss[$2]=$3; fp[$2]=$4}} /L3MEM 拍 [0-9]/{tick=$5; best=""; for (k in rss) if (k <= tick && (best == "" || k > best)) best=k; print "0\t" tick "\t" $7 "\t" $9 "\t" $11 "\t" $13 "\t" (best == "" ? 0 : rss[best]) "\t" (best == "" ? 0 : fp[best])}' "$run/host.log" > "$run/samples.tsv"
|
||||
[ -s "$run/samples.tsv" ] || { echo '🔴 没有采到 L3MEM 样本' >&2; exit 1; }
|
||||
python3 "$here/tools/l3reg.py" "$run/samples.tsv" 216000 > "$run/regression.log"; reg=$?
|
||||
cmp=$here/verify/savecmp.py; savecmp=3; if find "$run/save" -type f -name '*.d2s' -print -quit | grep -q .; then python3 "$cmp" "$run/save" "$run/save" --a-time="$fixed" --b-time="$fixed" >"$run/savecmp.log" 2>&1; savecmp=$?; else echo 'SAVECMP 射程不足:没有 .d2s' >"$run/savecmp.log"; fi
|
||||
cat "$run/regression.log"; tail -4 "$run/savecmp.log"; awk -v s="$scene" -v t="$ticks" -v w="$wall" -v st="$status" -v sc="$savecmp" 'BEGIN{printf "L3SEG %s ticks=%d tick_per_sec=%.2f wall=%ds status=%d savecmp=%d\n",s,t,t/w,w,st,sc}'
|
||||
if [ "$reg" -eq 0 ] && [ "$savecmp" -eq 0 ] && [ "$status" -eq 0 ]; then echo "L3SEG $scene OK"; else echo "L3SEG $scene RED"; fi
|
||||
du -sh "$run"; exit 0
|
||||
@@ -0,0 +1,27 @@
|
||||
# 锁等待对齐:全线程采样日志(DM_SAMPLE=毫秒:*)里,取「等待线程在某等待点上的样本」,对到「持锁线程同一时刻的样本」,
|
||||
# 打出持锁线程那一刻的宿主调用链(到第一个游戏帧为止)与次数汇总——看持锁时在干什么。
|
||||
# 用法:lockalign.py <日志> <起s> <止s> <等待线程 0x…> <等待点前缀,如 main+0x15c8> <持锁线程 0x…>
|
||||
# 例(⑤ 装载期资源锁):lockalign.py samp16/host.log 0.347 0.966 0x1005 main+0x15c8 0x1001
|
||||
# Lock wait alignment: in an all-thread sampling log (DM_SAMPLE=ms:*), take "the samples of the waiting thread at a given wait point" and match them to "the samples of the lock-holding thread at the same moment",
|
||||
# then print the lock-holding thread's host call chain at that moment (up to the first game frame) with a count summary -- to see what it was doing while holding the lock.
|
||||
# Usage: lockalign.py <log> <start s> <end s> <waiting thread 0x...> <wait point prefix, e.g. main+0x15c8> <lock-holding thread 0x...>
|
||||
# Example (⑤ resource lock during loading): lockalign.py samp16/host.log 0.347 0.966 0x1005 main+0x15c8 0x1001
|
||||
import re, sys, collections
|
||||
log, t0, t1, wth, wpt, hth = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), sys.argv[4], sys.argv[5], sys.argv[6]
|
||||
L = open(log, errors='replace').read().splitlines(); S = []
|
||||
for i, l in enumerate(L):
|
||||
m = re.match(r'\[dm\] SAMPLE #\d+ \[([\d.]+)s\] thr=(0x[0-9a-f]+) pc=(\S+) lr=(\S+)', l)
|
||||
if m and i + 1 < len(L) and L[i + 1].startswith('[dm] bt:'): S.append((float(m.group(1)), m.group(2), m.group(3), L[i + 1][9:].split()))
|
||||
W = [s for s in S if s[1] == wth and t0 <= s[0] <= t1 and any(f.startswith(wpt) for f in [s[2]] + s[3][:12])]
|
||||
H = [s for s in S if s[1] == hth]
|
||||
agg = collections.Counter()
|
||||
print(f'{wth} 在 {wpt}* 上等的样本 {len(W)}')
|
||||
for t, *_ in W:
|
||||
n = min(H, key=lambda s: abs(s[0] - t)); chain = []
|
||||
for f in [n[2]] + n[3]:
|
||||
if f.startswith(('main+', 'sdk+')): break
|
||||
chain.append(f.split('+')[0])
|
||||
game = [f for f in n[3] if f.startswith('main+')][:4]
|
||||
print(f'{t:.3f} 持锁线程@{n[0]:.3f} 宿主链:{" ← ".join(chain[:8])} | 游戏帧 {" ← ".join(game)}')
|
||||
for f in set(chain): agg[f] += 1
|
||||
print('宿主函数出现次数:', agg.most_common(15))
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
set -o pipefail
|
||||
|
||||
source "$(cd "$(dirname "$0")" && pwd)/../ios/tools/local_env.sh" # 本机配置(不进仓):MINI_SSH = 第二台 Mac 的 ssh 目标 | Local machine config (not in the repository): MINI_SSH = ssh target of the second Mac
|
||||
REMOTE=${MINI_SSH:?MINI_SSH 必填:第二台 Mac 的 ssh 目标(用户名@主机),放进本机环境或 ~/.config/dm-ios/local.env}
|
||||
ROOT=${MINI_ROOT:-${DM_ROOT:-$HOME/dm-work}/run/mini}
|
||||
OUT=${1:-$(bash "$(dirname "$0")/product.sh" path touch)}
|
||||
OUT_NAME=$(basename "$OUT")
|
||||
HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
COMMIT=$(git -C "$HERE" rev-parse HEAD) || exit 1
|
||||
TREE=$(find "$HERE/dm" -type f -print0 | sort -z | xargs -0 shasum -a 256 | shasum -a 256 | awk '{print $1}') || exit 1
|
||||
STAMP="$COMMIT $TREE $OUT_NAME"
|
||||
DIR="${COMMIT:0:12}_${OUT_NAME}"
|
||||
REMOTE_DIR="$ROOT/$DIR"
|
||||
REMOTE_ROOT="$REMOTE:$REMOTE_DIR"
|
||||
|
||||
started=$(date +%s)
|
||||
if timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" "test -f '$REMOTE_DIR/STAMP' && grep -Fxq '$STAMP' '$REMOTE_DIR/STAMP'"; then
|
||||
echo "已同步跳过:$STAMP"
|
||||
echo "$REMOTE_DIR"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
[ -d "$OUT" ] || { echo "🔴 产物目录不存在:$OUT" >&2; exit 1; }
|
||||
timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" "mkdir -p '$REMOTE_DIR/src' '$REMOTE_DIR/out' '$REMOTE_DIR/data/switch' '$REMOTE_DIR/verify'" || exit 1
|
||||
|
||||
sync_dir() {
|
||||
local source=$1 destination=$2 follow=${3:-}
|
||||
local args=(-a --delete --info=stats2)
|
||||
[ -n "$follow" ] && args+=(-L)
|
||||
timeout 600s rsync "${args[@]}" "$source" "$REMOTE_ROOT/$destination" || exit 1
|
||||
}
|
||||
|
||||
sync_dir "$HERE/dm/" src/dm
|
||||
sync_dir "$OUT/" "out/$OUT_NAME"
|
||||
sync_dir "${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/" data/switch/truth_runs
|
||||
sync_dir "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/" data/switch/save_ref_warlock L
|
||||
sync_dir "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock_v2/" data/switch/save_ref_warlock_v2 L
|
||||
sync_dir "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/" data/switch/save_ref L
|
||||
sync_dir "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/v4_truth_bootstrap_1002/war13_v4/" verify/war13_v4
|
||||
|
||||
timeout 600s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" "make -s -C '$REMOTE_DIR/src/dm/host' dmhost" || exit 1
|
||||
timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" "printf '%s\\n' '$STAMP' > '$REMOTE_DIR/STAMP'; : > '$REMOTE_DIR/.mini_sync_owner'" || exit 1
|
||||
timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" \
|
||||
"find '$ROOT' -maxdepth 1 -mindepth 1 -type d -name '[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]_*' -exec test -f '{}/.mini_sync_owner' \\; -print0 | xargs -0 -r ls -dt | tail -n +4 | xargs -r rm -rf" || exit 1
|
||||
|
||||
bytes=$(timeout 20s ssh -o BatchMode=yes -o ConnectTimeout=5 "$REMOTE" "du -sk '$REMOTE_DIR' | awk '{print \$1 * 1024}'") || exit 1
|
||||
elapsed=$(( $(date +%s) - started ))
|
||||
echo "同步字节数:$bytes"
|
||||
echo "同步耗时:${elapsed}s"
|
||||
echo "$REMOTE_DIR"
|
||||
@@ -0,0 +1,14 @@
|
||||
import sys,struct,lz4.block
|
||||
d=open(sys.argv[1],'rb').read()
|
||||
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)
|
||||
end=segs[2][1]+segs[2][2]
|
||||
img=bytearray(end+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
|
||||
open(sys.argv[2],'wb').write(img)
|
||||
print([hex(x) for s in segs for x in s],hex(bss),'moduleid',d[0x40:0x60].hex())
|
||||
@@ -0,0 +1,878 @@
|
||||
# 通用 NSO 改写器:Switch aarch64 模块 → 可在苹果系统原生执行的映像。
|
||||
# 用法:patch_nso.py <NSO 文件> <输出目录> <模块名>
|
||||
# 改写(苹果内核会改 x18 与 tpidr_el0;Horizon 的线程区、svc、计时器在苹果上没有对应物):
|
||||
# x18 读写 → 线程槽 K18(TSD,经 tpidrro_el0)
|
||||
# mrs tpidr_el0 → 读线程槽 KTLS;msr tpidr_el0 → 写 KTLS
|
||||
# mrs tpidrro_el0 → 读线程槽 KTLR(Horizon ThreadLocalRegion 指针)
|
||||
# svc #n、mrs cntpct_el0 → 宿主门(门地址取自线程槽 KGATE,进 C 后按返回点查 gates.tsv)
|
||||
# 已登记剪口(CUTS,按 NSO 构建号限定):改写前逐条断言原字节,不符即中止;结果列在 <名>.cuts.tsv
|
||||
# 已登记观测门(OBS,按构建号限定):入口一条指令换成「进宿主观测回调 → 执行原指令 → 跳回」,诊断零运行时改代码;列在 <名>.obs.tsv
|
||||
# 键页只在数据段末尾保存“实际键号 × 8”,补丁代码通过键页间接取线程槽:装载器可使用任意键号。
|
||||
# 输出:<名>.patched.bin(键页与补丁区接在映像后 PATCH_OFF)、<名>.fixups.tsv(布局与键页下标表头)、<名>.gates.tsv、<名>.sites.tsv、<名>.cuts.tsv、<名>.obs.tsv
|
||||
# Generic NSO rewriter: Switch aarch64 module → an image that can execute natively on Apple systems.
|
||||
# Usage: patch_nso.py <NSO file> <output dir> <module name>
|
||||
# Rewrites (the Apple kernel modifies x18 and tpidr_el0; Horizon's thread area, svc and timers have no counterpart on Apple):
|
||||
# x18 read/write → thread slot K18 (TSD, via tpidrro_el0)
|
||||
# mrs tpidr_el0 → read thread slot KTLS; msr tpidr_el0 → write KTLS
|
||||
# mrs tpidrro_el0 → read thread slot KTLR (Horizon ThreadLocalRegion pointer)
|
||||
# svc #n, mrs cntpct_el0 → host gate (gate address taken from thread slot KGATE; once in C, gates.tsv is looked up by return point)
|
||||
# Registered cuts (CUTS, restricted by NSO build ID): before rewriting, the original bytes are asserted one by one and any mismatch aborts; results are listed in <name>.cuts.tsv
|
||||
# Registered observation gates (OBS, restricted by build ID): one instruction at the entry is replaced with "enter the host observation callback → execute the original instruction → jump back", so diagnostics modify zero code at runtime; listed in <name>.obs.tsv
|
||||
# The key page only stores "actual key number × 8" at the end of the data segment, and patch code fetches thread slots indirectly through the key page: the loader may use any key number.
|
||||
# Output: <name>.patched.bin (key page and patch area appended after the image at PATCH_OFF), <name>.fixups.tsv (layout and key page index header), <name>.gates.tsv, <name>.sites.tsv, <name>.cuts.tsv, <name>.obs.tsv
|
||||
import struct, re, sys, os
|
||||
from itertools import combinations
|
||||
import lz4.block
|
||||
from capstone import *
|
||||
|
||||
src, outdir, NAME = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
d = open(src, 'rb').read()
|
||||
assert d[:4] == b'NSO0'
|
||||
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
|
||||
TEXT_END = segs[0][2]
|
||||
RO_OFF, DATA_OFF = segs[1][1], segs[2][1]
|
||||
KEY_PAGE_OFF = (len(IMG) + 0x3FFF) & ~0x3FFF
|
||||
IMG.extend(bytes(0x4000))
|
||||
PATCH_OFF = (len(IMG) + 0xFFFF) & ~0xFFFF
|
||||
|
||||
# ---- 已登记剪口:{NSO 构建号: [(偏移, 原字节, 新字节, 理由)]} ----
|
||||
# 联网剪口(排除范围:战网 / 联机):取自社区离线修复(LFS Mod Offline Fix for v2228224,与官方 94012 main 只差这 7 个字)。
|
||||
# 实测系统服务层(nifm 无网 / DNS 黑洞 / 账号服务)绕不过:游戏自己直接发战网请求、按「上次在线」时间放行离线。
|
||||
# ---- Registered cuts: {NSO build ID: [(offset, original bytes, new bytes, reason)]} ----
|
||||
# Networking cuts (excluded scope: Battle.net / online play): taken from a community offline fix (LFS Mod Offline Fix for v2228224, which differs from the official 94012 main in only these 7 words).
|
||||
# Measured: the system service layer (nifm offline / DNS black hole / account service) cannot get around it: the game itself sends Battle.net requests directly and allows offline play according to the "last online" time.
|
||||
CUTS = {'db0507f36b84200ac05f75d76ed5026f': [
|
||||
# (放进所有产物共用的基础改写):游戏显存分配器预算 260 MB → 512 MB
|
||||
# (Placed in the base rewrite shared by all build outputs): game video memory allocator budget 260 MB → 512 MB
|
||||
(0x8524c4, '0808a2d2', '0800a4d2', '显存分配器初始化配置:mov x8,#0x10400000(260 MB)→ mov x8,#0x20000000(512 MB),随后 movk #0xa0,lsl48 与 str [sp,#0x238] 不变;'
|
||||
'原预算下内部分辨率 > 约 345 万像素时(2736x1260 过、2864x1240 崩)渲染目标放不下,main+0x174b018 返回空、main+0x17417a4 读空崩溃;'
|
||||
'只是显存预算,不进游戏逻辑:cvd5 逐拍对拍在 1600x900 与 2868x1320 两档均一致'),
|
||||
(0x1979bc, 'e8a79f1a', 'e8d79f1a', '离线放行窗口:读存档设置键(0x1d53e80 处字串)的上次在线时刻,'
|
||||
'「当前时刻 − 上次在线 < 0x0009356907420000 ns(= 30 天)」置位 [x20+0x2c];lt→gt'),
|
||||
(0x5b14dc, 'e8a79f1a', 'e8d79f1a', '调 0xddab50(缓冲区 [x10+0x138]+x25、剩余长度、回调 0x527d50、表 0x209cdb8、9 项)返回值 <1 置位,'
|
||||
'为真时走 0x5b14f8 分支;lt→gt(业务含义未从字串定出)'),
|
||||
(0x5f3184, 'e8a79f1a', 'e8d79f1a', '数据表 [0x2d64a18+idx*16] → +0xf90 记录(0x1fc 字节)+0x4c 下标 → +0xfd0 记录(0x128 字节)+0xf1 有符号字节 <0 置位,'
|
||||
'与(w26>0x24)相与后作第 4 参传下游;lt→gt(业务含义未从字串定出)'),
|
||||
(0x1d53e80, '55736572204c617374204f6e6c696e6500', '566f6963654c616e677561676500000000',
|
||||
'只读字串 "User Last Online" → "VoiceLanguage":第 1 处改读一个必定存在的设置键,「上次在线」取到小数值,差值恒超 30 天,配合 gt 恒放行'),
|
||||
# 产品剪口:开场 Logo 与「按 A 开始」页剪掉,启动直达主菜单(装载画面保留)
|
||||
# Product cut: the opening Logo and the 「按 A 开始」(Press A to Start) page are cut, and startup goes straight to the main menu (the loading screen is kept)
|
||||
(0x8019ec, '280f0034', 'e8feff34', '前端引导首次进入分支:cbz w8,#0x801bd0(LogoMenuPanel → Logo 视频 → 标题页)改为 cbz w8,#0x8019c8'
|
||||
'(落到直达路径的 0x23e5e0(1) → 0xb156a0 进主菜单;跳过 0x8019bc 起置联机模式 [0x2d7badc]=1 的两条,联机模式保持启动初值 0 = 离线,'
|
||||
'不触发 0x80ec44 的联网检查、断网弹窗与回标题页);r4 版目标 0x8019bc 会置联机模式 1,实测仍回标题页并弹断网框'),
|
||||
# 宿主原生实现剪口(仅宿主:真值模拟器不应用,Ryujinx 不认识 0x80 起的宿主调用号;等价由逐块解码 5511/5511 一致证明)
|
||||
# Cuts for host-native implementations (host only: the ground-truth emulator does not apply them, Ryujinx does not know host call numbers from 0x80 up; equivalence is proven by per-block decoding matching 5511/5511)
|
||||
(0x1b0ee60, 'fc6fbaa9fa6701a9', '011000d4c0035fd6', 'TACT BLTE 块 zlib 解码入口(DecodeZlib)→ svc #0x80 ; ret:宿主用 libdeflate 实现'
|
||||
'(hle_tact.c,调用号登记在 hle.h SVC_HOST_TACT_ZLIB);改写器先打剪口再扫描,svc #0x80 自动成为宿主门,门块保存恢复 x30,ret 回原调用者', '仅宿主'),
|
||||
# 宿主测试开关的落点(仅宿主):缺省宿主原样转调,行为不变
|
||||
# Hook points for host test switches (host only): by default the host forwards as is, behavior unchanged
|
||||
(0x5d3a88, 'a27a0194', '211000d4', '收包泵 0x5d3960 投递客户端命令包的调用点 bl 0x632510 → svc #0x81:宿主缺省以原参数原样调用 0x632510(返回值调用方不用);'
|
||||
'DM_C2S_REPLAY 时丢弃客户端自发命令、改由拍入口按文件注入(diag.c,调用号登记在 hle.h SVC_HOST_C2S_DELIVER)', '仅宿主'),
|
||||
(0x5d39c8, 'ba750194', '411000d4', '收包泵 0x5d3960 投递系统类消息的调用点 bl 0x6310b0 → svc #0x82:宿主缺省以原参数原样调用 0x6310b0(返回值调用方不用);'
|
||||
'DM_C2S_REPLAY 时,回放文件首拍起丢弃宿主客户端自发的系统类消息(之前的加入消息放行),改由拍入口按文件注入(diag.c,调用号登记在 hle.h SVC_HOST_C2S_SYS)', '仅宿主'),
|
||||
# 屏幕比例(仅宿主,配合下方 PARAMS 分辨率参数位):输出分辨率上限 {u32 宽, u32 高},只被分辨率选择的三处读写
|
||||
# (0xe12e28 / 0xe10d70 读:选中值的宽或高超上限即不换;0xe12f54 初始化选完后写成选中值);初值 1920x1080 → 4096x2160,让按屏幕比例放宽的宽度能通过
|
||||
# Screen aspect (host only, together with the resolution parameter slots in PARAMS below): output resolution cap {u32 width, u32 height}, read or written at only three places in resolution selection
|
||||
# (0xe12e28 / 0xe10d70 read: if the selected value's width or height exceeds the cap, no switch is made; 0xe12f54 writes it to the selected value after initialization finishes selecting); initial value 1920x1080 → 4096x2160, so that a width widened to the screen aspect can pass
|
||||
(0x211da30, '8007000038040000', '0010000070080000', '输出分辨率上限初值 1920x1080 → 4096x2160(数据段):宿主按屏幕比例给的宽度(如 iPhone 19.5:9 的 1956x900)'
|
||||
'须不超上限才会被选中;Mac 前端仍给原值 1600x900 / 1280x720,行为不变', '仅宿主'),
|
||||
# 运行模式通知处理(0xe10d30)给「窗口尺寸变化」事件的宽度:原码 mov w9,#0x740; and x9,x25,x9——编译器知道宽只可能是 1280(0x500)/ 1600(0x640),
|
||||
# 把「取低 32 位」优化成了 & (0x500|0x640)。KRES0 / KRES1 参数位换掉了那两个常数,这个推导出来的掩码没跟着改:2868 & 0x740 = 768、2296 & 0x740 = 64
|
||||
# (运行中切主机 / 掌机后输出宽 64 / 768,iOS 过热降级走的就是这条)。改成直接取低 32 位:对原版两个宽度结果相同,对任意宽度正确
|
||||
# The width that the operation-mode notification handler (0xe10d30) gives to the "window size changed" event: original code mov w9,#0x740; and x9,x25,x9 -- the compiler knew the width could only be 1280 (0x500) / 1600 (0x640),
|
||||
# and optimized "take the low 32 bits" into & (0x500|0x640). The KRES0 / KRES1 parameter slots replaced those two constants, but this derived mask was not changed along with them: 2868 & 0x740 = 768, 2296 & 0x740 = 64
|
||||
# (after switching docked / handheld while running, the output width was 64 / 768; the iOS overheating downgrade takes exactly this path). Changed to take the low 32 bits directly: same result for the original game's two widths, correct for any width
|
||||
(0xe10e48, '09e880522903098a', 'e903192a1f2003d5', '运行模式通知发窗口尺寸事件的宽度:mov w9,#0x740; and x9,x25,x9 → mov w9,w25; nop(取低 32 位,不再用原版两档宽度推出的常数掩码)', '仅宿主'),
|
||||
(0xe12e88, '09e880528902098a', 'e903142a1f2003d5', '启动初始化选分辨率(0xe12d70)同一处掩码:mov w9,#0x740; and x9,x20,x9 → mov w9,w20; nop(structck 参数门下游掩码检查查出;启动时事件接收对象通常未建,平时不显形)', '仅宿主'),
|
||||
# 产品剪口(复刻排除清单「经典画面切换」):经典画面切换 0xb15d60 的两条状态写入 → nop。
|
||||
# 画面过渡状态在 0x2dc0758 起(+4 起点、+8 目标、+0xc 进度;1.0 = 新画面);全程序写它的只有 0x852280(启动初始化写 1)、0x85cb20(强制回新画面写 1)、
|
||||
# 0x856be0(只写 +0xc)与 0xb15d60(不在局内或局版本 1 / 2 时按当前系数在 0 / 1 间翻转目标)——后者是唯一能把目标推向 0 的地方;
|
||||
# 调用方 0x36a5a0 / 0x4035e8 / 0xc25f48 / 0xc2725c 都是切换动作(视频选项 LegacyGraphicsMode、建角页 ToggleLegacy、主机版 ClassicToggle、按键 LegacyToggle 汇入此处)。
|
||||
# 剪掉的是两条普通存储、不含调用:被剪部分的同步原语与对外副作用清单为空(剪口规矩)。局内局版本 3 的提示分支(0xb15e2c 起)不动
|
||||
# Product cut (reproducing the exclusion list item "classic picture toggle"): the two state writes of the classic picture toggle 0xb15d60 → nop.
|
||||
# The picture transition state starts at 0x2dc0758 (+4 start, +8 target, +0xc progress; 1.0 = new picture); in the whole program the only writers are 0x852280 (startup init writes 1), 0x85cb20 (force back to the new picture, writes 1),
|
||||
# 0x856be0 (writes only +0xc) and 0xb15d60 (when not in a run, or when the run version is 1 / 2, flips the target between 0 / 1 according to the current coefficient) -- the last is the only place that can push the target toward 0;
|
||||
# the callers 0x36a5a0 / 0x4035e8 / 0xc25f48 / 0xc2725c are all toggle actions (the video option LegacyGraphicsMode, the character creation page's ToggleLegacy, the console version's ClassicToggle and the key LegacyToggle all converge here).
|
||||
# What is cut is two plain stores, containing no calls: the list of synchronization primitives and external side effects of the cut part is empty (the cut rule). The hint branch for run version 3 in a run (from 0xb15e2c) is untouched
|
||||
(0xb15e20, '0281002d', '1f2003d5', '经典画面切换写起点 / 目标(stp s2, s0, [x8, #4])→ nop:目标恒为 1.0(新画面)'),
|
||||
(0xb15e24, '1f0d00b9', '1f2003d5', '经典画面切换清进度(str wzr, [x8, #0xc])→ nop'),
|
||||
# 宽屏(仅宿主,配合 PARAMS 的 KASPECT 宽高比上限):界面画布宽 = min(屏宽, 4560 = 2160 × 19/9) 的上限放开到 0xffff。
|
||||
# 原版 16:9 下屏宽 3840 单位 < 4560,结果不变;iPhone 1952x900 下屏宽约 4685 单位,原先被夹到 4560、两侧各留约 26 像素
|
||||
# Widescreen (host only, together with the KASPECT aspect ratio cap in PARAMS): the cap in UI canvas width = min(screen width, 4560 = 2160 × 19/9) is opened up to 0xffff.
|
||||
# In the original game at 16:9 the screen width of 3840 units < 4560, so the result is unchanged; on iPhone 1952x900 the screen width is about 4685 units, which used to be clamped to 4560, leaving about 26 pixels on each side
|
||||
(0xb1a660, '083a8252', 'e8ff9f52', '界面画布宽上限 mov w8, #4560 → mov w8, #0xffff(画布宽 = 屏宽)', '仅宿主'),
|
||||
# (撤销:原 r13 / r15 起的「SetLanguage 0x317298 清空 + 重装字符串表」剪口 0x3172f8 / 0x3173e4(原为排除简中以外的语言而设),
|
||||
# 因英文版撤销——原版切语言要靠这次重装。)
|
||||
# 产品剪口:字符串表 A(legacy,0x2d70ff0 / 0x2d71010)的装载整段跳过。装载函数 0x7f64f0(w0 = 是否装 legacy)
|
||||
# 在 0x7f669c tbz w23 处分支:不装时成功标志置 1(0x7f6800),与 17 个 strings-legacy/*.json 全部装成功的结果相同。
|
||||
# 无读者证明:全程序引用表 A 的 128 个函数里 124 个同时读选表标志 [0x2d71098] 并按「标志 = 0 → 表 B(0x2d71030 / 0x2d71050)」选表
|
||||
# (如 0x13b7d8 csel),其余 4 个是表自身的静态构造 0x7f8f80、装载 0x7f64f0、插表 0x7f72e0、清空 0x7f5b60。标志唯一写入点 0xb1bcf4
|
||||
# 写 !obj[0xb9],obj[0xb9] 由画面过渡状态 0x2dc0758 与 1.0 比较得出——r14 已剪掉唯一能把目标推离 1.0 的经典画面切换;标志在 .bss
|
||||
# (初值 0),r15 cvd5 全程探针 0xb1bcfc 命中 0 次(写入点从未执行)⇒ 全程只读表 B。被剪树 = 17 次 0x7f72e0 单文件装载,同上方
|
||||
# 语言重装剪口的补证(同一 0xdf67f0 读事务,成对、无外部等待者)
|
||||
# (Reverted: the cuts 0x3172f8 / 0x3173e4 for "SetLanguage 0x317298 clear + reload string tables" in place since r13 / r15 (originally set up to exclude languages other than Simplified Chinese),
|
||||
# reverted because of the English version -- switching language in the original game relies on this reload.)
|
||||
# Product cut: the loading of string table A (legacy, 0x2d70ff0 / 0x2d71010) is skipped as a whole. The load function 0x7f64f0(w0 = whether to load legacy)
|
||||
# branches at the tbz w23 at 0x7f669c: when not loading, the success flag is set to 1 (0x7f6800), the same result as all 17 strings-legacy/*.json loading successfully.
|
||||
# No-reader proof: of the 128 functions in the whole program that reference table A, 124 also read the table-select flag [0x2d71098] and select the table by "flag = 0 → table B (0x2d71030 / 0x2d71050)"
|
||||
# (e.g. the csel at 0x13b7d8); the other 4 are the table's own static constructor 0x7f8f80, load 0x7f64f0, table insert 0x7f72e0 and clear 0x7f5b60. The flag's only write site 0xb1bcf4
|
||||
# writes !obj[0xb9], and obj[0xb9] is obtained by comparing the picture transition state 0x2dc0758 with 1.0 -- r14 already cut the classic picture toggle, the only thing that can push the target away from 1.0; the flag is in .bss
|
||||
# (initial value 0), and the probe at 0xb1bcfc over the whole r15 cvd5 run hit 0 times (the write site never executed) ⇒ only table B is read throughout. The cut tree = 17 single-file loads via 0x7f72e0; same as the supplementary proof of
|
||||
# the language reload cut above (the same 0xdf67f0 read transaction, paired, no external waiters)
|
||||
(0x7f669c, '370b0036', '59000014', '字符串表装载 tbz w23, #0(是否装 legacy 表 A)→ b 0x7f6800:表 A 无读者(选表标志恒 0 → 表 B),整段 17 个 legacy 文件不装'),
|
||||
# Granny 段解码(BitKnit2)两条流式段读取路径的逐块解码调用点:宿主缺省原样转调 0x11f4af0(预解码方案 A 的替换落点,hle_granny.c)
|
||||
# The per-block decode call sites of the two streaming segment read paths of Granny segment decoding (BitKnit2): by default the host forwards as is to 0x11f4af0 (the replacement hook point of pre-decode plan A, hle_granny.c)
|
||||
(0x11f02dc, '05120094', '611000d4', '段读取 0x11f0110 逐块解码 bl 0x11f4af0(ctx, 块, 长度) → svc #0x83:宿主缺省以原参数原样调用并回填 w0(hle.h SVC_HOST_GRANNY_A)', '仅宿主'),
|
||||
# 掉落光(仅宿主):物品取外观定义路径 bl 0xa14dc4(资源管理器, 单位, x8 输出字符串) → svc #0x87:宿主原样代调,
|
||||
# 对模式 3 / 5(地上 / 掉落中)的物品按规则把路径改指覆盖层里的带光变体(dm_dropfilter.c svc_ground_asset;hle.h SVC_HOST_GROUND_ASSET)
|
||||
# 一档掉落音(仅宿主):落地取掉落音 bl 0x470c20(物品, &触发帧) → svc #0x88:宿主原样代调,一档物品换成提示音(dm_dropfilter.c svc_drop_sound)
|
||||
# Drop light (host only): the item's appearance definition path lookup bl 0xa14dc4(resource manager, unit, x8 output string) → svc #0x87: the host forwards the call as is,
|
||||
# and for items in mode 3 / 5 (on the ground / dropping) repoints the path by rule to the lit variant in the overlay (dm_dropfilter.c svc_ground_asset; hle.h SVC_HOST_GROUND_ASSET)
|
||||
# Tier-one drop sound (host only): fetching the drop sound on landing bl 0x470c20(item, &trigger frame) → svc #0x88: the host forwards the call as is, and tier-one items get a notification sound instead (dm_dropfilter.c svc_drop_sound)
|
||||
(0x468f2c, '3d1f0094', '011100d4', '物品落地取掉落音调用点 bl 0x470c20 → svc #0x88:宿主原样代调后按规则把一档物品的掉落音换成提示音(其余原样)', '仅宿主'),
|
||||
(0x8fa590, '0d6a0494', 'e11000d4', '物品外观路径调用点 bl 0xa14dc4 → svc #0x87:宿主原样代调后按规则改指地上物品的带光变体(存储 / 穿戴 / 腰带 / 镶嵌不碰)', '仅宿主'),
|
||||
# 进局出生点(进局落在城镇小站旁、尸体与人同处;仅宿主):玩家进局函数 0x5d7f70 里给玩家、给尸体各取一次出生点,都是 bl 0x5596c0(数据版本, 幕, 关卡, 格类型 0, &x, &y, 单位尺寸)
|
||||
# → svc #0x8a(玩家)/ #0x8b(尸体):宿主原样代调;进局在城镇时改按「小站格 13 + 固定安全距离」取点,人、尸体、佣兵由原版一次放好(不再第 2 拍换关挪人,尸体不再留在原出生点)(dm_townwp.c svc_join_spawn)
|
||||
# Run-entry spawn point (entering a run lands next to the town waypoint, with the corpse in the same place as the player; host only): the player join function 0x5d7f70 fetches a spawn point once for the player and once for the corpse, both via bl 0x5596c0(data version, act, level, cell type 0, &x, &y, unit size)
|
||||
# → svc #0x8a (player) / #0x8b (corpse): the host forwards the call as is; when the run is entered in town it instead picks the point by "waypoint cell 13 + a fixed safe distance", and the player, corpse and mercenary are placed in one go by the original game (the player is no longer moved by a level change on tick 2, and the corpse no longer stays at the original spawn point) (dm_townwp.c svc_join_spawn)
|
||||
(0x5d8040, 'a005fe97', '411100d4', '玩家进局取出生点调用点 bl 0x5596c0 → svc #0x8a:宿主原样代调,进局在城镇时出生点换成小站旁(hle.h SVC_HOST_JOIN_SPAWN)', '仅宿主'),
|
||||
(0x5d8400, 'b004fe97', '611100d4', '进局给尸体取落点调用点 bl 0x5596c0 → svc #0x8b:同上,尸体与人取同一个点(hle.h SVC_HOST_JOIN_CORPSE)', '仅宿主'),
|
||||
(0x11f0914, '77100094', '811000d4', '段读取 0x11f07d0 逐块解码 bl 0x11f4af0(ctx, 块, 长度) → svc #0x84:同上(hle.h SVC_HOST_GRANNY_B)', '仅宿主'),
|
||||
]}
|
||||
# ---- 已登记观测门:{NSO 构建号: [(偏移, 编号, 原指令字, 理由)]}。编号与宿主 hle.h 的 OBS_* 一致;
|
||||
# 原指令须与位置无关(不得 PC 相对 / 分支 / 涉 x18·tpidr),离线断言;宿主未挂回调时门块进出一次即返回 ----
|
||||
# ---- Registered observation gates: {NSO build ID: [(offset, number, original instruction word, reason)]}. Numbers match OBS_* in the host's hle.h;
|
||||
# the original instruction must be position independent (no PC-relative / branch / anything involving x18 or tpidr), asserted offline; when the host has no callback attached the gate block goes in and out once and returns ----
|
||||
OBS = {'db0507f36b84200ac05f75d76ed5026f': [
|
||||
(0xb1dc60, 1, 'd10603ff', 'UI 消息总线虚函数实现入口(x1 = 消息 {u64 类型哈希, u64 动作哈希, char* 面板名, …}):'
|
||||
'DM_UIMSG 消息流与 DM_BOOTPROF 启动分段的唯一来源;原指令 sub sp, sp, #0x180'),
|
||||
(0x5d3bc0, 2, 'd10503ff', '服务端拍入口(x0 = 游戏对象 G):DM_TICKS 逐拍 6 格状态哈希(dm/verify/tick_state_format.md,与真值 swtick.py 同一采集点);'
|
||||
'原指令 sub sp, sp, #0x140'),
|
||||
(0x6e5b40, 3, 'd10103ff', '客户端命令分派入口 (G, 单位, 包, 长度):DM_C2S_LOG 命令包序列(dm/verify/command_packet_format.md,与真值同一采集点);'
|
||||
'原指令 sub sp, sp, #0x40'),
|
||||
(0x6310b0, 4, 'a9bb67fc', '系统类客户端消息处理入口 (buf = u32 客户端号 + 包, 包长):包号 ≥ 0x67(加入 / 心跳 0x6d / 0x6f 等),收包泵先抽干此队列;'
|
||||
'DM_C2S_LOG 记为 "q":"sys";原指令 stp x28, x25, [sp, #-0x50]!'),
|
||||
(0x317298, 5, 'd10183ff', 'SetLanguage 入口(x1 → u32 新语言号,语言名表 main+0x20ae478):配合上方语言重载剪口,宿主断言新语言为 zhCN;'
|
||||
'原指令 sub sp, sp, #0x60'),
|
||||
]}
|
||||
BUILD_ID = d[0x40:0x50].hex()
|
||||
# 构建期产品规则:旧原资源/对拍域默认不变;触屏版单独出新版本,不在运行时写客体代码。
|
||||
# Build-time product rules: the old original-resource / comparison domain is unchanged by default; the touchscreen version is issued separately as a new version, and guest code is not written at runtime.
|
||||
RULESET = os.environ.get('DM_RULESET', 'native')
|
||||
assert RULESET in ('native', 'touch-run-v4'), f'未知规则域 {RULESET}'
|
||||
RULE_BUILD = 'db0507f36b84200ac05f75d76ed5026f'
|
||||
RULE_RUN = RULESET == 'touch-run-v4' and NAME == 'main'
|
||||
if RULE_RUN:
|
||||
import hashlib
|
||||
assert BUILD_ID == RULE_BUILD, f'Run规则构建号不符 {BUILD_ID}'
|
||||
RULE_ORIG_SHA = hashlib.sha256(IMG).hexdigest()
|
||||
cuts = list(CUTS.get(BUILD_ID, []))
|
||||
# 触屏版规则域默认同时带宿主私有门;规则闸门可显式关闭,保留同一出包入口和规则域。
|
||||
# The touchscreen rule domain by default also carries the host-private gates; the rule gate check can turn them off explicitly, keeping the same packaging entry point and rule domain.
|
||||
PRIVATE_GATES = os.environ.get("DM_PRIVATE_GATES", "1") != "0"
|
||||
PRIVATE_AIM = RULE_RUN and PRIVATE_GATES
|
||||
if PRIVATE_AIM:
|
||||
cuts.append((0x2faf04, 'fde7fe97', 'c11000d4',
|
||||
'skill-aim-v1-private: skill ground direction call only; svc86 delegates original2b4ef8 then sampled-right/original rotation+grid; zero/nonplayer/non-skill retain original; busy/town/skill/server untouched', '仅宿主'))
|
||||
if RULE_RUN:
|
||||
# 方向光阴影图边长(画质档位 1,0x168a520 填 +0x48 → 建 2 层数组 0x1697394):2100 → 1024。授权「视觉无差别即可」;
|
||||
# mini 108 张 + 连续 16 帧:营地 / 野外 / 战斗各档到 1024 的 FLIP 与同设置重跑的噪声分不开、影子区相邻帧变化量 0.71 → 0.75;真机两张阴影合计约 0.7–1.4 ms / 帧。
|
||||
# 游戏传给着色器的阴影尺寸常量与视口随同一配置值变(转储核过)。native 规则域(Mac 对原版真值的闸门)保持 2100
|
||||
# Directional light shadow map edge length (quality level 1, 0x168a520 fills +0x48 → creates the 2-layer array 0x1697394): 2100 → 1024. Authorization: "visually indistinguishable is enough";
|
||||
# on the second Mac, 108 images + 16 consecutive frames: for camp / wilderness / combat, at every level down to 1024 the FLIP cannot be told apart from the noise of a rerun with the same settings, and the change between adjacent frames in shadow regions is 0.71 → 0.75; on a real device the two shadow maps total about 0.7–1.4 ms / frame.
|
||||
# The shadow size constants and the viewport that the game passes to the shader change with the same config value (verified by dump). The native rule domain (the Mac gate check against the original game's ground truth) stays at 2100
|
||||
SHADOW_SIDE = 1024
|
||||
movz_w14 = lambda n: struct.pack('<I', 0x52800000 | (n << 5) | 14).hex() # movz w14,#n——字节由表达式算,不手写(手算成 #32768,阴影图 32768² 分配失败启动即崩) | movz w14,#n -- the bytes are computed by an expression, not written by hand (a hand calculation came out as #32768, and the shadow map allocation of 32768² failed, crashing at startup)
|
||||
cuts.append((0x168a580, movz_w14(2100), movz_w14(SHADOW_SIDE), f'阴影图边长 mov w14,#2100 → mov w14,#{SHADOW_SIDE}(档位 1)', '仅宿主'))
|
||||
if RULE_RUN:
|
||||
# 纯提示的系统通知不吞功能键:手柄版通知面板处理函数 0x3d84a0 遇「动作 9(PLUS)按下」就执行通知带的确认动作并吞键(给「升级通知按 PLUS 直达技能树」用)。
|
||||
# 系统通知(事件队列第 12 类,0xab5c08;如改难度后的「游戏难度设为 N…」)带的确认动作只是关掉自己,结果是通知停留的 10 秒里第一下红十字没反应(真机 + Mac 复现)。
|
||||
# 改法:系统通知不带确认动作(类别哈希存 0);没有确认动作的通知不处理 PLUS(走原函数的「转给子控件」出口 0x3d880c),到 notificationSeconds 自己关。带确认动作的通知不变
|
||||
# Purely informational system notifications do not swallow the function key: the controller version's notification panel handler 0x3d84a0, on "action 9 (PLUS) pressed", executes the confirm action carried by the notification and swallows the key (meant for "press PLUS on a level-up notification to go straight to the skill tree").
|
||||
# The confirm action carried by a system notification (event queue class 12, 0xab5c08; e.g. 「游戏难度设为 N…」(game difficulty set to N...) after changing the difficulty) only closes itself, and the result is that during the 10 seconds the notification stays up the first press of the red cross does nothing (reproduced on a real device + Mac).
|
||||
# Fix: system notifications carry no confirm action (the category hash is stored as 0); notifications without a confirm action do not handle PLUS (they take the original function's "forward to child widgets" exit 0x3d880c) and close by themselves at notificationSeconds. Notifications with a confirm action are unchanged
|
||||
cbz_x8 = lambda at, to: struct.pack('<I', 0xB4000008 | (((to - at) >> 2) & 0x7ffff) << 5).hex()
|
||||
str_x19_178 = lambda rt: struct.pack('<I', 0xF9000000 | (0x178 // 8) << 10 | 19 << 5 | rt).hex()
|
||||
cuts.append((0xab5c28, str_x19_178(8), str_x19_178(31), '系统通知的确认动作类别 str x8,[x19,#0x178] → str xzr(不带确认动作)', '仅宿主'))
|
||||
cuts.append((0x3d853c, cbz_x8(0x3d853c, 0x3d8560), cbz_x8(0x3d853c, 0x3d880c), '通知面板:确认动作类别为空 → 不处理 PLUS', '仅宿主'))
|
||||
cuts.append((0x3d8544, cbz_x8(0x3d8544, 0x3d8560), cbz_x8(0x3d8544, 0x3d880c), '通知面板:确认动作哈希为空 → 不处理 PLUS', '仅宿主'))
|
||||
if RULE_RUN:
|
||||
# 技能说明框出在技能树侧边、不盖树:技能树面板每帧更新(0xc356b0)在 0xc35fd4 调说明框入口 0xb16660,位置参数 x1 = 图标绝对坐标(低 32 位 x、高 32 位 y + 3),
|
||||
# 手柄版说明框贴着图标右下展开,触屏上正好盖住手指周围的几个技能。0xc35fb0 的 bfxil x1,x8,#0,#32 是把 x1 的低半拷回 x1 的空操作(x8 = x1),
|
||||
# 换成 movk x1,#3000:横坐标给到屏幕外,由说明框入口自己的回夹(0xb0d560,按 TooltipsPanel 的 screenEdgePadding)贴到右安全区边;纵坐标不动
|
||||
# The skill tooltip appears beside the skill tree and does not cover the tree: the skill tree panel's per-frame update (0xc356b0) calls the tooltip entry 0xb16660 at 0xc35fd4, with position argument x1 = the icon's absolute coordinates (low 32 bits x, high 32 bits y + 3);
|
||||
# the controller version's tooltip expands against the icon's lower right, which on a touchscreen covers exactly the few skills around the finger. The bfxil x1,x8,#0,#32 at 0xc35fb0 is a no-op that copies the low half of x1 back into x1 (x8 = x1),
|
||||
# and is replaced with movk x1,#3000: the x coordinate is put off screen, and the tooltip entry's own clamp-back (0xb0d560, by TooltipsPanel's screenEdgePadding) snaps it to the right safe-area edge; the y coordinate is untouched
|
||||
cuts.append((0xc35fb0, struct.pack('<I', 0xB3407D01).hex(), struct.pack('<I', 0xF2800000 | 3000 << 5 | 1).hex(), '技能说明框横坐标给到屏幕外,由原回夹贴右边(不盖技能树)', '仅宿主'))
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
# 只登记精力资格/移动选择/走跑偏好;不改方向、真实幅度、合法mode与零轴分支。
|
||||
# 两个成本/选择器通用点的type0防护在下方原生小跳板,非player保原行为。
|
||||
# Only stamina eligibility / movement selection / walk-run preference are registered; direction, real magnitude, legal mode and the zero-axis branch are not changed.
|
||||
# The type0 guard for the two generic cost / selector points is in the small native trampoline below; non-player keeps the original behavior.
|
||||
run_words = [
|
||||
(0x2c620c, 0xb90e511f, 0x52800029, '偏好初始化:mov w9,1(x8仍为2d20000)'),
|
||||
(0x2c6210, 0xd00152c8, 0xb90e5109, '偏好初始化:str w9,[x8,e50];替代同页重复adrp,保原x8'),
|
||||
(0x369a90, 0xd100c3ff, None, '客户端RunOff入口尾跳原RunOn;保其player0/合法mode/环境门'),
|
||||
(0x369980, 0x340006a0, 0xd503201f, '客户端RunOn仅取消既有player0门之后的零精力拒绝'),
|
||||
(0x2b2c74, 0x340000a0, 0xd503201f, '控制器d29资格仅取消stat10零值限制;幅度比较与停杆保原'),
|
||||
(0x2b2dc0, 0x3900031f, 0xd503201f, '控制器d29仅取消stat10零值清除;幅度归一化保原'),
|
||||
(0x2b30fc, 0x0a090101, 0x52800021, '已通过合法动作/零轴门的移动编码选择位固定Run;幅度不改'),
|
||||
(0x2b3104, 0x2a1f03e1, 0x52800021, '无用户走跑偏好时亦固定Run编码位;方向/幅度不改'),
|
||||
(0x6dc2c4, 0x1a880502, 0x52800062, 'server42合法移动请求固定Run3,原type0/死亡/锁定/幅度/方向门保留'),
|
||||
(0x6dce90, 0x340000e0, 0xd503201f, 'server49仅取消既有player0/mode2门之后的零精力拒绝'),
|
||||
(0x6dcec0, 0xa9bf7bfd, None, 'server4A入口尾跳原49;长度/type0/mode门保留'),
|
||||
]
|
||||
for off, old, new, why in run_words:
|
||||
if new is None:
|
||||
target = 0x369900 if off == 0x369a90 else 0x6dce50
|
||||
new = 0x14000000 | (((target - off) >> 2) & 0x3ffffff)
|
||||
cuts.append((off, struct.pack('<I', old).hex(), struct.pack('<I', new).hex(), 'touch-run-v4:' + why))
|
||||
cuts = [c if len(c) == 5 else (*c, '全') for c in cuts] # 第 5 项作用域:全 | 仅宿主(仅宿主 = 真值模拟器不应用) | 5th item is the scope: 全 (all) | 仅宿主 (host only) (仅宿主 = not applied by the ground-truth emulator)
|
||||
for off, ob, nb, why, scope in cuts:
|
||||
ob, nb = bytes.fromhex(ob), bytes.fromhex(nb)
|
||||
assert len(ob) == len(nb) and IMG[off:off + len(ob)] == ob, f'剪口原字节不符 {off:#x}:{bytes(IMG[off:off + len(ob)]).hex()}'
|
||||
IMG[off:off + len(nb)] = nb
|
||||
# 键页下标固定;键页内容由装载器写入“实际键号 × 8”。
|
||||
# Key page indices are fixed; the key page content is written by the loader as "actual key number × 8".
|
||||
KEYS = {'K18': 508, 'KTLS': 509, 'KTLR': 510, 'KGATE': 511, 'KRES0': 506, 'KRES1': 507, 'KASPECT': 505, 'KASPECTUI': 504} # KRES*:分辨率参数位;KASPECT:画面宽高比上限(见 PARAMS) | KRES*: resolution parameter slots; KASPECT: picture aspect ratio cap (see PARAMS)
|
||||
KEY_INDEX = {k: i for i, k in enumerate(('K18', 'KTLS', 'KTLR', 'KGATE', 'KRES0', 'KRES1', 'KASPECT', 'KASPECTUI'))}
|
||||
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); md.detail = True
|
||||
patch = bytearray(); fix = []; gates = []; stats = {}
|
||||
def stat(k): stats[k] = stats.get(k, 0) + 1
|
||||
def here(): return PATCH_OFF + len(patch)
|
||||
def emit(w, kind=None):
|
||||
if kind: fix.append((len(patch), kind))
|
||||
patch.extend(struct.pack('<I', w & 0xFFFFFFFF))
|
||||
|
||||
def emit_key_addr(reg, kind):
|
||||
fix.append((len(patch), kind)); emit(ADRP(reg, here(), KEY_PAGE_OFF)); emit(LDRX(reg, reg, KEY_INDEX[kind]))
|
||||
|
||||
def emit_slot_addr(base, key_reg, kind):
|
||||
emit_key_addr(key_reg, kind); emit(ADDR(base, base, key_reg))
|
||||
|
||||
# ---- 编码器 ----
|
||||
# ---- Encoders ----
|
||||
def B(frm, to):
|
||||
off = to - frm; assert -(1 << 27) <= off < (1 << 27) and off % 4 == 0
|
||||
return 0x14000000 | ((off >> 2) & 0x3FFFFFF)
|
||||
def STP(t, t2, n, off): return 0xA9000000 | (((off // 8) & 0x7F) << 15) | (t2 << 10) | (n << 5) | t
|
||||
def LDP(t, t2, n, off): return 0xA9400000 | (((off // 8) & 0x7F) << 15) | (t2 << 10) | (n << 5) | t
|
||||
def STP_PRE(t, t2, n, off): return 0xA9800000 | (((off // 8) & 0x7F) << 15) | (t2 << 10) | (n << 5) | t
|
||||
def LDP_POST(t, t2, n, off): return 0xA8C00000 | (((off // 8) & 0x7F) << 15) | (t2 << 10) | (n << 5) | t
|
||||
def STUR(t, n, off): return 0xF8000000 | ((off & 0x1FF) << 12) | (n << 5) | t # stur xt,[xn,#off](off 可负) | stur xt,[xn,#off] (off may be negative)
|
||||
def LDUR(t, n, off): return 0xF8400000 | ((off & 0x1FF) << 12) | (n << 5) | t # ldur xt,[xn,#off]
|
||||
def LDRX(t, n, imm12=0): return 0xF9400000 | (imm12 << 10) | (n << 5) | t
|
||||
def STRX(t, n, imm12=0): return 0xF9000000 | (imm12 << 10) | (n << 5) | t
|
||||
def MRS_TPIDRRO(t): return 0xD53BD060 | t
|
||||
def ADRP(dd, pc, target):
|
||||
imm = ((target & ~0xFFF) - (pc & ~0xFFF)) >> 12; assert -(1 << 20) <= imm < (1 << 20)
|
||||
return 0x90000000 | ((imm & 3) << 29) | (((imm >> 2) & 0x7FFFF) << 5) | dd
|
||||
def ADDI(dd, n, imm12, sh=0): return 0x91000000 | (sh << 22) | (imm12 << 10) | (n << 5) | dd
|
||||
def ADDR(dd, n, m): return 0x8B000000 | (m << 16) | (n << 5) | dd
|
||||
def SUBI(dd, n, imm12, sh=0): return 0xD1000000 | (sh << 22) | (imm12 << 10) | (n << 5) | dd
|
||||
def BR(n): return 0xD61F0000 | (n << 5)
|
||||
def BLR(n): return 0xD63F0000 | (n << 5)
|
||||
NOP = 0xD503201F
|
||||
|
||||
def dis(w, addr):
|
||||
l = list(md.disasm(struct.pack('<I', w), addr)); assert len(l) == 1, hex(w)
|
||||
return l[0]
|
||||
def regset(ins):
|
||||
r, w = ins.regs_access()
|
||||
return {ins.reg_name(x) for x in r}, {ins.reg_name(x) for x in w}
|
||||
def num(name):
|
||||
m = re.fullmatch(r'[xw](\d+)', name or ''); return int(m.group(1)) if m else None
|
||||
def has18(ins): return re.search(r'\b[xw]18\b', ins.op_str) is not None
|
||||
def regs_in(ins):
|
||||
s = {int(n) for n in re.findall(r'\b[xw](\d+)\b', ins.op_str)}
|
||||
try:
|
||||
rd, wr = regset(ins); s |= {num(n) for n in rd | wr} - {None}
|
||||
except Exception: pass
|
||||
return s
|
||||
def pick(avoid, n=2):
|
||||
out = [r for r in range(0, 16) if r not in avoid and r != 18][:n]; assert len(out) == n; return out
|
||||
|
||||
def subst(ins, S):
|
||||
"""x18/w18 → xS/wS:只改 4 个寄存器字段位置,用反汇编文本核对。 | x18/w18 → xS/wS: only the 4 register field positions are changed, verified against the disassembly text."""
|
||||
w = struct.unpack('<I', ins.bytes)[0]
|
||||
want = re.sub(r'\b([xw])18\b', lambda m: f'{m.group(1)}{S}', ins.op_str)
|
||||
pos = [p for p in (0, 5, 10, 16) if (w >> p) & 31 == 18]
|
||||
for k in range(len(pos), 0, -1):
|
||||
for c in combinations(pos, k):
|
||||
nw = w
|
||||
for p in c: nw = (nw & ~(31 << p)) | (S << p)
|
||||
try: dd = dis(nw, ins.address)
|
||||
except AssertionError: continue
|
||||
if dd.mnemonic == ins.mnemonic and dd.op_str == want: return nw
|
||||
raise RuntimeError(f'subst fail {ins.address:x} {ins.mnemonic} {ins.op_str}')
|
||||
|
||||
# ---- 各类改写块 ----
|
||||
# ---- Rewrite blocks of each kind ----
|
||||
def sp_delta(ins):
|
||||
"""指令对 sp 的写回量(前变址 [sp, #i]! / 后变址 [sp], #i);不写回 sp 返回 0。 | The amount an instruction writes back to sp (pre-index [sp, #i]! / post-index [sp], #i); returns 0 if sp is not written back."""
|
||||
m = re.search(r'\[sp, #(-?(?:0x)?[0-9a-f]+)\]!', ins.op_str)
|
||||
if m: return int(m.group(1), 0)
|
||||
m = re.search(r'\[sp\], #(-?(?:0x)?[0-9a-f]+)$', ins.op_str)
|
||||
if m: return int(m.group(1), 0)
|
||||
assert not re.match(r'(sp|wsp),', ins.op_str), f'writes sp: {ins.address:x} {ins.op_str}'
|
||||
return 0
|
||||
|
||||
def site_plain(ins):
|
||||
S, T = pick(regs_in(ins))
|
||||
dlt = sp_delta(ins)
|
||||
save = -16 if dlt == 0 else -112 # 改 sp 的指令会写到 sp 下方,暂存放到保留区深处 | Instructions that modify sp write below sp, so the scratch save is placed deep in the reserved area
|
||||
assert dlt == 0 or dlt >= -96, f'sp delta {dlt} at {ins.address:x}'
|
||||
start = here()
|
||||
emit(STP(S, T, 31, save)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
|
||||
emit(subst(ins, S))
|
||||
emit(STRX(S, T)) # 一律写回:capstone 会漏报写入(adds w18 实例) | Always write back: capstone can miss reporting a write (the adds w18 instance)
|
||||
emit(LDP(S, T, 31, save - dlt)); emit(B(here(), ins.address + 4))
|
||||
return start
|
||||
|
||||
def site_cond(ins):
|
||||
w = struct.unpack('<I', ins.bytes)[0]
|
||||
S, T = pick(regs_in(ins))
|
||||
tgt = ins.operands[-1].imm
|
||||
start = here()
|
||||
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
|
||||
m = ins.mnemonic
|
||||
taken = here() + 4 * 3
|
||||
off = (taken - here()) >> 2
|
||||
nw = ((w & 0xFF000000) | ((off & 0x7FFFF) << 5) | S) if m in ('cbz', 'cbnz') else ((w & 0xFFF80000) | ((off & 0x3FFF) << 5) | S)
|
||||
pc = here(); emit(nw)
|
||||
dd = dis(nw, pc); assert dd.mnemonic == m and dd.operands[-1].imm == taken
|
||||
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
|
||||
assert here() == taken
|
||||
emit(LDP(S, T, 31, -16)); emit(B(here(), tgt))
|
||||
return start
|
||||
|
||||
def site_pcrel(ins):
|
||||
tgt = ins.operands[1].imm
|
||||
S, T = pick(set())
|
||||
start = here()
|
||||
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18') # S 先作键页偏移暂存,下一条再装目标值 | S first serves as a temporary for the key page offset; the next instruction then loads the target value
|
||||
pc = here(); emit(ADRP(S, pc, tgt))
|
||||
if ins.mnemonic == 'adr': emit(ADDI(S, S, tgt & 0xFFF))
|
||||
emit(STRX(S, T))
|
||||
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
|
||||
return start
|
||||
|
||||
def site_br(ins, base, count):
|
||||
"""跳转表 br x18:目标 = base + 4i。x16 暂存红区 → 等距落地垫 → 恢复 x16 → 原目标。 | Jump table br x18: target = base + 4i. Stash x16 in the red zone → equally spaced landing pads → restore x16 → original target."""
|
||||
start = here()
|
||||
emit(STUR(16, 31, -16)); emit(STUR(17, 31, -24)) # x16 / x17 是函数内可存活的临时寄存器,借用前存红区 | x16 / x17 are temporary registers that can stay live within a function; save them to the red zone before borrowing
|
||||
emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(LDUR(17, 31, -24))
|
||||
padbase = start + 4 * 24
|
||||
delta = padbase - base
|
||||
op = ADDI if delta >= 0 else SUBI; dl = abs(delta)
|
||||
ops = []; hi, lo = dl >> 12, dl & 0xFFF
|
||||
while hi: h = min(hi, 0xFFF); ops.append(op(16, 16, h, 1)); hi -= h
|
||||
if lo: ops.append(op(16, 16, lo, 0))
|
||||
assert len(ops) <= 12
|
||||
for o in ops: emit(o)
|
||||
emit(BR(16))
|
||||
while here() < padbase: emit(NOP)
|
||||
tails = padbase + 4 * count
|
||||
for i in range(count): emit(B(here(), tails + 8 * i))
|
||||
for i in range(count):
|
||||
emit(0xF85F0000 | (31 << 5) | 16) # ldur x16,[sp,#-16]
|
||||
emit(B(here(), base + 4 * i))
|
||||
return start
|
||||
|
||||
def site_sysreg_read(ins, kind):
|
||||
"""mrs xN, tpidr_el0 / tpidrro_el0 → xN = 线程槽值。 | mrs xN, tpidr_el0 / tpidrro_el0 → xN = thread slot value."""
|
||||
N = ins.bytes[0] & 31
|
||||
tmp = 16 if N != 16 else 17
|
||||
start = here()
|
||||
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(N)); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp 存红区借用 | tmp is saved by borrowing the red zone
|
||||
emit(B(here(), ins.address + 4))
|
||||
return start
|
||||
|
||||
def site_tpidr_write(ins):
|
||||
N = struct.unpack('<I', ins.bytes)[0] & 31
|
||||
(T,) = pick({N}, 1)
|
||||
start = here()
|
||||
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
|
||||
tmp = next(x for x in (16, 17) if x not in (N, T))
|
||||
emit(STUR(tmp, 31, -24)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDUR(tmp, 31, -24))
|
||||
emit(0xF85F0000 | (31 << 5) | T) # ldur xT,[sp,#-16]
|
||||
emit(B(here(), ins.address + 4))
|
||||
return start
|
||||
|
||||
def emit_gate_call():
|
||||
"""门块公共段(紧跟 stp x29,x30,[sp,#-16]! 之后、blr x30 之前):x30 = 线程槽 KGATE 的门地址。
|
||||
键页取槽要借第二个寄存器,借 x29 后立即从栈上恢复:_dm_gate 存下的 x29 必须是客体原值——
|
||||
宿主按 [x29+8] 认调用者(技能绑定观测门 6、私有瞄准门 svc86)、崩溃回溯也走 x29 链
|
||||
(r24 方案 C 起借了不还,宿主拿到的 x29 是键页里的槽偏移,技能图标退回占位字)。
|
||||
Common section of a gate block (right after stp x29,x30,[sp,#-16]! and before blr x30): x30 = the gate address in thread slot KGATE.
|
||||
Fetching the slot through the key page needs a second register to be borrowed; x29 is borrowed and then immediately restored from the stack: the x29 saved by _dm_gate must be the guest's original value --
|
||||
the host identifies the caller by [x29+8] (skill binding observation gate 6, private aiming gate svc86), and the crash backtrace also walks the x29 chain
|
||||
(since r24 plan C it was borrowed and not returned, the x29 the host got was the slot offset from the key page, and skill icons fell back to placeholder text)."""
|
||||
emit(MRS_TPIDRRO(30)); emit_slot_addr(30, 29, 'KGATE'); emit(LDRX(30, 30)); emit(LDRX(29, 31))
|
||||
|
||||
def site_gate(ins, kind, arg):
|
||||
"""svc / mrs cntpct_el0 → 宿主门。门地址取自线程槽 KGATE;门按返回点(本块 ldp 的地址)查 gates.tsv。 | svc / mrs cntpct_el0 → host gate. The gate address is taken from thread slot KGATE; the gate looks up gates.tsv by return point (the address of this block's ldp)."""
|
||||
start = here()
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call()
|
||||
emit(BLR(30))
|
||||
ret = here()
|
||||
emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(B(here(), ins.address + 4))
|
||||
gates.append((ret, kind, arg, ins.address))
|
||||
return start
|
||||
|
||||
def site_obs(off, oid, word):
|
||||
"""观测门:入口原指令 → 进宿主门(arg = 观测编号)→ 恢复 x29/x30 → 执行原指令 → 跳回 off+4。
|
||||
门块前半与 site_gate 逐字同构;宿主只读寄存器、不改(dm_gate 回写的 x0–x8 即原值)。
|
||||
Observation gate: original entry instruction → enter the host gate (arg = observation number) → restore x29/x30 → execute the original instruction → jump back to off+4.
|
||||
The first half of the gate block is word-for-word isomorphic with site_gate; the host only reads registers and does not modify them (the x0–x8 written back by dm_gate are the original values)."""
|
||||
ins = dis(word, off)
|
||||
assert ins.mnemonic not in ('adr', 'adrp', 'b', 'bl', 'br', 'blr', 'ret', 'cbz', 'cbnz', 'tbz', 'tbnz') and not ins.mnemonic.startswith('b.') \
|
||||
and not (ins.mnemonic.startswith('ldr') and '[' not in ins.op_str) and not has18(ins), f'观测门原指令不可搬 {off:#x} {ins.mnemonic} {ins.op_str}'
|
||||
start = here()
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call()
|
||||
emit(BLR(30))
|
||||
ret = here()
|
||||
emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(word)
|
||||
emit(B(here(), off + 4))
|
||||
gates.append((ret, 'obs', oid, off))
|
||||
return start
|
||||
|
||||
# ---- 独占窗口 ----
|
||||
# ---- Exclusive windows ----
|
||||
EXCL_LD = ('ldxr', 'ldaxr', 'ldxp', 'ldaxp', 'ldxrb', 'ldaxrb', 'ldxrh', 'ldaxrh')
|
||||
EXCL_ST = ('stxr', 'stlxr', 'stxp', 'stlxp', 'stxrb', 'stlxrb', 'stxrh', 'stlxrh')
|
||||
def find_windows(insl):
|
||||
out = []
|
||||
for i, ins in enumerate(insl):
|
||||
if ins.mnemonic not in EXCL_LD: continue
|
||||
j = i
|
||||
while j < len(insl) and insl[j].mnemonic not in EXCL_ST: j += 1
|
||||
if j >= len(insl) or j - i >= 16: continue
|
||||
if j + 1 < len(insl) and insl[j + 1].mnemonic in ('cbz', 'cbnz'): j += 1
|
||||
seg = insl[i:j + 1]
|
||||
if any(has18(x) for x in seg): out.append(seg)
|
||||
return out
|
||||
|
||||
def site_window(seg):
|
||||
used = set()
|
||||
for x in seg: used |= regs_in(x)
|
||||
S, T = pick(used)
|
||||
lo, hi = seg[0].address, seg[-1].address + 4
|
||||
start = here()
|
||||
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
|
||||
copy0 = here(); n = len(seg)
|
||||
exits = copy0 + 4 * n
|
||||
ex_targets = []; words = []
|
||||
for k, x in enumerate(seg):
|
||||
w = struct.unpack('<I', x.bytes)[0]
|
||||
if has18(x): w = subst(x, S)
|
||||
m = x.mnemonic
|
||||
if m in ('cbz', 'cbnz', 'tbz', 'tbnz') or m.startswith('b.'):
|
||||
tgt = x.operands[-1].imm
|
||||
if lo <= tgt < hi: newt = copy0 + (tgt - lo)
|
||||
else: ex_targets.append(tgt); newt = exits + 16 * (len(ex_targets) - 1)
|
||||
pc = copy0 + 4 * k; off = (newt - pc) >> 2
|
||||
if m in ('tbz', 'tbnz'): w = (w & 0xFFF8001F) | ((off & 0x3FFF) << 5)
|
||||
else: w = (w & 0xFF00001F) | ((off & 0x7FFFF) << 5)
|
||||
dd = dis(w, pc); assert dd.operands[-1].imm == newt and dd.mnemonic == m
|
||||
else:
|
||||
assert m not in ('adr', 'adrp', 'b', 'bl', 'br', 'blr', 'ret') and not (m == 'ldr' and '[' not in x.op_str), hex(x.address)
|
||||
words.append(w)
|
||||
for w in words: emit(w)
|
||||
ex_targets.append(hi)
|
||||
for t in ex_targets:
|
||||
emit(STRX(S, T)); emit(LDP(S, T, 31, -16)); emit(B(here(), t)); emit(NOP)
|
||||
return start, lo, hi
|
||||
|
||||
# ---- 函数边界(eh_frame_hdr)----
|
||||
# ---- Function boundaries (eh_frame_hdr) ----
|
||||
m0 = struct.unpack_from('<I', IMG, 4)[0]
|
||||
assert IMG[m0:m0 + 4] == b'MOD0'
|
||||
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)
|
||||
starts = sorted(x for x in starts if x < TEXT_END)
|
||||
|
||||
# ---- 线性扫描找全部改写点(不靠寄存器读写报告)----
|
||||
# ---- Linear scan to find all rewrite points (not relying on register read/write reports) ----
|
||||
kinds = {}
|
||||
for o in range(0, TEXT_END, 4):
|
||||
w = struct.unpack_from('<I', IMG, o)[0]
|
||||
if w & 0xFFE0001F == 0xD4000001: kinds[o] = ('svc', (w >> 5) & 0xFFFF); continue
|
||||
if w & 0xFFFFFFE0 == 0xD53BD040: kinds[o] = ('tpidr_r', None); continue
|
||||
if w & 0xFFFFFFE0 == 0xD51BD040: kinds[o] = ('tpidr_w', None); continue
|
||||
if w & 0xFFFFFFE0 == 0xD53BD060: kinds[o] = ('tpidrro_r', None); continue
|
||||
if w & 0xFFFFFFE0 == 0xD53BE020: kinds[o] = ('cntpct', w & 31); continue
|
||||
if w & 0xFFFFFFE0 == 0xD53BE040: kinds[o] = ('cntvct', w & 31); continue
|
||||
for ins in md.disasm(IMG[o:o + 4], o):
|
||||
if has18(ins): kinds[o] = ('x18', None)
|
||||
|
||||
# 按函数取指令表,找窗口与跳转表
|
||||
# Take the instruction table per function, find the windows and jump tables
|
||||
import bisect
|
||||
def func_of(a):
|
||||
i = bisect.bisect_right(starts, a) - 1
|
||||
return (starts[i], starts[i + 1] if i + 1 < len(starts) else TEXT_END) if i >= 0 else (a, a + 4)
|
||||
done = set(); windows = []; jumps = {}
|
||||
funcs = sorted({func_of(a) for a, (k, _) in kinds.items() if k == 'x18'})
|
||||
for fa, fb in funcs:
|
||||
insl = list(md.disasm(bytes(IMG[fa:fb]), fa))
|
||||
ws = find_windows(insl)
|
||||
for wseg in ws:
|
||||
windows.append(wseg); done |= {x.address for x in wseg}
|
||||
for j, ins in enumerate(insl):
|
||||
if ins.mnemonic == 'br' and ins.op_str == 'x18':
|
||||
base = width = None
|
||||
ctx = insl[max(0, j - 8):j]
|
||||
for p in reversed(ctx):
|
||||
if p.mnemonic == 'adr' and p.op_str.startswith('x18,'): base = p.operands[1].imm; break
|
||||
for p in reversed(ctx):
|
||||
if p.mnemonic == 'add' and p.op_str.startswith('x18, x18,') and 'lsl #2' in p.op_str:
|
||||
idx = num(p.reg_name(p.operands[2].reg))
|
||||
for q in reversed(ctx):
|
||||
if q.mnemonic in ('ldrb', 'ldrsb') and num(q.reg_name(q.operands[0].reg)) == idx: width = 256
|
||||
if q.mnemonic in ('ldrh', 'ldrsh') and num(q.reg_name(q.operands[0].reg)) == idx: width = 65536
|
||||
if width: break
|
||||
break
|
||||
assert base and width, f'jump table {ins.address:x}'
|
||||
jumps[ins.address] = (base, width)
|
||||
# 不许有跳转落进窗口中间
|
||||
# No jump may land in the middle of a window
|
||||
inwin = {x.address for wseg in ws for x in wseg}; heads = {wseg[0].address for wseg in ws}
|
||||
for x in insl:
|
||||
if x.mnemonic in ('b', 'bl', 'cbz', 'cbnz', 'tbz', 'tbnz') or x.mnemonic.startswith('b.'):
|
||||
t = x.operands[-1].imm
|
||||
assert not (t in inwin and t not in heads), f'branch into window {x.address:x}'
|
||||
|
||||
def put_branch(at, to): struct.pack_into('<I', IMG, at, B(at, to))
|
||||
for wseg in windows:
|
||||
st, lo, hi = site_window(wseg); stat('window'); put_branch(lo, st)
|
||||
for a in sorted(kinds):
|
||||
if a in done: continue
|
||||
k, arg = kinds[a]
|
||||
ins = dis(struct.unpack_from('<I', IMG, a)[0], a)
|
||||
if k == 'x18':
|
||||
m = ins.mnemonic
|
||||
if m == 'br': st = site_br(ins, *jumps[a]); stat('br')
|
||||
elif m in ('cbz', 'cbnz', 'tbz', 'tbnz'): st = site_cond(ins); stat('cond')
|
||||
elif m in ('adr', 'adrp'): st = site_pcrel(ins); stat('pcrel')
|
||||
elif m in ('blr', 'ret', 'b', 'bl') or (m == 'ldr' and '[' not in ins.op_str): raise RuntimeError(f'{a:x} {m} {ins.op_str}')
|
||||
else: st = site_plain(ins); stat('plain')
|
||||
elif k == 'tpidr_r': st = site_sysreg_read(ins, 'KTLS'); stat(k)
|
||||
elif k == 'tpidrro_r': st = site_sysreg_read(ins, 'KTLR'); stat(k)
|
||||
elif k == 'tpidr_w': st = site_tpidr_write(ins); stat(k)
|
||||
elif k == 'svc': st = site_gate(ins, 'svc', arg); stat(k)
|
||||
elif k in ('cntpct', 'cntvct'): st = site_gate(ins, k, arg); stat(k)
|
||||
put_branch(a, st)
|
||||
|
||||
# 私有视觉分支;非OBS,0x85只读查询。只有本实验构建显式opt-in;原Qty/children和Update不变。
|
||||
# Private visual branch; not OBS, 0x85 is a read-only query. Only this experimental build explicitly opts in; the original Qty/children and Update are unchanged.
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
off, word = 0x3e443c, 0x3969c268
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == word
|
||||
assert off < TEXT_END and off not in kinds and not any(seg[0].address <= off < seg[-1].address + 4 for seg in windows)
|
||||
start = here()
|
||||
emit(STP_PRE(8, 31, 31, -16)) # w8查询结果仅用于cbz;两路恢复原x8。 | The w8 query result is used only for cbz; both paths restore the original x8.
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call(); emit(BLR(30))
|
||||
ret = here(); emit(LDP_POST(29, 30, 31, 16))
|
||||
# cbz w8, nonmatch;不改NZCV。match恢复寄存器后保children。
|
||||
# cbz w8, nonmatch; NZCV is not changed. On match, restore the registers and then preserve children.
|
||||
emit(0x34000068)
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(B(here(), 0x3e4460))
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(word); emit(B(here(), 0x3e4440))
|
||||
gates.append((ret, 'svc', 0x85, off))
|
||||
put_branch(off, start); stat('private_skill_render')
|
||||
cuts.append((off, struct.pack('<I', word).hex(), struct.pack('<I', B(off,start)).hex(),
|
||||
'private confirmed six HUD only: own image/text skip ->4460; unknown original ->4440; svc85 full800', '仅宿主'))
|
||||
elif RULE_RUN:
|
||||
patch.extend(bytes(0x80))
|
||||
stat('private_gates_reserved')
|
||||
|
||||
obs = list(OBS.get(BUILD_ID, []))
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
obs.append((0x43ecc8, 6, "b8686953", "private touch-run-v4 PRE-ldr; full800 host ABI"))
|
||||
obs.append((0x1237c60, 8, "d10143ff", "ui world anchor: camera world->screen entry (camera, point, out); host swaps x0 to a copy whose projection is shifted by the UI rect y (iPad UI kept 16:9 inside a taller screen), game camera untouched"))
|
||||
# 面板开着时冻结世界(宿主 diag.c freeze_tick,缺省关,DM_PANEL_FREEZE=1 开)。四个入口门,都只换入口参数。
|
||||
# Freeze the world while a panel is open (host diag.c freeze_tick, off by default, DM_PANEL_FREEZE=1 turns it on). Four entry gates, all of which only swap entry arguments.
|
||||
obs.append((0x5eb2c0, 10, "a9bc5ff8", "server world-sim entry (game G): while frozen the host swaps x0 to a stand-in whose event queue is empty, so no unit / timer callback runs this tick; the real queue is left untouched"))
|
||||
obs.append((0x4b7230, 11, "d10183ff", "client per-unit tick update entry (unit): while frozen the host swaps x0 to a stand-in unit carrying only the skip flag ([+0x124] bit 23), so the function takes its own early-out to the epilogue; all six call sites are inside the client tick simulation 0x461b80 / 0x461e60"))
|
||||
obs.append((0x4b74d0, 12, "f81e0ff3", "client per-unit per-frame update entry (unit): drives model animation / interpolation from the tick fraction; while frozen the host swaps x0 to a stand-in unit (type 9, no render component) so both the callee 0x2a18d0 and this function take their own early-outs"))
|
||||
obs.append((0x2c3c90, 13, "f81c0ff7", "render per-frame entry, called right after the main loop writes the world frame step [0x20cebb8] and world time [0x3114208]: while frozen the host rewrites the step to 0 and the world time to its value at freeze, the same thing the game's own pause path does at 0x2c1574"))
|
||||
obs.append((0xadc434, 14, "d10143ff", "TextBoxWidget text-changed entry (widget): reads the raw text at +0x88 and rebuilds the display; host rewrites +0x88 for strings our item-notes generator annotated with colour codes (TextBoxWidget draws U+E07E as '*'), exact-match table only, everything else untouched"))
|
||||
obs.append((0x442bc0, 15, "a9ba6ffc", "client event-message entry (x0 = packet; byte 1 = event subtype, jump table 0x1da6752): subtype 0x17 = offline difficulty scale changed -> 0x20f91c chat line + system notification; host rewrites byte 1 past the table (default branch, nothing shown) only for 0x17 and only in a rift game (dm_rift.c); otherwise untouched. orig stp x28, x27, [sp, #-0x60]!"))
|
||||
obs.append((0x634000, 16, "d10143ff", "server level change by level number (game, player, level, kind), used by waypoints / portals / quest moves: in a rift game, when the player leaves a rift map for a level that is neither town nor a rift map, the host swaps w2 to the rift's next map so the destination is replaced inside the single native transition"))
|
||||
obs.append((0x711040, 17, "d101c3ff", "server quest event 'monster killed' entry (game, monster, attacker), the only entry (callers 0x7d8550 kill, 0x7ab8dc); in a rift game, for a monster that died on a rift map, the host swaps x1 to a stand-in whose +0xc0 is null so the function takes its own early return (0x711064): bosses in the rift are combat only, no quest state / quest notifications"))
|
||||
obs.append((0x3d84a0, 18, "d10143ff", "NotificationPanel message handler entry (panel, message): on InputMessage / ControllerActionBegin with action id 9 (the menu key) the native handler re-sends the notice callback and marks the message bus consumed, so the first menu press only dismisses the notice. In touch mode the host swaps x1 to a copy of the message whose action id is not 9: the notice stays until it times out and the menu key opens the menu; controller mode keeps the native behaviour"))
|
||||
obs.append((0x2f7664, 7, "6dbb23e9", "touch target rank: candidate compare entry (closure, unit, kind, s0=score); host raises Boss/elite score, native eligibility unchanged"))
|
||||
for off, oid, ow, why in obs:
|
||||
w = struct.unpack_from('<I', IMG, off)[0]
|
||||
assert f'{w:08x}' == ow, f'观测门原指令不符 {off:#x}:{w:08x}'
|
||||
# 只许函数入口:dm_gate 只回写 x0–x8 / x30,宿主 C 代码可能改 x9–x17;入口处这些按 AAPCS64 不承载值(参数只在 x0–x7 / x8)
|
||||
# Function entries only: dm_gate writes back only x0–x8 / x30, and host C code may modify x9–x17; at entry these carry no values under AAPCS64 (arguments are only in x0–x7 / x8)
|
||||
assert off in set(starts) or (oid == 6 and off == 0x43ecc8), f'private obs point not approved {off:#x}'
|
||||
assert off < TEXT_END and off not in kinds and not any(lo <= off < hi for wseg in windows for lo, hi in [(wseg[0].address, wseg[-1].address + 4)]), f'观测门与改写点冲突 {off:#x}'
|
||||
put_branch(off, site_obs(off, oid, w)); stat('obs')
|
||||
|
||||
# 秘境出口改道(r36 起):分支门 0x89,挂在「按出口砖的连接换关」main+0x7cc1e0(游戏, 玩家, 砖) 的入口。它的四个调用者(点出口砖 0x6dbea0、
|
||||
# 入口物件 0x6aeaa0 / 0x6b0500、任务 0x7314c0)都在各自的判定通过之后才调它;目的地不是关卡号而是砖的对端房间(同一幕已生成的地图里),换不成别的幕。
|
||||
# 宿主在秘境局里把 w2 / w3 换成(秘境下一张图, 11)并让 x8≠0 → 门块直接跳去「按关卡号换关」0x634000,同一个调用者、只发生一次换关;其余情形执行原指令回 0x7cc1e4。
|
||||
# 门块与 0x85 分支门逐字同构(structck ⑪ 按 hle.h 登记表核);与观测门 15 / 16 一样只在带宿主私有门的产物里(touch)
|
||||
# Rift exit rerouting (since r36): branch gate 0x89, hooked at the entry of "change level by the exit tile's connection" main+0x7cc1e0(game, player, tile). Its four callers (clicking an exit tile 0x6dbea0,
|
||||
# entrance objects 0x6aeaa0 / 0x6b0500, quest 0x7314c0) all call it only after their own checks have passed; the destination is not a level id but the tile's peer room (in the already generated map of the same act), so it cannot be switched to another act.
|
||||
# In a rift run the host replaces w2 / w3 with (the rift's next map, 11) and makes x8≠0 → the gate block jumps straight to "change level by level id" 0x634000, same caller, exactly one level change; in all other cases the original instruction is executed and control returns to 0x7cc1e4.
|
||||
# The gate block is word-for-word isomorphic with the 0x85 branch gate (structck ⑪ checks it against the hle.h registry); like observation gates 15 / 16 it exists only in build outputs with host-private gates (touch)
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
off, word, tgt = 0x7cc1e0, 0xd10183ff, 0x634000
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == word and off in set(starts) and tgt in set(starts)
|
||||
assert off < TEXT_END and off not in kinds and not any(seg[0].address <= off < seg[-1].address + 4 for seg in windows)
|
||||
start = here()
|
||||
emit(STP_PRE(8, 31, 31, -16))
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call(); emit(BLR(30))
|
||||
ret = here(); emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(0x34000068)
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(B(here(), tgt))
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(word); emit(B(here(), off + 4))
|
||||
gates.append((ret, 'svc', 0x89, off))
|
||||
put_branch(off, start); stat('rift_exit')
|
||||
cuts.append((off, struct.pack('<I', word).hex(), struct.pack('<I', B(off, start)).hex(),
|
||||
'rift exit redirect: tile-link level change entry -> host swaps (level, kind) and x8!=0 takes the branch to level-number change 0x634000; otherwise original ->0x7cc1e4; svc89', '仅宿主'))
|
||||
|
||||
# 秘境里存档时的当前幕(r38 起):分支门 0x8c,挂在原版写存档头函数 0x6fa3e0 里「取难度」那条 main+0x6fa9d0(ldrb w10, [x21, #0x104])。
|
||||
# 它的上一条 0x6fa9cc 刚把「玩家当前在第几幕」读进 w9(ldrb w9, [x24, #0x2e8]),下面 0x6fa9e4 / 0x6fa9e8 写成难度字节 0x80 | 幕号(.d2s 0x98–0x9a),
|
||||
# 下次进局落哪个城由它定。宿主在人处于秘境图里时把 w9 换成 4(第五幕 → 重进落哈洛加斯),只动写进存档的这一个值,运行中的幕号不碰。
|
||||
# 用分支门而不是「替换一条指令」:structck 只认「bl 调用点」「入口」「分支门」三种登记形态。宿主永远让 x8 = 0(不走跳转那一路),
|
||||
# 门块恢复 x8、执行原指令、回 0x6fa9d4;跳转目标填回点本身只为满足模板(走不到)。门块与 0x85 / 0x89 逐字同构
|
||||
# Current act written to the save while in a Rift (since r38): branch gate 0x8c, hooked at the "read difficulty" instruction main+0x6fa9d0 (ldrb w10,
|
||||
# [x21, #0x104]) inside the original save-header writer 0x6fa3e0.
|
||||
# The preceding instruction 0x6fa9cc has just loaded "which act the player is currently in" into w9 (ldrb w9, [x24, #0x2e8]); below, 0x6fa9e4 / 0x6fa9e8
|
||||
# write it as the difficulty byte 0x80 | act number (.d2s 0x98–0x9a),
|
||||
# which decides which town the next session starts in. While the player is in a Rift map the host replaces w9 with 4 (Act 5 → re-enter in Harrogath);
|
||||
# only this one value written to the save is changed, the running act number is untouched.
|
||||
# A branch gate is used rather than "replace one instruction": structck only recognizes three registered forms, "bl call site", "entry" and "branch
|
||||
# gate". The host always sets x8 = 0 (the jump path is never taken);
|
||||
# the gate block restores x8, executes the original instruction and returns to 0x6fa9d4; the jump target is set to the return point itself only to
|
||||
# satisfy the template (never reached). The gate block is word-for-word identical in structure to 0x85 / 0x89
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
off, word, tgt = 0x6fa9d0, 0x394412aa, 0x6fa9d4 # 函数中间的一条指令(同 0x85 那扇门),不要求是函数入口;原指令不依赖 pc | An instruction in the middle of a function (same as gate 0x85); it need not be a function entry; the original instruction does not depend on pc
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == word
|
||||
assert off < TEXT_END and off not in kinds and not any(seg[0].address <= off < seg[-1].address + 4 for seg in windows)
|
||||
start = here()
|
||||
emit(STP_PRE(8, 31, 31, -16))
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call(); emit(BLR(30))
|
||||
ret = here(); emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(0x34000068)
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(B(here(), tgt))
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(word); emit(B(here(), off + 4))
|
||||
gates.append((ret, 'svc', 0x8c, off))
|
||||
put_branch(off, start); stat('rift_save_act')
|
||||
cuts.append((off, struct.pack('<I', word).hex(), struct.pack('<I', B(off, start)).hex(),
|
||||
'rift save act: save-header writer, right after it loads the current act into w9 -> host swaps w9 to 4 (act V) while the player is in a rift map; x8 stays 0, original insn runs ->0x6fa9d4; svc8c', '仅宿主'))
|
||||
# 佣兵加装备位(r39 起):分支门 0x8d,挂在原版通用放置校验 main+0x6493a8 的怪物主人分支里 main+0x64a34c(mov w9, w25)。
|
||||
# 这一段(0x64a314–0x64a354)对怪物类主人只放行两类物品:0x574bc0(物品, 3 护甲)、0x574bc0(物品, 0x25 头盔),都不是就走武器那条(按 monstats 的左右手类型),再不中就拒。
|
||||
# 门挂在「是不是头盔」返回之后、cbnz w0 之前:宿主在「主人是玩家的佣兵 + 秘境最高通关 ≥ 10 层 + 物品是腰带 / 鞋 / 手套 / 戒指 / 项链」时把 w0 改成 1,
|
||||
# 走头盔同一条放行路径(后面的部位格子、部位空不空等通用检查照常)。宿主永远让 x8 = 0;门块与 0x85 / 0x89 / 0x8c 逐字同构
|
||||
# Extra mercenary equipment slots (since r39): branch gate 0x8d, hooked in the monster-owner branch of the original game's generic placement check main+0x6493a8 at main+0x64a34c (mov w9, w25).
|
||||
# This section (0x64a314–0x64a354) lets through only two kinds of items for monster-type owners: 0x574bc0(item, 3 armor) and 0x574bc0(item, 0x25 helm); if neither, it takes the weapon path (by the left / right hand types in monstats), and if that fails too it rejects.
|
||||
# The gate is hooked after the "is it a helm" call returns and before cbnz w0: when "the owner is the player's mercenary + highest rift level cleared ≥ 10 + the item is a belt / boots / gloves / ring / amulet", the host changes w0 to 1,
|
||||
# taking the same pass path as the helm (the generic checks that follow, such as the body location cell and whether the location is empty, run as usual). The host always sets x8 = 0; the gate block is word-for-word isomorphic with 0x85 / 0x89 / 0x8c
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
off, word, tgt = 0x64a34c, 0x2a1903e9, 0x64a350 # 原指令不依赖 pc | The original instruction does not depend on pc
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == word
|
||||
assert off < TEXT_END and off not in kinds and not any(seg[0].address <= off < seg[-1].address + 4 for seg in windows)
|
||||
start = here()
|
||||
emit(STP_PRE(8, 31, 31, -16))
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call(); emit(BLR(30))
|
||||
ret = here(); emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(0x34000068)
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(B(here(), tgt))
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(word); emit(B(here(), off + 4))
|
||||
gates.append((ret, 'svc', 0x8d, off))
|
||||
put_branch(off, start); stat('merc_slot')
|
||||
cuts.append((off, struct.pack('<I', word).hex(), struct.pack('<I', B(off, start)).hex(),
|
||||
'merc slots: placement check, monster-owner branch right after the helm type test -> host sets w0=1 for ring/amulet/boots/gloves/belt on a hireling (rift best >= 10 for new equips; always on load); x8 stays 0, original insn runs ->0x64a350; svc8d', '仅宿主'))
|
||||
# 佣兵加装备位的客户端那一半(r39 同代):分支门 0x8e,挂在客户端「佣兵能不能穿这件」函数 main+0x3bea44(佣兵, 物品) 里 main+0x3beb58(mov x0, x19)。
|
||||
# 这个函数和服务端那段同一个规则:0x574bc0(物品, 3 护甲)、0x574bc0(物品, 0x25 头盔) 中一个就返回 1,都不是走武器那条。物品格控件拿它的结果画「不可放置」的红色、
|
||||
# 决定松手时放不放——不改它,已解锁的新格拖着对的物品悬停也是红的、原版放下不成(原先靠触摸层兜底直接调 0x3bed60)。
|
||||
# 门挂在「mov w1, #0x25」之后、这次类型判断的 bl 之前:宿主在「秘境最高通关 ≥ 10 层 + 物品是腰带 / 鞋 / 手套 / 戒指 / 项链」时把 w1 换成该物品自己的类型号,
|
||||
# 类型判断自然成立、走头盔同一条返回 1 的路。宿主永远让 x8 = 0;门块与 0x8d 逐字同构
|
||||
# Client half of the extra mercenary equipment slots (same generation as r39): branch gate 0x8e, hooked inside the client's "can the mercenary wear this" function main+0x3bea44(mercenary, item) at main+0x3beb58 (mov x0, x19).
|
||||
# This function follows the same rule as the server-side section: if either 0x574bc0(item, 3 armor) or 0x574bc0(item, 0x25 helm) matches it returns 1, and if neither does it takes the weapon path. The item cell widget uses its result to draw the "cannot place" red and
|
||||
# to decide whether to place on release -- without changing it, an unlocked new cell still shows red when the right item is dragged over it, and the original game's drop fails (previously the touch layer's fallback called 0x3bed60 directly).
|
||||
# The gate is hooked after "mov w1, #0x25" and before the bl of this type check: when "highest rift level cleared ≥ 10 + the item is a belt / boots / gloves / ring / amulet", the host replaces w1 with the item's own type number,
|
||||
# so the type check passes naturally and takes the same return-1 path as the helm. The host always sets x8 = 0; the gate block is word-for-word isomorphic with 0x8d
|
||||
if RULE_RUN and PRIVATE_GATES:
|
||||
off, word, tgt = 0x3beb58, 0xaa1303e0, 0x3beb5c # 原指令不依赖 pc | The original instruction does not depend on pc
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == word
|
||||
assert off < TEXT_END and off not in kinds and not any(seg[0].address <= off < seg[-1].address + 4 for seg in windows)
|
||||
start = here()
|
||||
emit(STP_PRE(8, 31, 31, -16))
|
||||
emit(STP_PRE(29, 30, 31, -16))
|
||||
emit_gate_call(); emit(BLR(30))
|
||||
ret = here(); emit(LDP_POST(29, 30, 31, 16))
|
||||
emit(0x34000068)
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(B(here(), tgt))
|
||||
emit(LDP_POST(8, 31, 31, 16)); emit(word); emit(B(here(), off + 4))
|
||||
gates.append((ret, 'svc', 0x8e, off))
|
||||
put_branch(off, start); stat('merc_slot_client')
|
||||
cuts.append((off, struct.pack('<I', word).hex(), struct.pack('<I', B(off, start)).hex(),
|
||||
'merc slots (client): hireling can-equip check, between "mov w1,#0x25" and the type test -> host swaps w1 to the item\'s own type for ring/amulet/boots/gloves/belt (rift best >= 10); x8 stays 0, original insn runs ->0x3beb5c; svc8e', '仅宿主'))
|
||||
|
||||
# ---- 参数位(仅宿主):{NSO 构建号: [(偏移 A, 原字 A, 偏移 B, 原字 B, 寄存器, 键, 理由)]}。
|
||||
# 原处两条造常数指令改成第一条跳补丁区参数跳板、第二条 nop;跳板间接取键页值后跳回第一条之后(A+4):A、B 不相邻时中间的原指令照常执行
|
||||
# (曾跳回 B+4,运行模式通知处理 0xe10d5c/0xe10d60 越过 adrp x19.. 与另一跳板,切掌机即崩;structck ⑩ 核跳板出口)。
|
||||
# A、B 之间不得读写 xR(离线断言:中间指令不含 xR)。宿主按前端给值,Mac 给原常数 → 行为不变 ----
|
||||
# ---- Parameter slots (host only): {NSO build ID: [(offset A, original word A, offset B, original word B, register, key, reason)]}.
|
||||
# The two constant-building instructions at the original site are changed so that the first jumps to a parameter trampoline in the patch area and the second is a nop; the trampoline fetches the key page value indirectly and jumps back to just after the first (A+4): when A and B are not adjacent, the original instructions in between execute as usual
|
||||
# (it used to jump back to B+4; in the operation-mode notification handler 0xe10d5c/0xe10d60 that skipped adrp x19.. and another trampoline, and switching to handheld crashed immediately; structck ⑩ checks the trampoline exit).
|
||||
# xR must not be read or written between A and B (offline assertion: the instructions in between do not contain xR). The host supplies values according to the front end, Mac supplies the original constants → behavior unchanged ----
|
||||
PARAMS = {'db0507f36b84200ac05f75d76ed5026f': [
|
||||
(0xe12d8c, 'd280c813', 0xe12d90, 'f2c07093', 19, 'KRES1', '启动初始化:主机模式输出分辨率 1600x900({u32 宽, u32 高} 打包)'),
|
||||
(0xe12e1c, 'd280a008', 0xe12e20, 'f2c05a08', 8, 'KRES0', '启动初始化:掌机模式输出分辨率 1280x720'),
|
||||
(0xe10d60, 'd280c818', 0xe10d80, 'f2c07098', 24, 'KRES1', '运行模式变化通知(0x1f)处理:主机模式 1600x900'),
|
||||
(0xe10d5c, 'd280a016', 0xe10d74, 'f2c05a16', 22, 'KRES0', '运行模式变化通知(0x1f)处理:掌机模式 1280x720'),
|
||||
# 宽高比上限 19:9(float 0x40071c72):宽于 19:9 的屏幕两侧留黑柱。宿主给 max(19/9, 输出宽 / 高) 的浮点位模式(低 32 位);
|
||||
# 原版输出 16:9(1600x900 / 1280x720)⇒ 仍为 19/9,行为不变;iPhone 1952x900(2.17:1)⇒ 2.169,黑柱宽 0
|
||||
# Aspect ratio cap 19:9 (float 0x40071c72): screens wider than 19:9 get black bars on both sides. The host supplies the float bit pattern (low 32 bits) of max(19/9, output width / height);
|
||||
# the original game outputs 16:9 (1600x900 / 1280x720) ⇒ still 19/9, behavior unchanged; iPhone 1952x900 (2.17:1) ⇒ 2.169, black bar width 0
|
||||
(0x1663ee8, '52838e49', 0x1663eec, '72a800e9', 9, 'KASPECTUI', '界面常量缓冲 0x15 号槽 [屏宽, 屏高, 宽高比上限]:界面精灵着色器按它在上限以外画两侧黑柱(带约 20–30 像素向内的柔边,宿主另加余量把柔边推出屏幕)'),
|
||||
(0xb152bc, '52838e48', 0xb152c0, '72a800e8', 8, 'KASPECT', '新画面模式视口:边距 = (屏宽 − 屏高 × 上限) / 2,经 0x85bc90 设居中视口'),
|
||||
(0x23e888, '52838e48', 0x23e88c, '72a800e8', 8, 'KASPECT', '新画面模式坐标钳制(0x23e760):x 夹进 [边距, 边距 + 屏高 × 上限],宽屏两侧的指针 / 触摸不再被夹回中间'),
|
||||
]}
|
||||
params = PARAMS.get(BUILD_ID, [])
|
||||
for oa, wa, ob_, wb, r, key, why in params:
|
||||
for o, w0 in ((oa, wa), (ob_, wb)):
|
||||
w = struct.unpack_from('<I', IMG, o)[0]
|
||||
assert f'{w:08x}' == w0, f'参数位原指令不符 {o:#x}:{w:08x}'
|
||||
assert o not in kinds and not any(lo <= o < hi for wseg in windows for lo, hi in [(wseg[0].address, wseg[-1].address + 4)]), f'参数位与改写点冲突 {o:#x}'
|
||||
for o in range(oa + 4, ob_, 4):
|
||||
ins = dis(struct.unpack_from('<I', IMG, o)[0], o)
|
||||
assert r not in regs_in(ins), f'参数位中间用到 x{r}:{o:#x} {ins.mnemonic} {ins.op_str}'
|
||||
start = here()
|
||||
tmp = 16 if r != 16 else 17
|
||||
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(r)); emit_slot_addr(r, tmp, key); emit(LDRX(r, r)); emit(LDUR(tmp, 31, -16)); emit(B(here(), oa + 4))
|
||||
struct.pack_into('<I', IMG, oa, B(oa, start)); struct.pack_into('<I', IMG, ob_, NOP); stat('param')
|
||||
|
||||
# 既有三块原生规则跳板均只使用后继覆盖的死临时w8,不改w0/stat返回、sp或NZCV。
|
||||
# 6c6290位于原mode3门后;前方Blaze/引用计数与数据失效6c62dc分支、后方状态更新不动。
|
||||
# The three existing native rule trampolines all use only the dead temporary w8 that is overwritten afterwards, and do not change the w0/stat return, sp or NZCV.
|
||||
# 6c6290 is after the original mode3 gate; the Blaze / reference count and data invalidation 6c62dc branches before it and the state update after it are untouched.
|
||||
rule_blocks = []
|
||||
if RULE_RUN:
|
||||
def run_branch(off, old, body, why):
|
||||
assert struct.unpack_from('<I', IMG, off)[0] == old, f'Run跳板原字不符 {off:#x}'
|
||||
start = here()
|
||||
for word in body(start): emit(word)
|
||||
new = B(off, start)
|
||||
struct.pack_into('<I', IMG, off, new)
|
||||
cuts.append((off, struct.pack('<I', old).hex(), struct.pack('<I', new).hex(), why, '全'))
|
||||
rule_blocks.append((start, bytes(patch[start - PATCH_OFF:]).hex(), why))
|
||||
def cbz(at, target, r, nonzero=False):
|
||||
delta = target-at; assert delta%4==0 and -(1<<20)<=delta<(1<<20)
|
||||
return (0x35000000 if nonzero else 0x34000000) | (((delta>>2)&0x7ffff)<<5) | r
|
||||
run_branch(0x6c6648, 0x34000060, lambda a: [
|
||||
0xb9400268, cbz(a+4,a+12,8,True), B(a+8,0x6c664c),
|
||||
cbz(a+12,a+20,0), B(a+16,0x6c664c), B(a+20,0x6c6654)],
|
||||
'touch-run-v4:Run选择仅player0忽略精力门,非player按原stat返回;w8后继覆盖')
|
||||
run_branch(0x6c6290, 0x710006df, lambda a: [
|
||||
0xb9400268, cbz(a+4,a+12,8,True), B(a+8,0x6c62ec), 0x710006df, B(a+16,0x6c6294)],
|
||||
'touch-run-v4:原合法Run成本段仅player0跳stat10扣除/耗尽降走;非player保持原cmp')
|
||||
|
||||
|
||||
# client4abc60原mode3/当前受控unit门之后;实际GetStat已返回,保W0,只type0取消STA自动Stop。
|
||||
# After the original mode3 / currently controlled unit gate at client4abc60; the actual GetStat has already returned, W0 is preserved, and only for type0 is the STA auto Stop cancelled.
|
||||
run_branch(0x4ac368, 0x35000460, lambda a: [
|
||||
0xb9400268, cbz(a+4,a+12,8), B(a+8,a+16), B(a+12,0x4ac3f4),
|
||||
cbz(a+16,a+24,0), B(a+20,0x4ac3f4), B(a+24,0x4ac36c)],
|
||||
'touch-run-v4:client当前受控Run3仅player0跳STA零值自动Stop;原getter值与真实松杆保留,非player保原门')
|
||||
|
||||
|
||||
# 原unit null/type5门之后、w8仍为原unitType;只规范player请求2,原其它动作分派/资格完整执行。
|
||||
# After the original unit null/type5 gate, with w8 still the original unitType; only player request 2 is normalized, and the other original action dispatch / eligibility checks run in full.
|
||||
run_branch(0x6c6580, 0x51000849, lambda a: [
|
||||
cbz(a,a+16,8,True), 0x51000849, cbz(a+8,a+16,9,True),
|
||||
0x52800062, 0x51000849, B(a+20,0x6c6584)],
|
||||
'touch-run-v4:原通用合法移动仅player0请求Walk2规范为Run3,非player与其它请求保原,w8/原资格不改')
|
||||
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
P = lambda ext: os.path.join(outdir, f'{NAME}.{ext}')
|
||||
open(P('patched.bin'), 'wb').write(IMG + bytearray(PATCH_OFF - len(IMG)) + patch)
|
||||
import hashlib
|
||||
with open(os.path.join(outdir, 'build_src.sha256'), 'w') as f:
|
||||
f.write(hashlib.sha256(open(os.path.abspath(__file__), 'rb').read()).hexdigest() + ' patch_nso.py\n')
|
||||
if PRIVATE_AIM:
|
||||
with open(P('aim.tsv'), 'w') as f:
|
||||
f.write('# RULESET\tskill-aim-v1-private\n# ORIGINAL_CALL\t0x2faf04\t97fee7fd\n# ORIGINAL_CALLEE\t0x2b4ef8\n# SKILL_CALLER\t0x2b5b80\n# SVC\t0x86\n# INPUT\tactual GetNpad sampled right; move axis unchanged\n')
|
||||
f.write('# IMAGE_SHA256\t'+hashlib.sha256(open(P('patched.bin'),'rb').read()).hexdigest()+'\n')
|
||||
if RULE_RUN:
|
||||
with open(P('rules.tsv'), 'w') as f:
|
||||
f.write(f'# RULESET\t{RULESET}\n# BUILD_ID\t{BUILD_ID}\n# ORIGINAL_SHA256\t{RULE_ORIG_SHA}\n# IMAGE_SHA256\t{hashlib.sha256(open(P("patched.bin"), "rb").read()).hexdigest()}\n')
|
||||
for off, raw, why in rule_blocks: f.write(f'{off:#x}\t{raw}\t{hashlib.sha256(bytes.fromhex(raw)).hexdigest()}\t{why}\n')
|
||||
elif os.path.exists(P('rules.tsv')):
|
||||
os.unlink(P('rules.tsv')) # 重出native时清本模块旧规则登记,不让旧manifest混入原资源域 | When rebuilding native, clear this module's old rule registration so the old manifest does not leak into the original-resource domain
|
||||
with open(P('fixups.tsv'), 'w') as f:
|
||||
f.write(f'# PATCH_OFF\t{PATCH_OFF:#x}\n# KEY_PAGE_OFF\t{KEY_PAGE_OFF:#x}\n# KEY_PAGE_SIZE\t0x4000\n# TEXT_END\t{TEXT_END:#x}\n# RO_OFF\t{RO_OFF:#x}\n# DATA_OFF\t{DATA_OFF:#x}\n')
|
||||
for k in KEY_INDEX: f.write(f'# KEY_{k}_IDX\t{KEY_INDEX[k]}\n')
|
||||
with open(P('gates.tsv'), 'w') as f:
|
||||
for ret, k, arg, orig in gates: f.write(f'{ret:#x}\t{k}\t{arg}\t{orig:#x}\n')
|
||||
with open(P('sites.tsv'), 'w') as f:
|
||||
for a in sorted(kinds):
|
||||
if a not in done: f.write(f'{a:#x}\t{kinds[a][0]}\n')
|
||||
for wseg in windows: f.write(f'{wseg[0].address:#x}\tW\t{wseg[-1].address + 4:#x}\n')
|
||||
for a, (b, c) in jumps.items(): f.write(f'{a:#x}\tJ\t{b:#x}\t{c}\n')
|
||||
with open(P('cuts.tsv'), 'w') as f:
|
||||
f.write(f'# BUILD_ID\t{BUILD_ID}\n')
|
||||
for off, ob, nb, why, scope in cuts: f.write(f'{off:#x}\t{ob}\t{nb}\t{scope}\t{why}\n') # 列:偏移 原字节 新字节 作用域 理由 | Columns: offset, original bytes, new bytes, scope, reason
|
||||
with open(P('params.tsv'), 'w') as f:
|
||||
f.write(f'# BUILD_ID\t{BUILD_ID}\n')
|
||||
for oa, wa, ob_, wb, r, key, why in params: f.write(f'{oa:#x}\t{ob_:#x}\tx{r}\t{key}\t{why}\n')
|
||||
with open(P('obs.tsv'), 'w') as f:
|
||||
f.write(f'# BUILD_ID\t{BUILD_ID}\n')
|
||||
for off, oid, ow, why in obs: f.write(f'{off:#x}\t{oid}\t{ow}\t{why}\n')
|
||||
print(NAME, stats, 'cuts', len(cuts), 'obs', len(obs), 'patch', len(patch), 'PATCH_OFF', hex(PATCH_OFF), 'slot_refs', len(fix), 'gates', len(gates))
|
||||
# 启动块清单随 main 出:取仓库版本化数据 dm/data/bootlist_<main 构建号>.tsv 原样拷进产物目录并写 sha256(清单入库、不每版重录;
|
||||
# 记录本身有竞态——同产物三次记录块集合 5292 / 5114 / 5281、发起线程亦有不同——重录只在构建号变化或主动改进时做,提交附 mini A/B)
|
||||
# The boot block list ships with main: take the repository's versioned data dm/data/bootlist_<main build ID>.tsv, copy it as is into the build output directory and write its sha256 (the list is checked in, not re-recorded for every version;
|
||||
# the recording itself is racy -- three recordings of the same build output gave block sets of 5292 / 5114 / 5281, and the initiating threads also differed -- re-record only when the build ID changes or for a deliberate improvement, and attach an A/B from the second Mac to the commit)
|
||||
if NAME == 'main':
|
||||
import hashlib, shutil
|
||||
BL = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', f'bootlist_{BUILD_ID}.tsv')
|
||||
if not os.path.isfile(BL): # 公开仓库不带这份清单(它每行带原版资源块的开头字节):没有就不预取,启动时少一步提前解码,别的不受影响 | the public repository does not ship this list (each line carries the first bytes of an original resource block): without it there is no prefetch, so launch skips one ahead-of-time decode step and nothing else is affected
|
||||
print('bootlist 没有启动块清单,跳过(不预取)。要用的话自己录一份:dm/tools/tact_bootlist.py')
|
||||
else:
|
||||
hd = open(BL, encoding='utf-8').readline().split()
|
||||
if hd[-1:] != [BUILD_ID]: sys.exit(f'【红】{BL} 头行构建号 {hd[-1:]} 与 main {BUILD_ID} 不符')
|
||||
shutil.copyfile(BL, os.path.join(outdir, 'bootlist.tsv'))
|
||||
sha = hashlib.sha256(open(BL, 'rb').read()).hexdigest()
|
||||
open(os.path.join(outdir, 'bootlist.sha256'), 'w').write(f'{sha} bootlist.tsv\n')
|
||||
print('bootlist', os.path.relpath(BL), sha[:12])
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
# 当前改写产物的代号只写在一处:dm/PRODUCT(一行,如 3.3.94012-r28)。换代只改那一行。
|
||||
# 用法:product.sh name <种类> → 3.3.94012-r28-<种类>(种类:touch / rules / keypage)
|
||||
# product.sh path <种类> → 本机缺省产物目录 $DM_ROOT/build/cache/dm/out/<name>
|
||||
# product.sh rev → r28
|
||||
# product.sh build → 重出三种产物(keypage / rules / touch)到本机缺省目录
|
||||
# The codename of the current rewrite build output is written in exactly one place: dm/PRODUCT (one line, e.g. 3.3.94012-r28). A revision bump changes only that line.
|
||||
# Usage: product.sh name <kind> → 3.3.94012-r28-<kind> (kind: touch / rules / keypage)
|
||||
# product.sh path <kind> → local default build output directory $DM_ROOT/build/cache/dm/out/<name>
|
||||
# product.sh rev → r28
|
||||
# product.sh build → rebuild the three kinds of build output (keypage / rules / touch) into the local default directory
|
||||
set -u
|
||||
P=$(head -1 "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/PRODUCT") || exit 2
|
||||
[ -n "$P" ] || { echo "dm/PRODUCT 为空" >&2; exit 2; }
|
||||
case "${1:-}" in
|
||||
name) echo "$P-${2:?种类}";;
|
||||
path) echo "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-${2:?种类}";;
|
||||
rev) echo "${P##*-}";;
|
||||
build) # 用本工作树的改写器重出三种产物到本机缺省目录(换代 / 改了 patch_nso.py 之后跑)。种类 → 规则集:keypage = 原生;rules = 触屏规则、不带宿主私有门;touch = 触屏规则 + 私有门 | Rebuild the three kinds of build output with this worktree's rewriter into the local default directory (run after a revision bump / after changing patch_nso.py). Kind → rule set: keypage = native; rules = touchscreen rules, without host-private gates; touch = touchscreen rules + private gates
|
||||
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); PY=${DM_PY:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python3}; NSO=${DM_NSO_DIR:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/ExeFS}
|
||||
for k in keypage rules touch; do O=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-$k; mkdir -p "$O"
|
||||
case $k in keypage) E=(DM_RULESET=native);; rules) E=(DM_RULESET=touch-run-v4 DM_PRIVATE_GATES=0);; touch) E=(DM_RULESET=touch-run-v4);; esac
|
||||
for m in main sdk subsdk0; do env "${E[@]}" "$PY" "$HERE/patch_nso.py" "$NSO/$m" "$O" "$m" > "$O/$m.patch.log" 2>&1 || { echo "🔴 $k $m 改写失败:$(tail -2 "$O/$m.patch.log")" >&2; exit 1; }; done
|
||||
echo "$P-$k 已出:$(ls "$O" | wc -l | tr -d ' ') 个文件"; done;;
|
||||
*) echo "用法:product.sh name|path <种类> | rev | build" >&2; exit 2;;
|
||||
esac
|
||||
@@ -0,0 +1,60 @@
|
||||
# 全线程采样(DM_SAMPLE=毫秒:*)汇总:按时间窗、可选线程,统计各线程在跑占比,及游戏函数(eh_frame 起点)自身 / 含子调用热点。
|
||||
# 用法:sampagg.py <日志> <起s> <止s> [线程句柄 0x…] 需要 build/cache/dm/out/3.3.94012-r2/{main,sdk}.orig.bin(原映像,按偏移解函数)
|
||||
# 不给线程:列各线程样本数、在跑占比、自身热点前 3
|
||||
# 给线程:该线程在跑样本的自身热点、宿主帧、含子调用热点(等待类样本 = 最内层在系统等待函数,不计入在跑)
|
||||
# All-thread sampling (DM_SAMPLE=ms:*) summary: for a time window and an optional thread, reports each thread's running share and the self / inclusive hotspots of game functions (eh_frame starts).
|
||||
# Usage: sampagg.py <log> <start s> <end s> [thread handle 0x...] Requires build/cache/dm/out/3.3.94012-r2/{main,sdk}.orig.bin (original images, functions resolved by offset)
|
||||
# No thread given: lists each thread's sample count, running share and top 3 self hotspots
|
||||
# Thread given: that thread's self hotspots among running samples, host frames, and inclusive hotspots (waiting samples = innermost frame is in a system wait function, not counted as running)
|
||||
import sys, re, bisect, subprocess, collections, os
|
||||
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)
|
||||
log, lo, hi = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]); thr = int(sys.argv[4], 16) if len(sys.argv) > 4 else None
|
||||
ORIG = os.path.join(DM_ROOT, 'build/cache/dm/out/3.3.94012-r2')
|
||||
SDIS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sdis.py')
|
||||
st = {}
|
||||
for m in ('main', 'sdk'):
|
||||
sys.argv = ['x', f'{ORIG}/{m}.orig.bin', '--find', 'x']; g = {}
|
||||
exec(open(SDIS).read().split("if sys.argv[2] == '--sym'")[0], g); st[m] = (g['fn_starts'](), g['name'])
|
||||
WAIT = ('mach_wait_until', '__psynch_cvwait', '__semwait_signal', 'nanosleep', 'mach_msg2_trap', 'swtch_pri', '__psynch_mutexwait', 'block_inner', '__ulock_wait')
|
||||
lines = open(log, encoding='utf-8', errors='replace').read().split('\n')
|
||||
def fnof(f):
|
||||
mm = re.match(r'(main|sdk)\+0x([0-9a-f]+)', f)
|
||||
if not mm: return None
|
||||
s, _ = st[mm.group(1)]; off = int(mm.group(2), 16); return f'{mm.group(1)}+{s[bisect.bisect_right(s, off) - 1]:#x}'
|
||||
def dm(fn):
|
||||
mod, a = fn.split('+'); r = st[mod][1](int(a, 16))
|
||||
return subprocess.run(['xcrun', 'c++filt', r], capture_output=True, text=True).stdout.strip()[:70]
|
||||
per = collections.defaultdict(lambda: [0, 0, collections.Counter()]); selfc = collections.Counter(); incl = collections.Counter(); host = collections.Counter(); waitat = collections.Counter(); n = 0
|
||||
for i, l in enumerate(lines):
|
||||
m = re.match(r'\[dm\] SAMPLE #\d+ \[([\d.]+)s\] thr=(0x[0-9a-f]+) pc=(\S+)', l)
|
||||
if not m or not (lo <= float(m.group(1)) <= hi): continue
|
||||
h = int(m.group(2), 16); pc = m.group(3); p = per[h]
|
||||
bt = lines[i + 1].split('bt:')[1].split() if i + 1 < len(lines) and 'bt:' in lines[i + 1] else []
|
||||
if any(pc.startswith(w) for w in WAIT):
|
||||
p[1] += 1
|
||||
if thr is not None and h == thr: # 等待点:回溯里第一个游戏函数(含 sdk 同步原语时再往外找一层 main 函数) | Wait point: the first game function in the backtrace (when it contains an sdk synchronization primitive, look one more level out for a main function)
|
||||
fs = [fnof(f) for f in bt if fnof(f)]; mf = next((f for f in fs if f.startswith('main')), None)
|
||||
waitat[(fs[0] if fs else '?') + ' ← ' + (mf or '?')] += 1
|
||||
continue
|
||||
p[0] += 1; frames = [pc] + bt
|
||||
first = next((fnof(f) for f in frames if fnof(f)), None)
|
||||
p[2][first or '(宿主) ' + pc.split('+')[0]] += 1
|
||||
if thr is None or h != thr: continue
|
||||
n += 1
|
||||
if not fnof(pc): host[pc.split('+')[0]] += 1
|
||||
if first: selfc[first] += 1
|
||||
seen = set()
|
||||
for f in frames:
|
||||
fn = fnof(f)
|
||||
if fn and fn not in seen: incl[fn] += 1; seen.add(fn)
|
||||
if thr is None:
|
||||
for h, (run, wait, c) in sorted(per.items(), key=lambda x: -x[1][0]):
|
||||
tot = run + wait
|
||||
if tot: print(f'{h:#x} 样本 {tot:5d} 在跑 {100 * run / tot:5.1f}% 热点: ' + '; '.join(f'{fn} {k}' for fn, k in c.most_common(3)))
|
||||
sys.exit(0)
|
||||
run, wait, _ = per[thr]
|
||||
print(f'线程 {thr:#x} 窗口 [{lo}, {hi}]:样本 {run + wait},在跑 {run}({100 * run / max(1, run + wait):.1f}%)')
|
||||
print('== 自身(最内层游戏函数,占在跑样本)'); [print(f'{c:4d} {100 * c / max(1, n):5.1f}% {fn} {dm(fn)}') for fn, c in selfc.most_common(12)]
|
||||
print('== 宿主帧(最内层非游戏)'); [print(f'{c:4d} {h}') for h, c in host.most_common(6)]
|
||||
print('== 含子调用'); [print(f'{c:4d} {100 * c / max(1, n):5.1f}% {fn} {dm(fn)}') for fn, c in incl.most_common(20)]
|
||||
print('== 等待点(等待样本:最内层游戏函数 ← 最内层 main 函数)'); [print(f'{c:4d} {k}') for k, c in waitat.most_common(8)]
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/bin/bash
|
||||
# 存档事务确定性回归(HLE 审计第 1–3 条;accept 全档用):在 cvd5 回放局里按存档写次数注入「被杀」/「写失败」,核已提交目录。
|
||||
# 用法:save_txn_regress.sh [产物目录];退出码 0 = 绿。每例一局 host_savecmp.sh(它的对拍结论在注入下必红,不看)。
|
||||
# cvd5 的提交顺序是确定的:提交 #1(此前存档写 0 次)→ 写 1、2(joe.d2s 与 .meta)→ 提交 #2 → 写 3(共享箱)→ 提交 #3。期望(不跑被测实现即可写出):
|
||||
# 被杀在第 1 次写:已提交 = 起始存档,逐文件相同;
|
||||
# 被杀在第 3 次写:已提交 = 提交 #2 的版本——除 joe/joe.d2s、.meta 外与起始存档逐文件相同(含共享箱),joe.d2s 长度字段 = 文件长、校验和对;
|
||||
# 写失败在第 1 次:事务 #2 拒绝提交、工作目录丢弃,事务 #3 照常提交 ⇒ 已提交 = 起始存档,只有共享箱 = 真值 save_after 的共享箱;
|
||||
# (cvd5 的共享箱重写前后字节相同,内容区分不了「#3 提交了」与「之后全拒」,另核拒绝之后恰有 1 条「此前存档写 3 次」的成功提交;
|
||||
# 内容上的区分由单测 t_fs ④ 证)
|
||||
# 写失败在第 3 次:事务 #3 拒绝 ⇒ 同「被杀在第 3 次写」。
|
||||
# 负对照(没有事务 / 不拒绝,这些残缺就进了存档):被杀例看工作目录 user/0.work 里被截成 0 字节的文件;写失败例看拒绝日志列出的 0 字节文件。
|
||||
# 截断文件:第 1 次写 = joe/joe.d2s,第 3 次写 = 共享箱。
|
||||
# Deterministic regression of save transactions (HLE audit items 1–3; used by accept full level): in a cvd5 replay run, injects "killed" / "write failure" by save write count and checks the committed directory.
|
||||
# Usage: save_txn_regress.sh [build output dir]; exit code 0 = green. Each case is one host_savecmp.sh run (its comparison verdict is necessarily a failure under injection and is ignored).
|
||||
# The commit order of cvd5 is deterministic: commit #1 (0 save writes before it) → writes 1, 2 (joe.d2s and .meta) → commit #2 → write 3 (shared stash) → commit #3. Expectations (can be written down without running the implementation under test):
|
||||
# Killed at write 1: committed = starting save, identical file by file;
|
||||
# Killed at write 3: committed = the version of commit #2 -- identical file by file to the starting save except joe/joe.d2s and .meta (shared stash included), the joe.d2s length field = file length, checksum correct;
|
||||
# Write failure at write 1: transaction #2 refuses to commit and the working directory is discarded, transaction #3 commits as usual ⇒ committed = starting save, with only the shared stash = the shared stash of the ground-truth save_after;
|
||||
# (the shared stash of cvd5 has the same bytes before and after the rewrite, so content cannot distinguish "#3 committed" from "everything refused afterwards"; additionally check that after the refusal there is exactly 1 successful commit with 「此前存档写 3 次」(3 save writes before it);
|
||||
# the distinction by content is proven by unit test t_fs ④)
|
||||
# Write failure at write 3: transaction #3 refuses ⇒ same as "killed at write 3".
|
||||
# Negative control (without transactions / without refusal these broken files would have gone into the save): for the killed cases look at the files truncated to 0 bytes in the working directory user/0.work; for the write failure cases look at the 0-byte files listed in the refusal log.
|
||||
# Truncated files: write 1 = joe/joe.d2s, write 3 = shared stash.
|
||||
set -u
|
||||
export LC_ALL=C
|
||||
X=${DM_ROOT:-$HOME/dm-work}; HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
TR=${TRUTH_RUN:-$X/data/switch/truth_runs/cvd5}; O=${1:-$(bash "$(dirname "$0")/product.sh" path keypage)}
|
||||
REF=$X/data/switch/save_ref_warlock/0000000000000001/0; AFT=$TR/save_after/0; PY=$X/build/cache/dm/venv/bin/python3
|
||||
[ -d "$TR" ] && [ -d "$REF" ] || { echo "【红】缺 cvd5 真值局或起始存档"; exit 2; }
|
||||
bad=0
|
||||
RUN=$X/run/verify/dm/save_txn/$(date +%m%d_%H%M%S)_$$; mkdir -p "$RUN" || exit 2
|
||||
echo "SAVE_TXN 现场 ${RUN};射程 4 例,每例独立存档副本"
|
||||
# 4 例各起一局宿主、互不相干(局目录带各自进程号、存档各用副本):一起起跑再逐例判,本项墙钟从 4 局之和降到最慢一局(accept 提速)
|
||||
# The 4 cases each start one host run and are independent of one another (run directories carry their own pid, each save uses its own copy): start them all together and then judge case by case, so this item's wall clock drops from the sum of 4 runs to the slowest single run (accept speedup)
|
||||
for c in KILL_AT:1 KILL_AT:3 FS_FAIL:1 FS_FAIL:3; do
|
||||
V=${c%%:*}; K=${c##*:}
|
||||
env DM_TEST_$V=write:$K bash "$HERE/dm/tools/host_savecmp.sh" "$TR" "$O" > "$RUN/${V}_$K.log" 2>&1 &
|
||||
done
|
||||
wait
|
||||
for c in KILL_AT:1 KILL_AT:3 FS_FAIL:1 FS_FAIL:3; do
|
||||
V=${c%%:*}; K=${c##*:}; L=$RUN/${V}_$K.log
|
||||
D=$(grep -o '局目录 .*' "$L" | cut -d' ' -f2)
|
||||
[ -n "$D" ] && [ -f "$D/host.log" ] || { echo "【红】$c 没跑起来,见 $L"; echo "$c 启动红" >> "$RUN/KEEP"; bad=1; continue; }
|
||||
echo "$D" > "$RUN/${V}_$K.dir"
|
||||
$PY - "$D" "$REF" "$c" "$K" "$AFT" <<'PY'
|
||||
import sys,os,hashlib,struct
|
||||
d,ref,c,k,aft=sys.argv[1],sys.argv[2],sys.argv[3],int(sys.argv[4]),sys.argv[5]
|
||||
log=open(d+'/host.log',errors='replace').read()
|
||||
def tree(r):
|
||||
o={}
|
||||
for root,_,fs in os.walk(r):
|
||||
for f in fs: p=os.path.join(root,f); o[os.path.relpath(p,r)]=open(p,'rb').read()
|
||||
return o
|
||||
def d2s_ok(b):
|
||||
if len(b)<16: return False
|
||||
b=bytearray(b); n,c0=struct.unpack_from('<II',b,8); struct.pack_into('<I',b,12,0); s=0
|
||||
for x in b: s=(((s<<1)|(s>>31))+x)&0xffffffff
|
||||
return n==len(b) and s==c0
|
||||
com,a,work=tree(d+'/user/0'),tree(ref),tree(d+'/user/0.work')
|
||||
hit=('DM_TEST_%s:存档第 %d 次写' % (c.split(':')[0],k)) in log
|
||||
STASH='ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i'
|
||||
fail=c.startswith('FS_FAIL')
|
||||
exempt={'joe/joe.d2s','joe/joe.d2s.meta'} if k==3 else set()
|
||||
want=dict(a)
|
||||
if fail and k==1: want[STASH]=tree(aft)[STASH]; exempt=set()
|
||||
diff=sorted(f for f in set(want)|set(com) if f not in exempt and want.get(f)!=com.get(f))
|
||||
ok_d2s=d2s_ok(com.get('joe/joe.d2s',b''))
|
||||
torn=STASH if k==3 else 'joe/joe.d2s'
|
||||
if fail:
|
||||
rl=[l for l in log.splitlines() if '存档提交拒绝' in l]
|
||||
neg=len(rl)==1 and torn in rl[0] and '仍有存档文件开着' not in rl[0]
|
||||
if k==1:
|
||||
after=log[log.index('存档提交拒绝'):] if rl else ''
|
||||
nxt=after.count('(此前存档写 3 次)')==1 and after.count('存档提交 #')==1
|
||||
print(f' 下一个事务照常提交(拒绝之后恰 1 条成功提交且此前写 3 次):{nxt}'); neg=neg and nxt
|
||||
else: neg=len(work.get(torn,b'x'))==0
|
||||
ok=hit and not diff and ok_d2s and neg
|
||||
print(f"{'✓' if ok else '✗'} {c}:注入命中 {hit};已提交 {len(com)} 个文件,应同期望版 {len(want)-len(exempt)} 个、不同 {len(diff)} {diff[:3]};joe.d2s 自洽 {ok_d2s};负对照 {'拒绝日志恰 1 条且列出' if fail else '工作目录'} {torn} 0 字节 {neg}")
|
||||
sys.exit(0 if ok else 1)
|
||||
PY
|
||||
rc=$?
|
||||
if [ "$rc" != 0 ]; then bad=1; echo "$c 判据红;现场保留" >> "$RUN/KEEP"; echo "$c 判据红;现场保留" >> "$D/KEEP"; fi
|
||||
done
|
||||
[ $bad = 0 ] && echo "结论:存档事务回归 4/4 绿" || echo "结论:存档事务回归有红"
|
||||
exit $bad
|
||||
@@ -0,0 +1,123 @@
|
||||
# 带符号的反汇编:按 dynsym 定义符号与 PLT 导入名标注 bl/b/adrp 目标。
|
||||
# 用法:sdis.py <原映像 .orig.bin> <符号名|0x偏移> [条数=200]
|
||||
# sdis.py <原映像> --sym 0x偏移... 偏移 → 函数+偏移
|
||||
# sdis.py <原映像> --xref 0x地址... 谁用 adrp+add 引用了该地址
|
||||
# sdis.py <原映像> --fn 0x地址... 所在函数起点(eh_frame 函数表)
|
||||
# sdis.py <原映像> --find <子串> 列出名字含子串的定义符号
|
||||
# sdis.py <原映像> --callers <符号名> 列出直接 bl/b 到该符号的调用点
|
||||
# Disassembly with symbols: annotates bl/b/adrp targets with dynsym defined symbols and PLT import names.
|
||||
# Usage: sdis.py <original image .orig.bin> <symbol name|0xoffset> [count=200]
|
||||
# sdis.py <original image> --sym 0xoffset... offset → function+offset
|
||||
# sdis.py <original image> --xref 0xaddr... who references this address with adrp+add
|
||||
# sdis.py <original image> --fn 0xaddr... start of the containing function (eh_frame function table)
|
||||
# sdis.py <original image> --find <substring> list defined symbols whose name contains the substring
|
||||
# sdis.py <original image> --callers <symbol name> list call sites that directly bl/b to this symbol
|
||||
import struct, sys, bisect
|
||||
from capstone import *
|
||||
from capstone.arm64 import ARM64_OP_IMM
|
||||
|
||||
img = open(sys.argv[1], 'rb').read()
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); md.detail = True
|
||||
m = struct.unpack_from('<I', img, 4)[0]; dyn = m + struct.unpack_from('<i', img, m + 4)[0]
|
||||
t = {}; o = dyn
|
||||
while True:
|
||||
tag, v = struct.unpack_from('<qQ', img, o); o += 16
|
||||
if tag == 0: break
|
||||
t.setdefault(tag, v)
|
||||
SYM, STR = t[6], t[5]
|
||||
def cstr(off): return img[off:img.index(b'\0', off)].decode()
|
||||
nsym = (STR - SYM) // 24
|
||||
defs = {}; byaddr = {}
|
||||
for i in range(1, nsym):
|
||||
nm, info, oth, shn, val, sz = struct.unpack_from('<IBBHQQ', img, SYM + i * 24)
|
||||
if shn and val:
|
||||
n = cstr(STR + nm); defs[n] = (val, sz); byaddr.setdefault(val, n)
|
||||
funcs = sorted(byaddr.items()); addrs = [a for a, _ in funcs]
|
||||
# PLT:adrp x16 / ldr x17,[x16,#o] / add / br x17 → JUMP_SLOT 名
|
||||
# PLT: adrp x16 / ldr x17,[x16,#o] / add / br x17 → JUMP_SLOT name
|
||||
got = {}
|
||||
for i in range(0, t.get(2, 0), 24):
|
||||
off, info, add = struct.unpack_from('<QQq', img, t[23] + i)
|
||||
got[off] = cstr(STR + struct.unpack_from('<I', img, SYM + (info >> 32) * 24)[0])
|
||||
plt = {}
|
||||
def plt_scan():
|
||||
lo = t[23] # PLT 紧随 text 末尾附近;直接扫 text 里 adrp x16 序列 | The PLT is right near the end of text; scan text directly for adrp x16 sequences
|
||||
for o in range(0, len(img) - 16, 4):
|
||||
w = struct.unpack_from('<I', img, o)[0]
|
||||
if w & 0x9F00001F != 0x90000010: continue
|
||||
ins = list(md.disasm(img[o:o + 16], o))
|
||||
if len(ins) == 4 and ins[1].mnemonic == 'ldr' and ins[3].mnemonic == 'br':
|
||||
a = ins[0].operands[1].imm + ins[1].operands[1].mem.disp
|
||||
if a in got: plt[o] = got[a]
|
||||
def name(a):
|
||||
if a in plt: return 'PLT:' + plt[a]
|
||||
i = bisect.bisect_right(addrs, a) - 1
|
||||
if i < 0: return hex(a)
|
||||
return funcs[i][1] + ('' if a == funcs[i][0] else f'+{a - funcs[i][0]:#x}')
|
||||
|
||||
def fn_starts(): # eh_frame_hdr 二分表里的全部函数起点(升序) | All function starts in the eh_frame_hdr binary search table (ascending)
|
||||
m0 = struct.unpack_from('<I', img, 4)[0]
|
||||
ehs = m0 + struct.unpack_from('<i', img, m0 + 16)[0]
|
||||
ver, penc, cenc, tenc = img[ehs:ehs + 4]
|
||||
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
|
||||
o = ehs + 4; _, k = rd(o, penc); o += k; n, k = rd(o, cenc); o += k
|
||||
out = []
|
||||
for _ in range(n):
|
||||
a, k = rd(o, tenc); o += k; _, k = rd(o, tenc); o += k; out.append(a)
|
||||
return sorted(set(out))
|
||||
|
||||
def resolve(s):
|
||||
return int(s, 16) if s.startswith('0x') else defs[s][0]
|
||||
|
||||
if sys.argv[2] == '--sym': # sdis.py <映像> --sym 0x偏移... 逐个给出所在函数 | sdis.py <image> --sym 0xoffset... give the containing function for each one
|
||||
plt_scan()
|
||||
for a in sys.argv[3:]: print(a, name(int(a, 16)))
|
||||
sys.exit()
|
||||
if sys.argv[2] == '--xref': # sdis.py <映像> --xref 0x地址... 找 adrp+add/ldr 拼出该地址的指令 | sdis.py <image> --xref 0xaddr... find the instructions that build this address with adrp+add/ldr
|
||||
want = {int(a, 16) for a in sys.argv[3:]}
|
||||
textend = max(v + s for v, s in defs.values() if v < 0x10000000 and s)
|
||||
for o in range(0, min(len(img), textend), 4):
|
||||
w = struct.unpack_from('<I', img, o)[0]
|
||||
if w & 0x9F000000 != 0x90000000: continue
|
||||
rd = w & 31; imm = (((w >> 5) & 0x7FFFF) << 2) | ((w >> 29) & 3)
|
||||
if imm & (1 << 20): imm -= 1 << 21
|
||||
page = (o & ~0xFFF) + (imm << 12)
|
||||
for i in md.disasm(img[o + 4:o + 24], o + 4):
|
||||
ops = i.operands
|
||||
if i.mnemonic == 'add' and len(ops) == 3 and ops[1].reg and i.reg_name(ops[1].reg) == f'x{rd}' and ops[2].type == ARM64_OP_IMM:
|
||||
if page + ops[2].imm in want: print(f'{i.address:#x} {name(i.address)} -> {page + ops[2].imm:#x}')
|
||||
break
|
||||
sys.exit()
|
||||
if sys.argv[2] == '--fn': # sdis.py <映像> --fn 0x地址... 所在函数起点(eh_frame) | sdis.py <image> --fn 0xaddr... start of the containing function (eh_frame)
|
||||
st = fn_starts()
|
||||
for a in sys.argv[3:]:
|
||||
a = int(a, 16); k = bisect.bisect_right(st, a) - 1
|
||||
if k < 0 or k + 1 >= len(st): print(f'{a:#x} 不在函数表'); continue # 首函数前 / 末函数后(如改写区):单条报,不连累整批 | Before the first function / after the last function (e.g. the rewrite area): report it on its own, without dragging down the whole batch
|
||||
print(f'{a:#x} 函数 {st[k]:#x} +{a - st[k]:#x} 下一函数 {st[k + 1]:#x}')
|
||||
sys.exit()
|
||||
if sys.argv[2] == '--find':
|
||||
for n, (v, sz) in sorted(defs.items(), key=lambda x: x[1]):
|
||||
if sys.argv[3] in n: print(f'{v:#x} {sz:#x} {n}')
|
||||
sys.exit()
|
||||
if sys.argv[2] == '--callers':
|
||||
tgt = resolve(sys.argv[3]); textend = max(v + s for v, s in defs.values() if v < 0x10000000 and s) # 粗上界 | Coarse upper bound
|
||||
for o in range(0, min(len(img), textend), 4):
|
||||
w = struct.unpack_from('<I', img, o)[0]
|
||||
if w >> 26 in (0x25, 0x05) and o + ((((w & 0x3ffffff) ^ 0x2000000) - 0x2000000) * 4) == tgt:
|
||||
print(f'{o:#x} {name(o)}')
|
||||
sys.exit()
|
||||
plt_scan()
|
||||
a = resolve(sys.argv[2]); n = int(sys.argv[3]) if len(sys.argv) > 3 else 200
|
||||
for ins in md.disasm(img[a:a + n * 4], a):
|
||||
ann = ''
|
||||
if ins.mnemonic in ('bl', 'b') or ins.mnemonic.startswith('b.') or ins.mnemonic in ('cbz', 'cbnz', 'tbz', 'tbnz', 'adr'):
|
||||
op = ins.operands[-1]
|
||||
if op.type == ARM64_OP_IMM: ann = ' ; ' + name(op.imm)
|
||||
print(f'{ins.address:#9x} {ins.mnemonic:8s} {ins.op_str}{ann}')
|
||||
if ins.mnemonic == 'ret' and n > 60 and ins.address > a + 8 and len(sys.argv) <= 3: break
|
||||
@@ -0,0 +1,110 @@
|
||||
# 剪口证据:列被剪调用树的全部同步原语与对外副作用(把「剪口证据只证结果相同」这条教训工具化)。
|
||||
# 用法:sideeff.py <原映像 .orig.bin> <根偏移>[,<根偏移>...] [--depth N]
|
||||
# 从根沿直接 bl/b(尾调用)走遍调用树(函数边界取 eh_frame),输出:
|
||||
# ① 每个导入(PLT)调用:名字 + 调用点 + 所在函数(同步原语 / 文件 / 线程类单独标出)
|
||||
# ② 每个间接调用点 blr / br xN(非跳表):需人工逐条解析目标
|
||||
# ③ 遍历到的函数数
|
||||
# 只做静态枚举,不判断「成对 / 无人等待」——那一步须按清单逐条人工证。
|
||||
# Cut evidence: lists all synchronization primitives and external side effects of the cut call tree (turning the lesson "cut evidence only proves the result is the same" into a tool).
|
||||
# Usage: sideeff.py <original image .orig.bin> <root offset>[,<root offset>...] [--depth N]
|
||||
# Walks the whole call tree from the roots along direct bl/b (tail calls) (function boundaries from eh_frame) and outputs:
|
||||
# ① every import (PLT) call: name + call site + containing function (synchronization primitive / file / thread classes are marked separately)
|
||||
# ② every indirect call site blr / br xN (not a jump table): the target must be resolved manually one by one
|
||||
# ③ the number of functions traversed
|
||||
# Static enumeration only, with no judgment of "paired / nobody waiting" -- that step must be proven manually item by item from the list.
|
||||
import struct, sys, bisect, re
|
||||
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
|
||||
|
||||
img = open(sys.argv[1], 'rb').read()
|
||||
roots = [int(x, 16) for x in sys.argv[2].split(',')]
|
||||
maxd = int(sys.argv[sys.argv.index('--depth') + 1]) if '--depth' in sys.argv else 64
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
|
||||
|
||||
# ---- 动态段:符号表 / PLT 槽名(同 sdis.py)
|
||||
# ---- Dynamic section: symbol table / PLT slot names (same as sdis.py)
|
||||
m = struct.unpack_from('<I', img, 4)[0]
|
||||
dyn, _, _, ehs, ehe, _ = [m + x for x in struct.unpack_from('<6i', img, m + 4)]
|
||||
t = {}; o = dyn
|
||||
while True:
|
||||
tag, v = struct.unpack_from('<qQ', img, o); o += 16
|
||||
if tag == 0: break
|
||||
t.setdefault(tag, v)
|
||||
SYM, STR = t[6], t[5]
|
||||
def cstr(off): return img[off:img.index(b'\0', off)].decode()
|
||||
got = {}
|
||||
for i in range(0, t.get(2, 0), 24):
|
||||
off, info, _ = struct.unpack_from('<QQq', img, t[23] + i)
|
||||
got[off] = cstr(STR + struct.unpack_from('<I', img, SYM + (info >> 32) * 24)[0])
|
||||
|
||||
# ---- eh_frame_hdr 函数起点
|
||||
# ---- eh_frame_hdr function starts
|
||||
def rd(o, enc, base):
|
||||
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 += base
|
||||
return v, sz
|
||||
_, ptrenc, cntenc, tblenc = img[ehs:ehs + 4]
|
||||
o = ehs + 4; _, s = rd(o, ptrenc, ehs); o += s; n, s = rd(o, cntenc, ehs); o += s
|
||||
starts = set()
|
||||
for _ in range(n):
|
||||
a, s = rd(o, tblenc, ehs); o += s; _, s = rd(o, tblenc, ehs); o += s; starts.add(a)
|
||||
starts = sorted(starts)
|
||||
def fbounds(a):
|
||||
i = bisect.bisect_right(starts, a) - 1
|
||||
return starts[i], starts[i + 1] if i + 1 < len(starts) else a + 4
|
||||
|
||||
# ---- PLT 桩:adrp x16 / ldr x17,[x16,#o] / add / br x17
|
||||
# ---- PLT stubs: adrp x16 / ldr x17,[x16,#o] / add / br x17
|
||||
plt = {}
|
||||
def plt_name(a):
|
||||
if a in plt: return plt[a]
|
||||
w = list(md.disasm(img[a:a + 12], a)); name = None
|
||||
if len(w) >= 2 and w[0].mnemonic == 'adrp' and w[0].op_str.startswith('x16') and w[1].mnemonic == 'ldr' and 'x17' in w[1].op_str:
|
||||
page = int(w[0].op_str.split('#')[1], 16); off = int(re.search(r'#(0x[0-9a-f]+|\d+)\]', w[1].op_str).group(1), 0)
|
||||
name = got.get(page + off)
|
||||
plt[a] = name; return name
|
||||
|
||||
SYNC = re.compile(r'Mutex|Condition|Semaphore|Event|Barrier|ReaderWriter|Lock|Signal|Wait|Thread|Sleep|Yield|Fiber|Message|Queue|Atomic|futex|cond|sem_', re.I)
|
||||
IO = re.compile(r'File|fopen|fwrite|fclose|Write|Flush|Mount|Save|Commit|Directory|Create|Delete|Rename|socket|send|connect|Notify|Event', re.I)
|
||||
|
||||
seen = {}; imports = []; indirect = []; parent = {}
|
||||
stack = [(r, 0, None) for r in roots]
|
||||
while stack:
|
||||
a, d, par = stack.pop()
|
||||
lo, hi = fbounds(a)
|
||||
if lo in seen: continue
|
||||
seen[lo] = d; parent[lo] = par
|
||||
code = img[lo:hi]
|
||||
for ins in md.disasm(code, lo):
|
||||
mn = ins.mnemonic
|
||||
if mn in ('bl', 'b') and ins.op_str.startswith('#'):
|
||||
tgt = int(ins.op_str[1:], 16)
|
||||
if mn == 'b' and lo <= tgt < hi: continue # 函数内跳转 | Jump within the function
|
||||
nm = plt_name(tgt)
|
||||
if nm: imports.append((nm, ins.address, lo)); continue
|
||||
if d + 1 <= maxd: stack.append((tgt, d + 1, (lo, ins.address)))
|
||||
elif mn in ('blr', 'br') and not ins.op_str.startswith('x16') and not ins.op_str.startswith('x17'):
|
||||
indirect.append((ins.address, lo, mn + ' ' + ins.op_str))
|
||||
|
||||
print(f'根 {",".join(hex(r) for r in roots)}:遍历函数 {len(seen)} 个(深度上限 {maxd})')
|
||||
def cat(nm): return '同步' if SYNC.search(nm) else ('外部I/O' if IO.search(nm) else '其它')
|
||||
from collections import defaultdict
|
||||
by = defaultdict(list)
|
||||
for nm, at, fn in imports: by[(cat(nm), nm)].append((at, fn))
|
||||
for (c, nm), lst in sorted(by.items()):
|
||||
print(f'[{c}] {nm} ×{len(lst)}:' + ' '.join(f'{hex(at)}@{hex(fn)}' for at, fn in lst[:12]) + (' …' if len(lst) > 12 else ''))
|
||||
print(f'间接调用 {len(indirect)} 处(br 含跳表,需人工区分):')
|
||||
for at, fn, s in indirect[:200]: print(f' {hex(at)} 在 {hex(fn)}:{s}')
|
||||
|
||||
def path(fn):
|
||||
out = []
|
||||
while fn is not None and parent.get(fn) is not None:
|
||||
pf, at = parent[fn]; out.append(f'{hex(pf)}@{hex(at)}'); fn = pf
|
||||
return ' ← '.join(out)
|
||||
if '--paths' in sys.argv:
|
||||
print('同步 / 外部 I/O 导入的调用链(被调函数 ← 调用者@调用点 …,深度优先首次发现的那条):')
|
||||
done = set()
|
||||
for nm, at, fn in imports:
|
||||
if cat(nm) == '其它' or (nm, fn) in done: continue
|
||||
done.add((nm, fn)); print(f' {nm} 在 {hex(fn)} ← {path(fn)}')
|
||||
@@ -0,0 +1,23 @@
|
||||
import struct,re
|
||||
from capstone import *
|
||||
md=Cs(CS_ARCH_ARM64,CS_MODE_ARM)
|
||||
TEXT_END=0x1b786a0
|
||||
def scan(img,lo,hi):
|
||||
out=set()
|
||||
for o in range(lo,hi,4):
|
||||
for i in md.disasm(img[o:o+4],o):
|
||||
if re.search(r'\b[xw]18\b',i.op_str) or 'tpidr_el0' in i.op_str: out.add(o)
|
||||
return out
|
||||
orig=open('main.bin','rb').read(); pat=open('main.patched.bin','rb').read()
|
||||
A=scan(orig,0,TEXT_END)
|
||||
done=set(); win=[]
|
||||
for l in open('sites.tsv'):
|
||||
f=l.split()
|
||||
if len(f)==3: win.append((int(f[0],16),int(f[2],16)))
|
||||
else: done.add(int(f[0],16))
|
||||
inwin=lambda a:any(lo<=a<hi for lo,hi in win)
|
||||
miss=sorted(a for a in A if a not in done and not inwin(a))
|
||||
print('orig text x18/tpidr sites',len(A),'covered',len(done),'windows',len(win),'MISSED',len(miss),[hex(x) for x in miss[:10]])
|
||||
P=scan(pat,0,TEXT_END); left=sorted(a for a in P if not inwin(a))
|
||||
print('patched text remaining (outside windows)',len(left),[hex(x) for x in left[:10]])
|
||||
PO=0x3220000; Q=scan(pat,PO,len(pat)); print('patch area x18/tpidr refs',len(Q))
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# 启动块清单:从一局 DM_TACTCHK 记录(每次 TACT zlib 块解码一行:输入开头16字节hex \t 输入长度 \t 输出长度 \t 输出MD5 \t 发起线程句柄)
|
||||
# 反查每块在 RomFS 存储里的位置,按首次请求顺序输出,同一块只留首次(mini A/B:去重不影响预取命中;按偏移排序则 ④ 慢约 0.07 s,顺序不能改)。宿主 DM_TACT_PREFETCH 按它提前解码(只是性能提示:块与清单不符时宿主退回原路径)。
|
||||
# 输出每行:数据文件名 \t 块内容偏移('Z' 之后) \t 压缩长度 \t 解码长度 \t 压缩数据开头16字节hex(宿主查缓存的键,免得启动时再读盘) \t 发起线程句柄(宿主按线程分流)
|
||||
# 文件头一行「# BUILD_ID\t<main 构建号>」(取自 ExeFS/main 的 NSO 头 0x40–0x50,与改写器 cuts.tsv 同口径):清单随产物目录(out/<版本>-rN/bootlist.tsv),
|
||||
# 宿主核对产物 main.cuts.tsv 的构建号,不符整段不启用。出新 r 版本时与产物一起重出。
|
||||
# 产物不再每版重录(记录有竞态:同产物三次记录块集合不同):输出入库为 dm/data/bootlist_<构建号>.tsv,patch_nso.py 出 main 时拷进产物目录;
|
||||
# 只在构建号变化或主动改进时重录,提交附 mini A/B 读数。
|
||||
# 用法:tact_bootlist.py <DM_TACTCHK 记录> <输出清单> [RomFS 目录] [ExeFS/main]
|
||||
# Boot block list: from the DM_TACTCHK record of one run (one line per TACT zlib block decode: first 16 input bytes hex \t input length \t output length \t output MD5 \t initiating thread handle)
|
||||
# looks up each block's position in the RomFS storage and outputs them in first-request order, keeping only the first occurrence of a block (A/B on the second Mac: deduplication does not affect prefetch hits; sorting by offset makes ④ about 0.07 s slower, so the order must not be changed). The host's DM_TACT_PREFETCH decodes ahead of time according to it (a performance hint only: when a block does not match the list the host falls back to the original path).
|
||||
# Each output line: data file name \t block content offset (after 'Z') \t compressed length \t decoded length \t first 16 bytes of compressed data hex (the key the host uses to look up its cache, sparing another disk read at startup) \t initiating thread handle (the host dispatches by thread)
|
||||
# One header line at the top of the file, "# BUILD_ID\t<main build ID>" (taken from 0x40–0x50 of the NSO header of ExeFS/main, same convention as the rewriter's cuts.tsv): the list goes with the build output directory (out/<version>-rN/bootlist.tsv),
|
||||
# the host checks it against the build ID in the build output's main.cuts.tsv, and on mismatch the whole thing is not enabled. When a new r version is issued it is regenerated together with the build output.
|
||||
# Build outputs are no longer re-recorded for every version (recording is racy: three recordings of the same build output gave different block sets): the output is checked in as dm/data/bootlist_<build ID>.tsv, and patch_nso.py copies it into the build output directory when producing main;
|
||||
# re-record only when the build ID changes or for a deliberate improvement, and attach A/B readings from the second Mac to the commit.
|
||||
# Usage: tact_bootlist.py <DM_TACTCHK record> <output list> [RomFS dir] [ExeFS/main]
|
||||
import sys, os, mmap, struct, zlib, hashlib, collections
|
||||
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)
|
||||
chk, out = sys.argv[1], sys.argv[2]
|
||||
R = (sys.argv[3] if len(sys.argv) > 3 else os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS')) + '/data'
|
||||
NSO = sys.argv[4] if len(sys.argv) > 4 else os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/ExeFS/main')
|
||||
BUILD_ID = open(NSO, 'rb').read(0x50)[0x40:0x50].hex()
|
||||
maps = {}
|
||||
def mm(fn):
|
||||
if fn not in maps: fh = open(f'{R}/{fn}', 'rb'); maps[fn] = (fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ))
|
||||
return maps[fn][1]
|
||||
idx = collections.defaultdict(list) # (开头16字节hex, 压缩长) → [(文件, 偏移)],同键可多处(撞键) | (first 16 bytes hex, compressed length) → [(file, offset)]; the same key may be in several places (key collision)
|
||||
for l in open(f'{R}/build_manifest.psv', encoding='utf-8'):
|
||||
if l.startswith(('FileId', '#')): continue
|
||||
f = l.rstrip('\n').split('|')
|
||||
if len(f) < 10: continue
|
||||
fn = f'{int(f[2]):02d}-{int(f[3]):08d}.data'; off = int(f[6][22:32], 16); es = int(f[7]); enc = f[8]; m = mm(fn)
|
||||
if enc == 'z': idx[(m[off:off + 16].hex(), es)].append((fn, off)); continue
|
||||
if enc.startswith('b') and m[off:off + 4] == b'BLTE':
|
||||
hs = struct.unpack_from('>I', m, off + 4)[0]
|
||||
if hs == 0: continue
|
||||
nc = struct.unpack_from('>I', m, off + 8)[0] & 0xffffff; p = off + hs
|
||||
for k in range(nc):
|
||||
ce, cd = struct.unpack_from('>II', m, off + 12 + k * 24)
|
||||
if m[p:p + 1] == b'Z': idx[(m[p + 1:p + 17].hex(), ce - 1)].append((fn, p + 1))
|
||||
p += ce
|
||||
rows = []; seen = set(); miss = amb = 0
|
||||
for l in open(chk):
|
||||
q = l.rstrip('\n').split('\t')
|
||||
if len(q) < 4: continue
|
||||
if len(q[0]) != 32 or len(q[3]) != 32: continue # 进程到点退出时没写完的残行 | Partial line left unfinished when the process exited at its deadline
|
||||
h, n, dl, md = q[0], int(q[1]), int(q[2]), q[3]; th = q[4] if len(q) > 4 and q[4].startswith('0x') else '0'
|
||||
cands = idx.get((h, n), [])
|
||||
if len(cands) > 1: amb += 1
|
||||
hit = None
|
||||
for fn, off in cands: # 同键多处:按输出 MD5 选中真正那一块 | Same key in several places: pick the real block by output MD5
|
||||
if len(cands) == 1 or hashlib.md5(zlib.decompress(mm(fn)[off:off + n])).hexdigest() == md: hit = (fn, off); break
|
||||
if not hit: miss += 1; continue
|
||||
if hit in seen: continue
|
||||
seen.add(hit)
|
||||
rows.append(f'{hit[0]}\t{hit[1]}\t{n}\t{dl}\t{h}\t{th}')
|
||||
with open(out, 'w') as f: f.write(f'# BUILD_ID\t{BUILD_ID}\n' + '\n'.join(rows) + '\n')
|
||||
print(f'启动块清单(main 构建号 {BUILD_ID}){len(rows)} 块(撞键消歧 {amb},查不到 {miss}):压缩 {sum(int(r.split()[2]) for r in rows)/1048576:.1f} MiB → 解码 {sum(int(r.split()[3]) for r in rows)/1048576:.1f} MiB → {out}')
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
import unittest
|
||||
|
||||
from l3reg import fit
|
||||
|
||||
|
||||
class L3RegressionTest(unittest.TestCase):
|
||||
def test_linear_samples_use_ticks_and_project_total_growth(self):
|
||||
rows = [(tick, int(100 + 0.5 * tick), int(200 + 0.25 * tick), 7, 300, 8, 9) for tick in (100, 200, 400)]
|
||||
expected_slope = 500
|
||||
expected_growth = 500 * (216000 - 400) / 1000 + 300 - 150
|
||||
|
||||
slope, growth = fit(rows, 1, 216000)
|
||||
|
||||
self.assertAlmostEqual(slope, expected_slope, places=6)
|
||||
self.assertAlmostEqual(growth, expected_growth, places=6)
|
||||
|
||||
def test_constant_samples_have_zero_slope(self):
|
||||
rows = [(tick, 123, 456, 7, 300, 8, 9) for tick in (100, 200, 400)]
|
||||
|
||||
slope, growth = fit(rows, 1, 216000)
|
||||
|
||||
self.assertEqual(slope, 0)
|
||||
self.assertEqual(growth, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,22 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
static void *spin(void*a){volatile uint64_t x=0;for(;;)x++;return 0;}
|
||||
static void *probe(void*a){
|
||||
uint64_t orig; __asm__ volatile("mrs %0, tpidr_el0":"=r"(orig));
|
||||
uint64_t mark=0x5A5A123400000000ull|(uint64_t)(uintptr_t)a;
|
||||
long changed=0,n=0;
|
||||
for(int i=0;i<20000;i++){
|
||||
__asm__ volatile("msr tpidr_el0, %0"::"r"(mark));
|
||||
for(volatile int k=0;k<20000;k++);
|
||||
if(i%50==0) usleep(100);
|
||||
uint64_t v; __asm__ volatile("mrs %0, tpidr_el0":"=r"(v));
|
||||
n++; if(v!=mark) changed++;
|
||||
}
|
||||
__asm__ volatile("msr tpidr_el0, %0"::"r"(orig));
|
||||
printf("thread %ld: orig=%llx changed %ld/%ld\n",(long)(uintptr_t)a,orig,changed,n);
|
||||
return 0;}
|
||||
int main(){pthread_t t[40];for(int i=0;i<24;i++)pthread_create(&t[i],0,spin,0);
|
||||
pthread_t p[4];for(long i=0;i<4;i++)pthread_create(&p[i],0,probe,(void*)i);
|
||||
for(int i=0;i<4;i++)pthread_join(p[i],0);return 0;}
|
||||
@@ -0,0 +1,20 @@
|
||||
# Windows 上让出包工具链的每个 Python 进程写文本文件时都用 \n 换行(tools/d2rm_pack.py 把本目录放进 PYTHONPATH,
|
||||
# Python 启动时会自动加载名叫 sitecustomize 的模块,子进程、进程池里的进程也一样)。
|
||||
# 为什么:Windows 的文本模式缺省把 \n 写成 \r\n。工具链写出的表、清单、着色器源码与说明都要进安装包,多出来的 \r 会让
|
||||
# 同样的输入在 Windows 上出的包与 macOS / Linux 上的不一样,手机上读表的代码也不认 \r。
|
||||
# 为什么放在这一处:出库链的几个脚本内容参与翻译链版本,不能逐个去加 newline 参数;在入口统一处理,别的系统上本文件什么都不做。
|
||||
# On Windows, makes every Python process of the packaging tool chain write text files with LF line endings (tools/d2rm_pack.py puts this directory on PYTHONPATH;
|
||||
# Python loads a module named sitecustomize automatically at startup, in child processes and pool workers too).
|
||||
# Why: Windows text mode writes LF as CRLF by default. The tables, lists, shader sources and descriptions written by the tool chain all go into the install package; the extra \r would make
|
||||
# the package built on Windows differ from the one built on macOS / Linux from the same input, and the table readers on the phone do not accept \r.
|
||||
# Why here: the contents of the shader chain scripts feed the chain version, so a newline argument cannot be added to them one by one; it is handled once at the entry, and this file does nothing on other systems.
|
||||
import builtins, io, os
|
||||
|
||||
if os.name == 'nt':
|
||||
_open = io.open
|
||||
|
||||
def _lf_open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
|
||||
if newline is None and 'b' not in mode and '+' not in mode and any(c in mode for c in 'wax'): newline = '\n'
|
||||
return _open(file, mode, buffering, encoding, errors, newline, closefd, opener)
|
||||
|
||||
builtins.open = io.open = _lf_open
|
||||
@@ -0,0 +1,29 @@
|
||||
import pickle,struct,sys
|
||||
from capstone import *
|
||||
from capstone.arm64 import *
|
||||
img=open('main.bin','rb').read()
|
||||
starts=pickle.load(open('starts.pkl','rb'))
|
||||
TEXT=0x1b786a0
|
||||
md=Cs(CS_ARCH_ARM64,CS_MODE_ARM);md.detail=True
|
||||
lo,hi=int(sys.argv[1]),int(sys.argv[2])
|
||||
res=[]
|
||||
for i in range(lo,min(hi,len(starts))):
|
||||
a=starts[i]; b=starts[i+1] if i+1<len(starts) else TEXT
|
||||
if a>=TEXT: continue
|
||||
used=set();x18=0;n=0;bad=0
|
||||
for ins in md.disasm(img[a:b],a):
|
||||
n+=1
|
||||
try: r,w=ins.regs_access()
|
||||
except Exception: bad+=1;continue
|
||||
for reg in list(r)+list(w):
|
||||
nm=ins.reg_name(reg)
|
||||
if nm and nm[0] in 'xw' and nm[1:].isdigit(): used.add(int(nm[1:]))
|
||||
elif nm in('fp',):used.add(29)
|
||||
elif nm in('lr',):used.add(30)
|
||||
if 18 in used and x18==0: pass
|
||||
x18+=sum(1 for reg in list(r)+list(w) if ins.reg_name(reg) in('x18','w18'))
|
||||
if x18:
|
||||
free_cs=[k for k in range(9,18) if k not in used]
|
||||
free_ce=[k for k in range(19,29) if k not in used]
|
||||
res.append((a,b-a,n,x18,len(free_cs),len(free_ce),bad))
|
||||
pickle.dump(res,open(f'x18_{lo}.pkl','wb'))
|
||||
@@ -0,0 +1,35 @@
|
||||
import pickle,struct,bisect,sys
|
||||
from capstone import *
|
||||
img=open('sdk.bin','rb').read();md=Cs(CS_ARCH_ARM64,CS_MODE_ARM);md.detail=True
|
||||
syms=pickle.load(open('sdk_syms.pkl','rb'))
|
||||
funcs=sorted((v,k) for k,(v,s) in syms.items() if v<0x58d930)
|
||||
addrs=[f[0] for f in funcs]
|
||||
def fname(a):
|
||||
i=bisect.bisect_right(addrs,a)-1; return f'{funcs[i][1]}+{a-funcs[i][0]:#x}'
|
||||
m=struct.unpack_from('<I',img,4)[0]; dyn=m+struct.unpack_from('<i',img,m+4)[0]
|
||||
t={};o=dyn
|
||||
while True:
|
||||
a,v=struct.unpack_from('<qQ',img,o);o+=16
|
||||
if a==0:break
|
||||
t.setdefault(a,v)
|
||||
sym,strt=t[6],t[5]
|
||||
got={}
|
||||
for i in range(0,t[2],24):
|
||||
off,info,add=struct.unpack_from('<QQq',img,t[23]+i); si=info>>32
|
||||
nm=struct.unpack_from('<I',img,sym+si*24)[0]; got[off]=img[strt+nm:img.index(b'\0',strt+nm)].decode()
|
||||
plt={}
|
||||
for o in range(0,0x58d930,4):
|
||||
w=struct.unpack_from('<I',img,o)[0]
|
||||
if w&0x9F00001F==0x90000010:
|
||||
i2=list(md.disasm(img[o:o+16],o))
|
||||
if len(i2)==4 and i2[3].mnemonic=='br' and i2[1].mnemonic=='ldr':
|
||||
page=i2[0].operands[1].imm; off=i2[1].operands[1].mem.disp
|
||||
if page+off in got: plt[o]=got[page+off]
|
||||
want={a:n for a,n in plt.items() if n in sys.argv[1:]}
|
||||
print(want)
|
||||
for o in range(0,0x58d930,4):
|
||||
w=struct.unpack_from('<I',img,o)[0]
|
||||
if w>>26==0x25 or w>>26==0x05:
|
||||
tgt=o+(((w&0x3ffffff)^0x2000000)-0x2000000)*4
|
||||
if tgt in want: print('call',want[tgt],'from',fname(o))
|
||||
pickle.dump(plt,open('sdk_plt.pkl','wb'))
|
||||
Reference in New Issue
Block a user