build(repo): restore build tools and define the workspace layout

Restore the reviewed pack, PE, and patch tooling. Specify a TypeScript
build pipeline, a type-preserving BLK codec, and a configurable loopback
port selected at launch. Document the package boundaries.
This commit is contained in:
N0VAN0M4LY committed 2026-11-24 00:19:04 +08:00
1 parent 7b6d8973d1
commit 89aa5198c3
25 files changed
+1155

No files matched your search

+2
View File
@@ -8,3 +8,5 @@
| 目录 | 内容 |
|---|---|
| `tools/` | Python 工具:数据包读写、exe 补丁引擎 |
| `exe-patches/` | exe 补丁定义 |
@@ -0,0 +1,14 @@
{
"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 ??"
}
@@ -0,0 +1,42 @@
{
"id": "startup/skip-resource-archive-signature-check",
"title": "让资源包签名校验直接返回通过",
"program_behaviour": {
"stock": "挂载 .vromfs.bin 资源包时,程序调用一个函数校验包尾的 256 字节签名。返回 0(不合法)时,调用方跳到失败分支,这个包不会被挂载。",
"patched": "这个校验函数一进去就返回「通过」,不再读取签名。"
},
"derivation": {
"requirement": "功能清单 A「离线启动」。服务地址写在 char.vromfs.bin 的 config/network.blk 里(implementation notes),要把它们指向本地服务,就要重新打包这个数据包。",
"cause": "签名用 Gaijin 的私钥生成,我们无法为重新打包的内容生成有效签名。校验失败是运行时的硬拦截:包不会被挂载。",
"lighter_options_ruled_out": [
"原生自带:校验在挂载路径上无条件执行,没有跳过它的配置项。",
"本地服务:不适用。程序挂载本地数据包时不联网。",
"客户端脚本:不适用。脚本本身也在数据包里,而且挂载发生在脚本运行之前。"
],
"conclusion": "只能改 exe。",
"if_not_applied": "重新打包的 char.vromfs.bin 不会被挂载,客户端拿不到指向本地服务的地址。"
},
"why_this_site": [
"校验函数的返回值直接控制流程:调用方是 call、test al,al、je 失败分支。让函数立即返回 1,就等于「签名通过」。",
"改函数入口只需要 3 字节、一个位置;改调用点要动 3 处。改一处更小、更稳。",
"打了补丁后这个函数不再调用任何东西,是个立即返回的叶子函数,所以不需要补异常展开信息。"
],
"features": ["A-离线启动"],
"requires": [],
"evidence": [
"2.61.0.37 原版 aces.exe:校验函数 0x4073d30 在挂载路径上无条件调用,返回 0 时调用方跳到失败分支。",
"已在 2.61.0.37 上实测:打补丁后,重新打包的数据包可以正常挂载。"
],
"verified_on": ["2.61.0.37"],
"edit": {
"offset": 0,
"asm": ["mov al, 1", "ret"],
"bytes": "b001c3",
"expect_original": "415741"
}
}
+21
View File
@@ -0,0 +1,21 @@
[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 project: game data packs (vromfs) and exe patches."
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
@@ -0,0 +1,7 @@
"""Tools for the War Thunder offline rewrite.
Subpackages:
- vromfs: read and write the game's .vromfs.bin data packs
- pe: read-only view of a PE executable (address mapping, sections, functions)
- exepatch: locate and apply declarative exe patches from the exe-patches/ tree
"""
+22
View File
@@ -0,0 +1,22 @@
"""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
Run `wtotools <command> --help` for the arguments of one command.
"""
from __future__ import annotations
import argparse
from . import exe_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,):
group.register(commands)
args = parser.parse_args(argv)
return args.handler(args)
+3
View File
@@ -0,0 +1,3 @@
from . import main
raise SystemExit(main())
+80
View File
@@ -0,0 +1,80 @@
"""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
+31
View File
@@ -0,0 +1,31 @@
"""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
@@ -0,0 +1,39 @@
"""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
@@ -0,0 +1,38 @@
"""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
@@ -0,0 +1,88 @@
"""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
@@ -0,0 +1,133 @@
"""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
@@ -0,0 +1,22 @@
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.
"""
@@ -0,0 +1,27 @@
"""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"]
@@ -0,0 +1,57 @@
"""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
@@ -0,0 +1,121 @@
"""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
@@ -0,0 +1,4 @@
"""Read-only view of a PE executable."""
from .image import PeImage, Section
__all__ = ["PeImage", "Section"]
+77
View File
@@ -0,0 +1,77 @@
"""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
+13
View File
@@ -0,0 +1,13 @@
"""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
@@ -0,0 +1,33 @@
"""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
@@ -0,0 +1,128 @@
"""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
@@ -0,0 +1,2 @@
class VromfsFormatError(ValueError):
"""The bytes are not a .vromfs.bin archive this tool understands, or an edit would make it invalid."""
+124
View File
@@ -0,0 +1,124 @@
"""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
@@ -0,0 +1,27 @@
"""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)