chore(repo): archive the prototype and document hangar requests

Archive the earlier backend, client, build, and patch definitions. Document
the stock login and profile requests required to reach the hangar, along
with the profile structure and the relevant configuration blocks.
This commit is contained in:
N0VAN0M4LY committed 2026-11-24 00:07:51 +08:00
1 parent 0e4af609c8
commit 7b6d8973d1
34 files changed
-1655

No files matched your search

-4
View File
@@ -8,7 +8,3 @@
| 目录 | 内容 |
|---|---|
| `backend/` | 本地服务(TypeScript) |
| `client/` | 对原版文件的改动记录 |
| `exe-patches/` | exe 补丁定义 |
| `tools/` | Python 工具:数据包读写、构建、exe 补丁引擎、脚本检查、静态分析 |
@@ -1,14 +0,0 @@
{
"method": "signature",
"section": ".text",
"how": [
"整函数开头 0x60 字节的掩码特征。rip 相对操作数里的地址、以及相对跳转的目标,都已通配(authoring.py 生成)。",
"为什么要用这么长的特征:这个函数的开头是很常见的函数序言,只取十几个字节会匹配到几十处。",
"特征里的 56 52 46 78 是容器魔数 \"VRFx\" 的比较,和我们自己的脚本包读写实现对得上,是一个语义锚点,不太可能随版本变化。",
"备用:开头 0x40 字节在 2.61.0.37 上同样唯一命中。如果将来 0x60 的特征失配,先用 0x40 核对是不是只有后半段变了。",
"在 2.61.0.37 原版 aces.exe 上唯一命中 0x4073d30,函数范围 0x4073d30-0x407497d。"
],
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 68 01 00 00 0f 29 b4 24 50 01 00 00 48 8b 7a 40 48 85 ff 74 ?? 8b 5a 48 85 db 74 ?? 8b 42 08 83 f8 10 73 ?? 31 c0 0f 28 b4 24 50 01 00 00 48 81 c4 68 01 00 00 5b 5d 5f 5e 41 5c 41 5d 41 5e 41 5f c3 48 89 ce 4c 8b 32 41 81 3e 56 52 46 78 75 ??"
}
@@ -1,41 +0,0 @@
{
"id": "startup/skip-resource-archive-signature-check",
"title": "让资源包签名校验直接返回通过",
"program_behaviour": {
"stock": "挂载 .vromfs.bin 资源包时,程序调用一个函数校验包尾的 256 字节签名。返回 0(不合法)时,调用方跳到失败分支,这个包不会被挂载。",
"patched": "这个校验函数一进去就返回「通过」,不再读取签名。"
},
"derivation": {
"requirement": "功能清单 A「离线启动」。我们必须把适配层放进界面脚本包,这就要重新打包 gui.vromfs.bin。",
"cause": "签名用 Gaijin 的私钥生成,我们无法为重新打包的内容生成有效签名。校验失败是运行时的硬拦截,不是只写日志的断言。",
"lighter_options_ruled_out": [
"原生自带:不行。校验在挂载路径上无条件执行,没有开关。",
"适配层:不行。适配层是脚本,要先被加载才能运行,而脚本就在这个被拒绝的包里——循环依赖。",
"订阅引擎事件:不适用,这是加载资源的环节,不是对局事件。",
"后端:不适用,程序加载本地资源时不会问后端。",
"客户端脚本:同适配层,脚本此时还没有被加载。"
],
"conclusion": "只能改 exe。",
"if_not_applied": "重新打包的界面脚本包不会被挂载,适配层根本不会运行,游戏进不去。"
},
"why_this_site": [
"校验函数的返回值直接控制流程:调用方是 call、test al,al、je 失败分支。让函数立即返回 1,就等于「签名通过」。",
"改函数入口只需要 3 字节、一个位置;改调用点要动 3 个位置(implementation notes 附录第 2 节列出的 3 处)。改一处更小、更稳。",
"打了补丁后这个函数不再调用任何东西,是个立即返回的叶子函数,所以不需要补异常展开信息。"
],
"features": ["A-离线启动"],
"requires": [],
"evidence": ["implementation notes#2-资源包校验是运行时硬拦截"],
"verified_on": ["2.61.0.37"],
"edit": {
"offset": 0,
"asm": ["mov al, 1", "ret"],
"bytes": "b001c3",
"expect_original": "415741"
}
}
-21
View File
@@ -1,21 +0,0 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "wtotools"
version = "0.1.0"
description = "Developer and installer tools for the War Thunder offline rewrite: script archives, exe patches, data extraction."
requires-python = ">=3.12"
dependencies = [
"pefile>=2024.8.26",
"capstone>=5.0",
"keystone-engine>=0.9.2",
"zstandard>=0.22",
]
[project.scripts]
wtotools = "wtotools.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
-7
View File
@@ -1,7 +0,0 @@
"""Tools for the War Thunder offline rewrite.
Subpackages:
- vromfs: read and write the game's .vromfs.bin script/resource archives
- pe: read-only view of a PE executable (address mapping, sections, functions)
- exepatch: locate and apply declarative exe patches from the exe-patches/ tree
"""
-21
View File
@@ -1,21 +0,0 @@
"""Assemble the files that get deployed into a game copy.
Modules:
- overrides: declarative edit records for stock files (anchor + insert/replace)
- script_archive: produce a new .vromfs.bin from the stock one plus our overrides and added files
Nothing here reads or writes a game folder; callers pass bytes and get bytes back.
"""
from .errors import BuildError, OverrideError
from .overrides import OverrideRecord, apply_edits, load_overrides
from .script_archive import ScriptArchiveReport, build_script_archive
__all__ = [
"BuildError",
"OverrideError",
"OverrideRecord",
"ScriptArchiveReport",
"apply_edits",
"build_script_archive",
"load_overrides",
]
-10
View File
@@ -1,10 +0,0 @@
class BuildError(Exception):
"""A build input is unusable, so nothing was produced."""
class OverrideError(BuildError):
"""An override record does not fit the stock file it targets.
Raised instead of writing a guessed result: the caller reports which override
failed and which features depend on it, and the player decides how to proceed.
"""
-148
View File
@@ -1,148 +0,0 @@
"""Declarative edits to stock game files.
We keep our changes to stock files as records rather than as modified copies, so the
repository holds no game content and the same record can be applied to whatever game
version the player has. Each record is one JSON file:
{
"archive": "gui.vromfs.bin",
"path": "scripts/main.nut",
"why": "load the offline adapter before any interface code runs",
"features": ["A-offline-start"],
"edits": [
{"kind": "insert-after", "anchor": "#default:forbid-root-table\\n", "text": "...\\n"}
]
}
Every edit is anchored on text that must occur exactly once. If an anchor is missing or
ambiguous the record is refused (OverrideError) and nothing is written, so a game update
that moves the anchor produces a clear report instead of a corrupted file.
Records are written with plain "\\n" line breaks. Stock files use CRLF in places and LF in
others, sometimes within one file, so the engine matches the anchor against whichever form
the file actually uses and writes the inserted text the same way. The rest of the file is
left byte for byte as it was.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from .errors import OverrideError
INSERT_AFTER = "insert-after"
INSERT_BEFORE = "insert-before"
REPLACE = "replace"
_KINDS = (INSERT_AFTER, INSERT_BEFORE, REPLACE)
@dataclass(frozen=True)
class Edit:
kind: str
anchor: str
text: str
@dataclass(frozen=True)
class OverrideRecord:
archive: str
path: str
why: str
features: tuple[str, ...]
edits: tuple[Edit, ...]
source: Path | None = None
@property
def label(self) -> str:
return f"{self.archive}:{self.path}"
def load_overrides(directory: Path) -> list[OverrideRecord]:
"""Read every *.json override record under `directory`, sorted by file name."""
records = [_parse_record(path, json.loads(path.read_text("utf-8"))) for path in sorted(directory.rglob("*.json"))]
_reject_duplicate_targets(records)
return records
def apply_edits(text: str, edits: tuple[Edit, ...], label: str) -> str:
"""Apply every edit to `text`, or raise OverrideError without changing anything."""
for index, edit in enumerate(edits):
text = _apply_one(text, edit, f"{label} edit {index + 1}")
return text
def _apply_one(text: str, edit: Edit, where: str) -> str:
newline = _resolve_newline(text, edit.anchor, where)
anchor = edit.anchor.replace("\n", newline)
replacement = edit.text.replace("\n", newline)
occurrences = text.count(anchor)
if occurrences == 0:
raise OverrideError(f"{where}: anchor not found in the stock file: {edit.anchor!r}")
if occurrences > 1:
raise OverrideError(f"{where}: anchor occurs {occurrences} times, so the position is ambiguous: {edit.anchor!r}")
if edit.kind == REPLACE:
return text.replace(anchor, replacement)
if replacement in text:
raise OverrideError(f"{where}: the text to insert is already present; the file looks already modified")
position = text.index(anchor)
if edit.kind == INSERT_AFTER:
position += len(anchor)
return text[:position] + replacement + text[position:]
def _resolve_newline(text: str, anchor: str, where: str) -> str:
"""Which line break this file uses where the anchor sits."""
if "\n" not in anchor:
return _dominant_newline(text)
matching = [newline for newline in ("\r\n", "\n") if anchor.replace("\n", newline) in text]
if len(matching) > 1:
raise OverrideError(f"{where}: anchor matches with both CRLF and LF line breaks, so the position is ambiguous")
return matching[0] if matching else _dominant_newline(text)
def _dominant_newline(text: str) -> str:
crlf = text.count("\r\n")
return "\r\n" if crlf >= text.count("\n") - crlf else "\n"
def _parse_record(source: Path, raw: object) -> OverrideRecord:
if not isinstance(raw, dict):
raise OverrideError(f"{source}: expected a JSON object")
missing = [key for key in ("archive", "path", "why", "edits") if key not in raw]
if missing:
raise OverrideError(f"{source}: missing required key(s): {', '.join(missing)}")
edits = tuple(_parse_edit(source, item) for item in raw["edits"])
if not edits:
raise OverrideError(f"{source}: the record has no edits")
return OverrideRecord(
archive=str(raw["archive"]),
path=str(raw["path"]),
why=str(raw["why"]),
features=tuple(str(item) for item in raw.get("features", ())),
edits=edits,
source=source,
)
def _parse_edit(source: Path, raw: object) -> Edit:
if not isinstance(raw, dict):
raise OverrideError(f"{source}: every edit must be a JSON object")
kind = str(raw.get("kind", ""))
if kind not in _KINDS:
raise OverrideError(f"{source}: edit kind must be one of {', '.join(_KINDS)}, got {kind!r}")
for key in ("anchor", "text"):
if not isinstance(raw.get(key), str) or not raw[key]:
raise OverrideError(f"{source}: edit needs a non-empty string {key!r}")
return Edit(kind=kind, anchor=raw["anchor"], text=raw["text"])
def _reject_duplicate_targets(records: list[OverrideRecord]) -> None:
seen: dict[str, Path | None] = {}
for record in records:
if record.label in seen:
raise OverrideError(f"two records target {record.label}: {seen[record.label]} and {record.source}")
seen[record.label] = record.source
@@ -1,61 +0,0 @@
"""Produce a deployable .vromfs.bin from the stock one plus our changes.
Two kinds of change go in:
- overrides: anchored edits to files that already exist in the stock archive
- added files: our own new files, which must not collide with a stock path
Everything is validated before any output is produced, so a failure leaves the caller
with an error and no half-built archive.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from ..vromfs import read_archive, write_archive
from .errors import BuildError, OverrideError
from .overrides import OverrideRecord, apply_edits
@dataclass
class ScriptArchiveReport:
archive: str
stock_file_count: int
overridden: list[str] = field(default_factory=list)
added: list[str] = field(default_factory=list)
@property
def summary(self) -> str:
return (f"{self.archive}: {self.stock_file_count} stock files, "
f"{len(self.overridden)} overridden, {len(self.added)} added")
def build_script_archive(
archive_name: str,
stock: bytes,
overrides: list[OverrideRecord],
added_files: dict[str, bytes],
) -> tuple[bytes, ScriptArchiveReport]:
archive = read_archive(stock)
report = ScriptArchiveReport(archive=archive_name, stock_file_count=len(archive.files))
for record in [item for item in overrides if item.archive == archive_name]:
archive.files[record.path] = _edited(archive.files, record)
report.overridden.append(record.path)
for path, content in sorted(added_files.items()):
if path in archive.files:
raise BuildError(f"{archive_name}: {path} already exists in the stock archive; use an override record")
archive.put(path, content)
report.added.append(path)
return write_archive(archive), report
def _edited(files: dict[str, bytes], record: OverrideRecord) -> bytes:
if record.path not in files:
raise OverrideError(f"{record.label}: the stock archive has no such file")
try:
text = files[record.path].decode("utf-8")
except UnicodeDecodeError as error:
raise OverrideError(f"{record.label}: stock file is not UTF-8 text, cannot apply text edits") from error
return apply_edits(text, record.edits, record.label).encode("utf-8")
-24
View File
@@ -1,24 +0,0 @@
"""Command line entry point for the development-side tools.
Each group of commands lives in its own module and registers itself here:
- exe_commands: check-patches, patch-exe
- build_commands: build-gui
- script_commands: build-script-checker, check-scripts
Run `wtotools <command> --help` for the arguments of one command.
"""
from __future__ import annotations
import argparse
from . import build_commands, exe_commands, script_commands
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="wtotools", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
for group in (exe_commands, build_commands, script_commands):
group.register(commands)
args = parser.parse_args(argv)
return args.handler(args)
-3
View File
@@ -1,3 +0,0 @@
from . import main
raise SystemExit(main())
-64
View File
@@ -1,64 +0,0 @@
"""Commands that produce deployable files.
wtotools build-gui --stock <gui.vromfs.bin> --out <gui.vromfs.bin> [--client client] [--force]
Inputs, all under the client folder:
- overrides/ edit records for stock files (see wtotools.build.overrides)
- gui/ our own files, laid out exactly as their path inside gui.vromfs.bin
The stock archive is only read. The output must be a different file, and an existing output
is replaced only with --force.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from ..build import BuildError, OverrideError, build_script_archive, load_overrides
from ..vromfs.errors import VromfsFormatError
GUI_ARCHIVE = "gui.vromfs.bin"
DEFAULT_CLIENT = Path("client")
def register(commands: argparse._SubParsersAction) -> None:
gui = commands.add_parser("build-gui", help="build gui.vromfs.bin from the stock one plus the client folder")
gui.add_argument("--stock", type=Path, required=True, help="the stock gui.vromfs.bin to read")
gui.add_argument("--out", type=Path, required=True, help="where to write the built archive")
gui.add_argument("--client", type=Path, default=DEFAULT_CLIENT, help="folder with overrides/ and gui/")
gui.add_argument("--force", action="store_true", help="overwrite an existing output file")
gui.set_defaults(handler=_build_gui)
def _build_gui(args: argparse.Namespace) -> int:
if args.out.resolve() == args.stock.resolve():
print("refusing to write over the stock archive; choose a different --out", file=sys.stderr)
return 2
if args.out.exists() and not args.force:
print(f"{args.out} already exists; pass --force to overwrite", file=sys.stderr)
return 2
try:
overrides = load_overrides(args.client / "overrides")
added = _added_files(args.client / "gui")
built, report = build_script_archive(GUI_ARCHIVE, args.stock.read_bytes(), overrides, added)
except (BuildError, OverrideError, VromfsFormatError) as error:
print(f"build failed, nothing was written: {error}", file=sys.stderr)
return 1
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_bytes(built)
print(report.summary)
for path in report.overridden:
print(f" edited {path}")
for path in report.added:
print(f" added {path}")
print(f"wrote {args.out}")
return 0
def _added_files(root: Path) -> dict[str, bytes]:
if not root.is_dir():
return {}
return {path.relative_to(root).as_posix(): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()}
-80
View File
@@ -1,80 +0,0 @@
"""Commands that work on the game executable.
wtotools check-patches --exe <aces.exe> [--patches exe-patches]
wtotools patch-exe --exe <aces.exe> --out <aces.exe> [--patches exe-patches] [--force]
The input executable is only ever read. `patch-exe` refuses to write over its input and
refuses an existing output unless --force is given, so it cannot modify a game install by
accident.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from ..exepatch import apply_writes, changed_ranges, load_patches, plan_patches
from ..exepatch.assemble import disagreement
from ..pe import PeImage
DEFAULT_PATCHES = Path("exe-patches")
def register(commands: argparse._SubParsersAction) -> None:
check = commands.add_parser("check-patches", help="locate and verify every patch, write nothing")
_add_common(check)
check.set_defaults(handler=_check_patches)
patch = commands.add_parser("patch-exe", help="apply every patch to a copy of the executable")
_add_common(patch)
patch.add_argument("--out", type=Path, required=True, help="where to write the patched copy")
patch.add_argument("--force", action="store_true", help="overwrite an existing output file")
patch.set_defaults(handler=_patch_exe)
def _add_common(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--exe", type=Path, required=True, help="the game executable to read")
parser.add_argument("--patches", type=Path, default=DEFAULT_PATCHES, help="patch definition directory")
def _check_patches(args: argparse.Namespace) -> int:
definitions = load_patches(args.patches)
print(f"{len(definitions)} patch definition(s) in {args.patches}")
mismatched = 0
for definition in definitions:
problem = disagreement(definition)
if problem:
mismatched += 1
print(f" assembly disagrees with stored bytes: {definition.identifier}: {problem}")
if not mismatched:
print(" every patch's assembly source compiles to its stored bytes")
plan = plan_patches(PeImage(args.exe.read_bytes()), definitions)
print(plan.describe())
return 0 if plan.complete and not mismatched else 1
def _patch_exe(args: argparse.Namespace) -> int:
if args.out.resolve() == args.exe.resolve():
print("refusing to write over the input executable; choose a different --out", file=sys.stderr)
return 2
if args.out.exists() and not args.force:
print(f"{args.out} already exists; pass --force to overwrite", file=sys.stderr)
return 2
original = args.exe.read_bytes()
plan = plan_patches(PeImage(original), load_patches(args.patches))
print(plan.describe())
if not plan.complete:
print("some patches are unavailable; nothing was written", file=sys.stderr)
return 1
patched = apply_writes(original, plan.writes)
for start, end in changed_ranges(original, patched):
print(f" changed {end - start} byte(s) at file offset {start:#x}: "
f"{original[start:end].hex()} -> {patched[start:end].hex()}")
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_bytes(patched)
print(f"wrote {args.out}")
return 0
-49
View File
@@ -1,49 +0,0 @@
"""Commands for syntax checking game scripts.
wtotools build-script-checker [--source build/quirrel-source] [--out build/quirrel-check]
wtotools check-scripts [--checker build/quirrel-check/sq.exe] <file or folder>...
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from ..scriptcheck import CheckerBuildError, build_checker, check_scripts, find_scripts
DEFAULT_SOURCE = Path("build/quirrel-source")
DEFAULT_OUT = Path("build/quirrel-check")
def register(commands: argparse._SubParsersAction) -> None:
build = commands.add_parser("build-script-checker", help="compile the Quirrel syntax checker with MSVC")
build.add_argument("--source", type=Path, default=DEFAULT_SOURCE, help="Quirrel source checkout")
build.add_argument("--out", type=Path, default=DEFAULT_OUT, help="where to put sq.exe")
build.set_defaults(handler=_build)
check = commands.add_parser("check-scripts", help="syntax-check .nut files")
check.add_argument("paths", type=Path, nargs="+", help=".nut files or folders containing them")
check.add_argument("--checker", type=Path, default=DEFAULT_OUT / "sq.exe", help="the compiled checker")
check.set_defaults(handler=_check)
def _build(args: argparse.Namespace) -> int:
try:
checker = build_checker(args.source, args.out)
except CheckerBuildError as error:
print(error, file=sys.stderr)
return 1
print(f"built {checker}")
return 0
def _check(args: argparse.Namespace) -> int:
if not args.checker.is_file():
print(f"checker not found at {args.checker}; run build-script-checker first", file=sys.stderr)
return 2
files = find_scripts(args.paths)
failures = check_scripts(args.checker, files)
for failure in failures:
print(f"FAIL {failure.path}\n {failure.message}")
print(f"{len(files) - len(failures)}/{len(files)} file(s) pass syntax and static checks")
return 1 if failures else 0
-31
View File
@@ -1,31 +0,0 @@
"""Locate and apply the declared changes to aces.exe.
The patches themselves live as data under exe-patches/; this package is only the engine.
Order of work, and the reason for it: find every site and verify every original byte first
(plan), then write (apply). A site that is missing or ambiguous is reported, never guessed,
so a game update produces a list of unavailable patches and the features they cover rather
than a broken executable.
`authoring` and `assemble` are development-side only: they need a disassembler and an
assembler, and are imported explicitly rather than from here.
"""
from .apply import apply_writes, changed_ranges
from .definition import PatchDefinition, PatchEdit, load_patches
from .errors import DefinitionError, LocateError, PatchError, VerifyError
from .plan import PatchFailure, PatchPlan, PlannedWrite, plan_patches
__all__ = [
"DefinitionError",
"LocateError",
"PatchDefinition",
"PatchEdit",
"PatchError",
"PatchFailure",
"PatchPlan",
"PlannedWrite",
"VerifyError",
"apply_writes",
"changed_ranges",
"load_patches",
"plan_patches",
]
-39
View File
@@ -1,39 +0,0 @@
"""Write a verified plan into a copy of the executable's bytes.
The expected original bytes are checked once more immediately before each write, so a plan
made against different bytes than it is applied to is refused instead of landing half
applied. The input is never modified; the patched bytes are returned.
"""
from __future__ import annotations
from .errors import VerifyError
from .plan import PlannedWrite
def apply_writes(data: bytes, writes: list[PlannedWrite]) -> bytes:
patched = bytearray(data)
for write in sorted(writes, key=lambda item: item.file_offset):
actual = bytes(patched[write.file_offset:write.end_offset])
if actual != write.expect_original:
raise VerifyError(
f"{write.patch_id}: bytes at file offset {write.file_offset:#x} are {actual.hex()}, "
f"expected {write.expect_original.hex()}; nothing was written")
patched[write.file_offset:write.end_offset] = write.payload
return bytes(patched)
def changed_ranges(original: bytes, patched: bytes) -> list[tuple[int, int]]:
"""Byte ranges that differ, for confirming a patched file changed only what was planned."""
if len(original) != len(patched):
raise VerifyError(f"size changed from {len(original)} to {len(patched)} bytes")
ranges: list[tuple[int, int]] = []
start = None
for index, (left, right) in enumerate(zip(original, patched)):
if left != right and start is None:
start = index
elif left == right and start is not None:
ranges.append((start, index))
start = None
if start is not None:
ranges.append((start, len(original)))
return ranges
-38
View File
@@ -1,38 +0,0 @@
"""Development-side helper: compile a patch's assembly source to machine code.
Patch definitions carry both the assembly source, which is what a reader should look at,
and the compiled bytes, which are what gets written. This module compiles the source so a
development-side check can prove the two agree; an installer only writes the stored bytes
and needs no assembler.
"""
from __future__ import annotations
from keystone import KS_ARCH_X86, KS_MODE_64, Ks, KsError
from .definition import PatchDefinition
from .errors import DefinitionError
_assembler = Ks(KS_ARCH_X86, KS_MODE_64)
def assemble(lines: tuple[str, ...] | list[str]) -> bytes:
"""Compile position-independent x86-64 assembly to bytes."""
source = "; ".join(line.strip() for line in lines if line.strip())
if not source:
raise DefinitionError("no assembly source to compile")
try:
encoding, _count = _assembler.asm(source)
except KsError as error:
raise DefinitionError(f"could not assemble {source!r}: {error}") from error
return bytes(encoding)
def disagreement(definition: PatchDefinition) -> str | None:
"""Why a definition's assembly source and stored bytes differ, or None if they agree."""
if not definition.edit.asm:
return "no assembly source recorded for the stored bytes"
compiled = assemble(definition.edit.asm)
if compiled != definition.edit.payload:
return (f"assembly compiles to {compiled.hex()} but the stored bytes are "
f"{definition.edit.payload.hex()}")
return None
-88
View File
@@ -1,88 +0,0 @@
"""Development-side helper: turn a known code range into a stored signature pattern.
This is where a disassembler is needed, so it is deliberately separate from the matching
code in locate/signature.py. Patterns produced here are committed into patch definitions;
an installer never runs this module.
Masking rule: keep the bytes that describe what the code does, wildcard the bytes that
hold an address. Those are the displacement of a rip-relative operand and the target of a
relative call or jump, both of which shift when unrelated code moves.
"""
from __future__ import annotations
from dataclasses import dataclass
from capstone import CS_ARCH_X86, CS_MODE_64, Cs
from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_REG_RIP
from .errors import DefinitionError
from .locate import signature
_disassembler = Cs(CS_ARCH_X86, CS_MODE_64)
_disassembler.detail = True
@dataclass(frozen=True)
class PatternDraft:
pattern: str
byte_length: int
instruction_count: int
hits: list[int]
@property
def unique(self) -> bool:
return len(self.hits) == 1
def build_pattern(image, rva: int, length: int) -> str:
"""Masked pattern for `length` bytes of code starting at `rva`."""
tokens: list[str] = []
consumed = 0
for instruction in _disassembler.disasm(image.read(rva, length), rva):
tokens.extend(_instruction_tokens(instruction))
consumed += instruction.size
if consumed == 0:
raise DefinitionError(f"could not disassemble any instruction at {rva:#x}")
return " ".join(tokens)
def draft_for_function(reference, target, rva: int, length: int | None = None) -> PatternDraft:
"""Build a pattern from `reference` at `rva` and report where it matches in `target`.
`length` defaults to the whole function containing `rva`, which is what makes a generic
function prologue identifiable; pass a smaller value when the function is very large.
"""
bounds = reference.function_containing(rva)
if length is None:
if bounds is None:
raise DefinitionError(f"{rva:#x} is not inside a known function; pass an explicit length")
length = bounds[1] - rva
pattern = build_pattern(reference, rva, length)
return PatternDraft(
pattern=pattern,
byte_length=signature.pattern_length(pattern),
instruction_count=sum(1 for _ in _disassembler.disasm(reference.read(rva, length), rva)),
hits=signature.locate(target, pattern=pattern),
)
def _instruction_tokens(instruction) -> list[str]:
raw = instruction.bytes
masked = bytearray(len(raw)) # 1 marks a wildcard
for start, size in _address_fields(instruction):
masked[start:start + size] = b"\1" * size
return [signature.WILDCARD if flag else f"{byte:02x}" for byte, flag in zip(raw, masked)]
def _address_fields(instruction) -> list[tuple[int, int]]:
fields = []
for operand in instruction.operands:
if operand.type == X86_OP_MEM and operand.mem.base == X86_REG_RIP:
fields.append((instruction.disp_offset, instruction.disp_size))
elif operand.type == X86_OP_IMM and _is_relative_branch(instruction):
fields.append((instruction.imm_offset, instruction.imm_size))
return [(start, size) for start, size in fields if size]
def _is_relative_branch(instruction) -> bool:
return instruction.mnemonic == "call" or instruction.mnemonic.startswith("j")
-133
View File
@@ -1,133 +0,0 @@
"""Patch definitions as they are stored on disk.
One directory per change to the program's behaviour, under exe-patches/<domain>/<name>/:
patch.json what the program does now, what it does after the patch, why the
executable has to change at all, which features depend on it, and the
bytes to write
locate.json how to find the site, and how that was established
The engine reads these; it holds no knowledge about any particular patch. Keeping the
definitions as data is what lets the installer report exactly which changes did not apply
and which features are affected.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from pathlib import Path
from .errors import DefinitionError
PATCH_FILE = "patch.json"
LOCATE_FILE = "locate.json"
@dataclass(frozen=True)
class PatchEdit:
"""Bytes to write, and the bytes that must already be there."""
offset: int
payload: bytes
expect_original: bytes
asm: tuple[str, ...]
def __post_init__(self) -> None:
if len(self.payload) != len(self.expect_original):
raise DefinitionError(
f"payload is {len(self.payload)} bytes but expect_original is "
f"{len(self.expect_original)}; they must cover the same bytes")
@dataclass(frozen=True)
class PatchDefinition:
identifier: str
title: str
features: tuple[str, ...]
requires: tuple[str, ...]
edit: PatchEdit
locate: dict
directory: Path | None = None
notes: dict = field(default_factory=dict)
@property
def locate_method(self) -> str:
return str(self.locate.get("method", ""))
def load_patches(root: Path) -> list[PatchDefinition]:
"""Read every patch definition under `root`, sorted by identifier."""
definitions = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))]
_reject_duplicate_ids(definitions)
_reject_unknown_requirements(definitions)
return sorted(definitions, key=lambda item: item.identifier)
def _read(directory: Path) -> PatchDefinition:
patch = _read_json(directory / PATCH_FILE)
locate = _read_json(directory / LOCATE_FILE)
for key in ("id", "title", "edit"):
if key not in patch:
raise DefinitionError(f"{directory / PATCH_FILE}: missing key {key!r}")
if "method" not in locate:
raise DefinitionError(f"{directory / LOCATE_FILE}: missing key 'method'")
return PatchDefinition(
identifier=str(patch["id"]),
title=str(patch["title"]),
features=tuple(str(item) for item in patch.get("features", ())),
requires=tuple(str(item) for item in patch.get("requires", ())),
edit=_read_edit(directory, patch["edit"]),
locate=locate,
directory=directory,
notes={key: value for key, value in patch.items()
if key not in ("id", "title", "features", "requires", "edit")},
)
def _read_edit(directory: Path, raw: object) -> PatchEdit:
if not isinstance(raw, dict):
raise DefinitionError(f"{directory / PATCH_FILE}: 'edit' must be an object")
for key in ("bytes", "expect_original"):
if not isinstance(raw.get(key), str):
raise DefinitionError(f"{directory / PATCH_FILE}: edit needs a hex string {key!r}")
return PatchEdit(
offset=int(raw.get("offset", 0)),
payload=_hex(directory, "bytes", raw["bytes"]),
expect_original=_hex(directory, "expect_original", raw["expect_original"]),
asm=tuple(str(line) for line in raw.get("asm", ())),
)
def _hex(directory: Path, key: str, text: str) -> bytes:
try:
return bytes.fromhex(text)
except ValueError as error:
raise DefinitionError(f"{directory / PATCH_FILE}: {key} is not valid hex: {text!r}") from error
def _read_json(path: Path) -> dict:
if not path.is_file():
raise DefinitionError(f"{path}: file not found")
try:
data = json.loads(path.read_text("utf-8"))
except json.JSONDecodeError as error:
raise DefinitionError(f"{path}: invalid JSON: {error}") from error
if not isinstance(data, dict):
raise DefinitionError(f"{path}: expected a JSON object")
return data
def _reject_duplicate_ids(definitions: list[PatchDefinition]) -> None:
seen: dict[str, Path | None] = {}
for definition in definitions:
if definition.identifier in seen:
raise DefinitionError(f"two definitions use id {definition.identifier!r}: "
f"{seen[definition.identifier]} and {definition.directory}")
seen[definition.identifier] = definition.directory
def _reject_unknown_requirements(definitions: list[PatchDefinition]) -> None:
known = {definition.identifier for definition in definitions}
for definition in definitions:
unknown = [item for item in definition.requires if item not in known]
if unknown:
raise DefinitionError(f"{definition.identifier} requires unknown patch(es): {', '.join(unknown)}")
-22
View File
@@ -1,22 +0,0 @@
class PatchError(Exception):
"""A patch cannot be applied, so nothing was written."""
class DefinitionError(PatchError):
"""A patch definition on disk is malformed."""
class LocateError(PatchError):
"""A patch site could not be found, or was found in more than one place.
The caller reports which patches are affected and which features depend on them;
it never falls back to a guessed address.
"""
class VerifyError(PatchError):
"""The bytes at a located site are not what the definition expects.
Either the game version differs more than the signature could detect, or the
executable is already patched.
"""
@@ -1,27 +0,0 @@
"""Ways to find a patch site in an executable.
One method per module, each exposing `locate(image, spec) -> list[int]` returning the
RVAs it matched. A method never picks a winner among several matches; the caller
requires exactly one and refuses otherwise.
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from ..errors import DefinitionError
from . import signature
Locator = Callable[..., list[int]]
_METHODS: Mapping[str, Locator] = {
signature.METHOD: signature.locate,
}
def method(name: str) -> Locator:
if name not in _METHODS:
raise DefinitionError(f"unknown locate method {name!r}; known methods: {', '.join(sorted(_METHODS))}")
return _METHODS[name]
__all__ = ["Locator", "method", "signature"]
@@ -1,57 +0,0 @@
"""Find a patch site by scanning for a byte pattern with wildcards.
A pattern is a hex string where "??" stands for any byte, for example:
"41 57 41 56 48 81 ec ?? ?? ?? ??"
Wildcards cover the bytes that legitimately differ between builds: addresses inside
rip-relative operands and the targets of relative calls and jumps. What is left is the
shape of the code, which is what identifies the function across versions.
This module only matches patterns; it needs no disassembler, which is why it is the part
that runs on the player's machine. Patterns are generated once on the development side
(see authoring.py) and stored in the patch definition.
"""
from __future__ import annotations
import re
from ..errors import DefinitionError
METHOD = "signature"
WILDCARD = "??"
def locate(image, *, pattern: str, section: str = ".text", limit: int = 8, **_unused) -> list[int]:
"""RVAs in `section` where `pattern` matches, at most `limit` of them."""
expression = compile_pattern(pattern)
data = image.section_bytes(section)
base = image.section(section).rva
hits = []
for match in expression.finditer(data):
hits.append(base + match.start())
if len(hits) >= limit:
break
return hits
def compile_pattern(pattern: str) -> re.Pattern[bytes]:
return re.compile(b"".join(_token_to_regex(token) for token in _tokens(pattern)), re.DOTALL)
def pattern_length(pattern: str) -> int:
return len(_tokens(pattern))
def _tokens(pattern: str) -> list[str]:
tokens = pattern.split()
if not tokens:
raise DefinitionError("signature pattern is empty")
for token in tokens:
if token != WILDCARD and not re.fullmatch(r"[0-9a-fA-F]{2}", token):
raise DefinitionError(f"signature pattern token must be a hex byte or {WILDCARD!r}, got {token!r}")
return tokens
def _token_to_regex(token: str) -> bytes:
return b"." if token == WILDCARD else re.escape(bytes.fromhex(token))
-121
View File
@@ -1,121 +0,0 @@
"""Work out every write first, then let the caller decide whether to apply it.
Planning does three things per patch: find the site, require that it was found in exactly
one place, and check that the bytes there are the ones the definition expects. A patch
that fails any of these produces a PatchFailure with a reason instead of a write, and so
does any patch that depends on it. Nothing is written during planning.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .definition import PatchDefinition
from .errors import DefinitionError, LocateError, PatchError, VerifyError
from .locate import method as locate_method
@dataclass(frozen=True)
class PlannedWrite:
patch_id: str
rva: int
file_offset: int
payload: bytes
expect_original: bytes
@property
def end_offset(self) -> int:
return self.file_offset + len(self.payload)
@dataclass(frozen=True)
class PatchFailure:
patch_id: str
features: tuple[str, ...]
reason: str
@dataclass
class PatchPlan:
writes: list[PlannedWrite] = field(default_factory=list)
failures: list[PatchFailure] = field(default_factory=list)
@property
def complete(self) -> bool:
return not self.failures
@property
def affected_features(self) -> list[str]:
return sorted({feature for failure in self.failures for feature in failure.features})
def describe(self) -> str:
lines = [f"{len(self.writes)} patch(es) ready, {len(self.failures)} unavailable"]
lines += [f" ready {write.patch_id} at {write.rva:#x}" for write in self.writes]
lines += [f" FAILED {failure.patch_id}: {failure.reason}" for failure in self.failures]
if self.failures:
lines.append(f" features affected: {', '.join(self.affected_features) or 'none recorded'}")
return "\n".join(lines)
def plan_patches(image, definitions: list[PatchDefinition]) -> PatchPlan:
plan = PatchPlan()
failed: dict[str, str] = {}
for definition in definitions:
try:
plan.writes.append(_plan_one(image, definition))
except PatchError as error:
failed[definition.identifier] = str(error)
_propagate_failures(definitions, failed)
for definition in definitions:
if definition.identifier in failed:
plan.writes = [write for write in plan.writes if write.patch_id != definition.identifier]
plan.failures.append(PatchFailure(definition.identifier, definition.features, failed[definition.identifier]))
_reject_overlaps(plan.writes)
return plan
def _plan_one(image, definition: PatchDefinition) -> PlannedWrite:
spec = {key: value for key, value in definition.locate.items() if key != "method"}
hits = locate_method(definition.locate_method)(image, **spec)
if not hits:
raise LocateError("site not found; this game build differs from the verified ones, "
"or the executable is already patched")
if len(hits) > 1:
raise LocateError(f"site found in {len(hits)} places, so it is ambiguous: "
f"{', '.join(hex(hit) for hit in hits)}")
rva = hits[0] + definition.edit.offset
file_offset = image.file_offset(rva)
actual = image.read(rva, len(definition.edit.expect_original))
if actual != definition.edit.expect_original:
raise VerifyError(
f"bytes at {rva:#x} are {actual.hex()}, expected {definition.edit.expect_original.hex()}"
" (different game build, or already patched)")
return PlannedWrite(definition.identifier, rva, file_offset,
definition.edit.payload, definition.edit.expect_original)
def _propagate_failures(definitions: list[PatchDefinition], failed: dict[str, str]) -> None:
"""A patch whose prerequisite is unavailable cannot be applied either."""
requirements = {definition.identifier: definition.requires for definition in definitions}
changed = True
while changed:
changed = False
for identifier, requires in requirements.items():
if identifier in failed:
continue
blocking = [item for item in requires if item in failed]
if blocking:
failed[identifier] = f"depends on unavailable patch(es): {', '.join(blocking)}"
changed = True
def _reject_overlaps(writes: list[PlannedWrite]) -> None:
for earlier, later in zip(sorted(writes, key=lambda w: w.file_offset),
sorted(writes, key=lambda w: w.file_offset)[1:]):
if later.file_offset < earlier.end_offset:
raise DefinitionError(
f"{earlier.patch_id} and {later.patch_id} write overlapping bytes at "
f"{earlier.rva:#x} and {later.rva:#x}")
-4
View File
@@ -1,4 +0,0 @@
"""Read-only view of a PE executable."""
from .image import PeImage, Section
__all__ = ["PeImage", "Section"]
-77
View File
@@ -1,77 +0,0 @@
"""Address mapping, sections and function ranges of a PE image held in memory.
Addresses are RVAs (relative to the image base) unless a name says otherwise.
The view never modifies the bytes it was built from.
"""
from __future__ import annotations
import bisect
import struct
from dataclasses import dataclass
from functools import cached_property
import pefile
_EXCEPTION_DIRECTORY = 3
@dataclass(frozen=True)
class Section:
name: str
rva: int
virtual_size: int
raw_offset: int
raw_size: int
def contains_rva(self, rva: int) -> bool:
return self.rva <= rva < self.rva + max(self.virtual_size, self.raw_size)
class PeImage:
def __init__(self, data: bytes):
self.data = data
self._pe = pefile.PE(data=data, fast_load=True)
self.image_base = self._pe.OPTIONAL_HEADER.ImageBase
self.sections = [
Section(s.Name.rstrip(b"\0").decode(), s.VirtualAddress, s.Misc_VirtualSize, s.PointerToRawData, s.SizeOfRawData)
for s in self._pe.sections
]
def section(self, name: str) -> Section:
for section in self.sections:
if section.name == name:
return section
raise KeyError(f"no section {name}")
def section_of(self, rva: int) -> Section:
for section in self.sections:
if section.contains_rva(rva):
return section
raise ValueError(f"RVA {rva:#x} is outside every section")
def file_offset(self, rva: int) -> int:
section = self.section_of(rva)
if rva - section.rva >= section.raw_size:
raise ValueError(f"RVA {rva:#x} has no file bytes (uninitialised data)")
return rva - section.rva + section.raw_offset
def read(self, rva: int, size: int) -> bytes:
offset = self.file_offset(rva)
return self.data[offset:offset + size]
def section_bytes(self, name: str) -> bytes:
section = self.section(name)
return self.data[section.raw_offset:section.raw_offset + min(section.virtual_size, section.raw_size)]
@cached_property
def functions(self) -> list[tuple[int, int]]:
"""(begin, end) RVA pairs from the exception directory, sorted by begin."""
directory = self._pe.OPTIONAL_HEADER.DATA_DIRECTORY[_EXCEPTION_DIRECTORY]
raw = self.read(directory.VirtualAddress, directory.Size)
return sorted((begin, end) for begin, end, _unwind in struct.iter_unpack("<III", raw))
def function_containing(self, rva: int) -> tuple[int, int] | None:
index = bisect.bisect_right(self.functions, (rva, 1 << 32)) - 1
if index >= 0 and self.functions[index][0] <= rva < self.functions[index][1]:
return self.functions[index]
return None
@@ -1,14 +0,0 @@
"""Syntax checking for game scripts (.nut), development side only.
The game's script language is Quirrel. We compile the upstream Quirrel command line tool
once and run it in `-syntax-check` mode, which parses a file to a syntax tree without
resolving imports, so our scripts can be checked without the game's native modules.
Modules:
- build: compile the checker from a Quirrel source checkout with MSVC
- check: run the checker over script files and collect the failures
"""
from .build import CheckerBuildError, build_checker
from .check import ScriptFailure, check_scripts, find_scripts
__all__ = ["CheckerBuildError", "ScriptFailure", "build_checker", "check_scripts", "find_scripts"]
-84
View File
@@ -1,84 +0,0 @@
"""Compile the Quirrel command line tool (`sq`) from a source checkout.
The source list is read from the checkout's own CMakeLists.txt files, so a newer Quirrel
checkout builds without editing this file. CMake itself is not needed: MSVC's `cl` is
driven directly through a response file.
The checkout is expected at build/quirrel-source (git-ignored); docs/implementation notes records
which commit it is pinned to.
"""
from __future__ import annotations
import re
import subprocess
from pathlib import Path
DEFAULT_VCVARS = Path("C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvars64.bat")
CHECKER_NAME = "sq.exe"
# (folder, CMake variable) pairs whose files make up the command line tool.
_SOURCE_LISTS = (
("squirrel", "SQUIRREL_SRC"),
("squirrel/compiler", "COMPILER_SRC"),
("sqstdlib", "SQSTDLIB_SRC"),
("sqmodules", "SQMODULES_SRC"),
)
# Chosen by an if() in CMake rather than listed: we build without variable tracing.
_EXTRA_SOURCES = ("squirrel/vartracestub.cpp", "sq/sq.cpp", "sq/sq_test_natives.cpp")
_INCLUDE_DIRS = ("include", "internal", "squirrel", "squirrel/compiler", "helpers", "sqrat/include", "sqmodules", ".")
_FLAGS = (
"/nologo", "/utf-8", "/EHsc", "/std:c++17", "/O1", "/MP",
"/D_SQ64", "/DSQ_VAR_TRACE_ENABLED=0", "/D_CRT_SECURE_NO_WARNINGS",
"/wd4244", "/wd4018", "/wd4267",
)
class CheckerBuildError(Exception):
pass
def build_checker(source: Path, out_dir: Path, vcvars: Path = DEFAULT_VCVARS) -> Path:
"""Compile `sq.exe` into `out_dir` and return its path. Raises CheckerBuildError."""
if not vcvars.is_file():
raise CheckerBuildError(f"MSVC environment script not found: {vcvars}")
sources = collect_sources(source)
out_dir.mkdir(parents=True, exist_ok=True)
response = out_dir / "sources.rsp"
response.write_text("\n".join(_response_lines(source, sources)) + "\n", encoding="utf-8")
# A single string, not a list: cmd.exe needs the inner quotes verbatim, and /s makes it
# strip only the outermost pair.
command = f'cmd /d /s /c "call "{vcvars}" >nul && cl @sources.rsp"'
completed = subprocess.run(command, cwd=out_dir, capture_output=True, text=True)
checker = out_dir / CHECKER_NAME
if completed.returncode != 0 or not checker.is_file():
tail = "\n".join((completed.stdout + completed.stderr).splitlines()[-30:])
raise CheckerBuildError(f"compiling the checker failed (exit {completed.returncode}):\n{tail}")
return checker
def collect_sources(source: Path) -> list[Path]:
files: list[Path] = []
for folder, variable in _SOURCE_LISTS:
files.extend(_cmake_list(source / folder, variable))
files.extend(source / item for item in _EXTRA_SOURCES)
missing = [path for path in files if not path.is_file()]
if missing:
raise CheckerBuildError(f"source checkout is incomplete, missing: {', '.join(map(str, missing[:5]))}")
return files
def _cmake_list(folder: Path, variable: str) -> list[Path]:
cmake = folder / "CMakeLists.txt"
if not cmake.is_file():
raise CheckerBuildError(f"not a Quirrel source checkout: {cmake} is missing")
match = re.search(rf"set\({variable}\s+([^)]*)\)", cmake.read_text("utf-8"))
if match is None:
raise CheckerBuildError(f"{cmake} does not define {variable}")
return [folder / name for name in match[1].split()]
def _response_lines(source: Path, sources: list[Path]) -> list[str]:
includes = [f'/I"{(source / item).resolve()}"' for item in _INCLUDE_DIRS]
files = [f'"{path.resolve()}"' for path in sources]
return [*_FLAGS, *includes, *files, f"/Fe:{CHECKER_NAME}"]
-46
View File
@@ -1,46 +0,0 @@
"""Run the Quirrel syntax checker over script files.
Each file is parsed and run through Quirrel's static analyzer (`-syntax-check -sa`), in its
own process so a failure is attributed to exactly one file and one bad file cannot hide the
others. Analyzer warnings (unused bindings, suspicious expressions) count as failures: the
files we check are our own, and we keep them clean.
Not covered: names that are not defined anywhere. Quirrel reports those only when it fully
compiles a file, and full compilation resolves imports, which needs the game's native modules.
"""
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class ScriptFailure:
path: Path
message: str
def check_scripts(checker: Path, files: list[Path]) -> list[ScriptFailure]:
"""Return one ScriptFailure per file that does not parse; an empty list means all passed."""
failures: list[ScriptFailure] = []
for path in files:
completed = subprocess.run([str(checker), "-syntax-check", "-sa", str(path)], capture_output=True, text=True)
output = (completed.stderr + completed.stdout).strip()
if completed.returncode != 0 or _reports_problem(output):
failures.append(ScriptFailure(path, output or f"exit code {completed.returncode}"))
return failures
def _reports_problem(output: str) -> bool:
# sq.exe exits with 0 even when parsing fails; it then prints "Error [...]" on stderr.
# Analyzer findings start with "WARNING:".
return any(line.startswith(("Error [", "WARNING:")) for line in output.splitlines())
def find_scripts(roots: list[Path]) -> list[Path]:
"""Expand directories into the .nut files under them; files are taken as given."""
found: list[Path] = []
for root in roots:
found.extend(sorted(root.rglob("*.nut")) if root.is_dir() else [root])
return found
-13
View File
@@ -1,13 +0,0 @@
"""Read and write .vromfs.bin archives.
A .vromfs.bin file has two layers:
- container (container.py): header, zstd compression with a small XOR obfuscation,
an MD5 of the inner image, and a 256-byte signature tail;
- image (image.py): the file table (names, offsets, optional SHA-1 digests) and file data.
archive.py ties them together; most callers only need `read_archive` / `write_archive`.
"""
from .archive import Archive, read_archive, write_archive
from .errors import VromfsFormatError
__all__ = ["Archive", "VromfsFormatError", "read_archive", "write_archive"]
-33
View File
@@ -1,33 +0,0 @@
"""High-level archive access: read a .vromfs.bin, change files, write it back."""
from __future__ import annotations
from dataclasses import dataclass, field
from .container import ContainerInfo, build_container, parse_container
from .errors import VromfsFormatError
from .image import ImageLayout, build_image, parse_image
@dataclass
class Archive:
container: ContainerInfo
layout: ImageLayout
files: dict[str, bytes] = field(default_factory=dict)
def put(self, path: str, content: bytes) -> None:
"""Add or replace a file. The game lower-cases lookup paths, so stored paths must be lower case."""
if path != path.lower():
raise VromfsFormatError(f"archive paths must be lower case: {path}")
if path.startswith("/") or "\\" in path:
raise VromfsFormatError(f"archive paths are relative and use '/': {path}")
self.files[path] = content
def read_archive(data: bytes) -> Archive:
container, image = parse_container(data)
layout, files = parse_image(image)
return Archive(container, layout, files)
def write_archive(archive: Archive) -> bytes:
return build_container(archive.container, build_image(archive.layout, archive.files))
-128
View File
@@ -1,128 +0,0 @@
"""Outer layer of a .vromfs.bin file.
Layout:
header 16 bytes: magic (VRFs | VRFx), platform, unpacked size, packed word
ext header 8 bytes, only for VRFx: size (=8), flags, version (stored reversed)
payload compressed (zstd, obfuscated) or plain image bytes
digest 16-byte MD5 of the unpacked image, absent for the "no check" pack type
signature 0 or 256 trailing bytes
The packed word is little-endian: top 6 bits are the pack type, low 26 bits the packed size.
"""
from __future__ import annotations
import hashlib
import struct
from dataclasses import dataclass
from enum import Enum
import zstandard
from . import obfuscation
from .errors import VromfsFormatError
SIGNATURE_SIZE = 0x100
_HEADER = struct.Struct("<4s4sII")
_EXT_HEADER = struct.Struct("<HH4s")
class Magic(Enum):
VRFS = b"VRFs"
VRFX = b"VRFx"
class PackType(Enum):
ZSTD_NO_CHECK = 0x10
PLAIN = 0x20
ZSTD = 0x30
@property
def compressed(self) -> bool:
return self is not PackType.PLAIN
@property
def checked(self) -> bool:
return self is not PackType.ZSTD_NO_CHECK
@dataclass(frozen=True)
class ContainerInfo:
"""Everything about the container except the image itself; reused when writing back."""
magic: Magic
platform: bytes
pack_type: PackType
ext_flags: int | None
version: tuple[int, int, int, int] | None
signature: bytes
def parse_container(data: bytes) -> tuple[ContainerInfo, bytes]:
"""Return the container description and the unpacked inner image."""
if len(data) < _HEADER.size:
raise VromfsFormatError("file too short for a container header")
magic_raw, platform, unpacked_size, packed_word = _HEADER.unpack_from(data, 0)
try:
magic = Magic(magic_raw)
pack_type = PackType(packed_word >> 26)
except ValueError as error:
raise VromfsFormatError(f"unknown container header: {error}") from error
packed_size = packed_word & 0x03FF_FFFF
cursor = _HEADER.size
ext_flags = version = None
if magic is Magic.VRFX:
ext_size, ext_flags, version_raw = _EXT_HEADER.unpack_from(data, cursor)
if ext_size != _EXT_HEADER.size:
raise VromfsFormatError(f"unexpected extended header size {ext_size}")
version = tuple(reversed(version_raw))
cursor += _EXT_HEADER.size
stored_size = packed_size if pack_type.compressed else unpacked_size
stored = data[cursor:cursor + stored_size]
cursor += stored_size
image = _unpack_payload(stored, pack_type, unpacked_size)
if pack_type.checked:
digest = data[cursor:cursor + 16]
cursor += 16
if hashlib.md5(image).digest() != digest:
raise VromfsFormatError("image MD5 does not match the container digest")
signature = data[cursor:]
if len(signature) not in (0, SIGNATURE_SIZE):
raise VromfsFormatError(f"unexpected trailing data of {len(signature)} bytes")
info = ContainerInfo(magic, platform, pack_type, ext_flags, version, signature)
return info, image
def build_container(info: ContainerInfo, image: bytes) -> bytes:
"""Pack an inner image using the same container settings it was read with."""
stored = _pack_payload(image, info.pack_type)
packed_size = len(stored) if info.pack_type.compressed else 0
if packed_size > 0x03FF_FFFF:
raise VromfsFormatError("compressed payload too large for the 26-bit size field")
parts = [_HEADER.pack(info.magic.value, info.platform, len(image), (info.pack_type.value << 26) | packed_size)]
if info.magic is Magic.VRFX:
parts.append(_EXT_HEADER.pack(_EXT_HEADER.size, info.ext_flags or 0, bytes(reversed(info.version))))
parts.append(stored)
if info.pack_type.checked:
parts.append(hashlib.md5(image).digest())
parts.append(info.signature)
return b"".join(parts)
def _unpack_payload(stored: bytes, pack_type: PackType, unpacked_size: int) -> bytes:
if not pack_type.compressed:
return stored
compressed = obfuscation.toggle(stored)
image = zstandard.ZstdDecompressor().decompress(compressed, max_output_size=unpacked_size)
if len(image) != unpacked_size:
raise VromfsFormatError(f"image is {len(image)} bytes, header says {unpacked_size}")
return image
def _pack_payload(image: bytes, pack_type: PackType) -> bytes:
if not pack_type.compressed:
return image
compressed = zstandard.ZstdCompressor(level=9, write_content_size=True).compress(image)
return obfuscation.toggle(compressed)
-2
View File
@@ -1,2 +0,0 @@
class VromfsFormatError(ValueError):
"""The bytes are not a .vromfs.bin archive this tool understands, or an edit would make it invalid."""
-124
View File
@@ -1,124 +0,0 @@
"""Inner image of a .vromfs.bin: the file table and file data.
Layout (every block aligned to 16 bytes):
0x00 names header: u32 offset of the name-offset table, u32 file count
0x10 data header: u32 offset of the data table, u32 file count
0x20 digest header: u64 end, u16 begin (only when names offset == 0x30)
name offsets: count x u64, each pointing at a NUL-terminated path
names
data table: count x 16 bytes: u32 offset, u32 size, 8 bytes padding
digests: count x 20-byte SHA-1 (only when digest begin != 0)
file data
The game binary-searches the full path bytes, so entries are sorted by their UTF-8
bytes, with the special name-map file "nm" (stored as b"\\xff?nm") last.
"""
from __future__ import annotations
import hashlib
import struct
from dataclasses import dataclass
from .errors import VromfsFormatError
NAME_MAP_PATH = "nm"
_NAME_MAP_STORED = b"\xff?nm"
_ALIGN = 16
_PAIR = struct.Struct("<II")
_DIGEST_HEADER = struct.Struct("<QH")
_DIGEST_SIZE = 20
@dataclass(frozen=True)
class ImageLayout:
"""Optional features of the file table, kept so a rewritten image matches the original."""
has_digest_header: bool
has_digests: bool
def parse_image(image: bytes) -> tuple[ImageLayout, dict[str, bytes]]:
names_offset, count = _PAIR.unpack_from(image, 0x00)
data_offset, data_count = _PAIR.unpack_from(image, 0x10)
if count != data_count:
raise VromfsFormatError(f"name count {count} differs from data count {data_count}")
has_digest_header = names_offset == 0x30
digests_begin = _DIGEST_HEADER.unpack_from(image, 0x20)[1] if has_digest_header else 0
paths = [_read_name(image, offset) for offset in struct.unpack_from(f"<{count}Q", image, names_offset)]
files: dict[str, bytes] = {}
for index, path in enumerate(paths):
offset, size = _PAIR.unpack_from(image, data_offset + index * _ALIGN)
content = image[offset:offset + size]
if digests_begin:
expected = image[digests_begin + index * _DIGEST_SIZE:digests_begin + (index + 1) * _DIGEST_SIZE]
if hashlib.sha1(content).digest() != expected:
raise VromfsFormatError(f"SHA-1 mismatch for {path}")
files[path] = content
return ImageLayout(has_digest_header, bool(digests_begin)), files
def build_image(layout: ImageLayout, files: dict[str, bytes]) -> bytes:
if layout.has_digests and not layout.has_digest_header:
raise VromfsFormatError("digests require the digest header")
paths = sorted_paths(files)
count = len(paths)
names_offset = 0x30 if layout.has_digest_header else 0x20
names_blob, name_offsets = _build_names(paths, names_offset + _aligned(8 * count))
data_table_offset = names_offset + _aligned(8 * count) + len(names_blob)
digests_offset = data_table_offset + _ALIGN * count
first_data_offset = digests_offset + (_aligned(_DIGEST_SIZE * count) if layout.has_digests else 0)
data_blob, data_entries = _build_data(paths, files, first_data_offset)
out = bytearray(first_data_offset)
_PAIR.pack_into(out, 0x00, names_offset, count)
_PAIR.pack_into(out, 0x10, data_table_offset, count)
if layout.has_digest_header:
begin, end = (digests_offset, digests_offset + _DIGEST_SIZE * count) if layout.has_digests else (0, first_data_offset)
_DIGEST_HEADER.pack_into(out, 0x20, end, begin)
struct.pack_into(f"<{count}Q", out, names_offset, *name_offsets)
out[names_offset + _aligned(8 * count):data_table_offset] = names_blob
for index, (offset, size) in enumerate(data_entries):
_PAIR.pack_into(out, data_table_offset + index * _ALIGN, offset, size)
if layout.has_digests:
for index, path in enumerate(paths):
out[digests_offset + index * _DIGEST_SIZE:digests_offset + (index + 1) * _DIGEST_SIZE] = hashlib.sha1(files[path]).digest()
return bytes(out) + data_blob
def sorted_paths(files: dict[str, bytes]) -> list[str]:
"""File order the game expects: byte-wise path order, name map last."""
paths = sorted((path for path in files if path != NAME_MAP_PATH), key=lambda path: path.encode("utf-8"))
if NAME_MAP_PATH in files:
paths.append(NAME_MAP_PATH)
return paths
def _read_name(image: bytes, offset: int) -> str:
raw = image[offset:image.index(b"\0", offset)]
return NAME_MAP_PATH if raw == _NAME_MAP_STORED else raw.decode("utf-8")
def _build_names(paths: list[str], base: int) -> tuple[bytes, list[int]]:
blob = bytearray()
offsets = []
for path in paths:
offsets.append(base + len(blob))
blob += (_NAME_MAP_STORED if path == NAME_MAP_PATH else path.encode("utf-8")) + b"\0"
blob += bytes(_aligned(len(blob)) - len(blob))
return bytes(blob), offsets
def _build_data(paths: list[str], files: dict[str, bytes], base: int) -> tuple[bytes, list[tuple[int, int]]]:
blob = bytearray()
entries = []
for path in paths:
content = files[path]
entries.append((base + len(blob), len(content)))
blob += content + bytes(_aligned(len(content)) - len(content))
return bytes(blob), entries
def _aligned(size: int) -> int:
return (size + _ALIGN - 1) & ~(_ALIGN - 1)
-27
View File
@@ -1,27 +0,0 @@
"""XOR obfuscation applied to the compressed payload of a container.
The first 16 bytes are XORed with a fixed key; if the payload is at least 32 bytes long,
the 16 bytes ending at the last 4-byte boundary are XORed with the same key words in
reverse order. The operation is its own inverse.
"""
_KEY_WORDS = tuple(bytes.fromhex(word) for word in ("55aa55aa", "0ff00ff0", "55aa55aa", "48124812"))
_HEAD_KEY = b"".join(_KEY_WORDS)
_TAIL_KEY = b"".join(reversed(_KEY_WORDS))
_SIZE_MASK = 0x03FF_FFFF
def _xor_into(buffer: bytearray, start: int, key: bytes) -> None:
for index, key_byte in enumerate(key):
buffer[start + index] ^= key_byte
def toggle(payload: bytes) -> bytes:
"""Obfuscate or de-obfuscate (same operation) a compressed payload."""
buffer = bytearray(payload)
size = len(buffer) & _SIZE_MASK
if size >= 16:
_xor_into(buffer, 0, _HEAD_KEY)
if size >= 32:
_xor_into(buffer, (size & 0x03FF_FFFC) - 16, _TAIL_KEY)
return bytes(buffer)