Files
WoW-Hybrid-gateway/ops/chrraces_hotfix_language.py
2026-11-23 03:28:32 +02:00

165 lines
7.5 KiB
Python

#!/usr/bin/env python3
"""Apply the reviewed two-byte ChrRaces language fix to a compact hotfix header.
The selected enUS ChrRaces DB2 already has this correction. The native codec's
ChrRaces hotfix rows must agree, or those rows mask the corrected CASC data.
This tool preserves every other record and recomputes the content-derived push
identities before a codec is built. It never starts or edits a game client.
"""
import argparse
import hashlib
import json
import re
import struct
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_HEADER = ROOT / "include/gateway/item_sparse_compat.hpp"
TABLE = 0x53F1783C
ROWS = {
9: (9597319, 190, 7, 1), # Goblin: Common -> Orcish
10: (9597509, 307, 1, 7), # Blood Elf / Octo High Elf: Orcish -> Common
}
BASE_LANGUAGE_TRAILING_FIELDS = 17 # schema fields 34..50 are uint8
PAGE_FIRST = 81920
PAGE_COUNT = 4096
OCTAL_LINE_BYTES = 64
LITERAL_LINE_BYTES = 2 + 4 * OCTAL_LINE_BYTES + 1 # quotes, escapes, newline
RECORD = re.compile(rb"\{(0x[0-9A-Fa-f]+),(\d+),(?:\{PayloadBlob\+(\d+),(\d+)\}|\{\},2)\}")
PUSH = re.compile(rb"\{(\d+),(\d+),(\d+)\}")
def digest_identity(records, blob, begin=0, end=None):
selected = records[begin:end]
removed = any(row[4] == 2 for row in selected)
identity = bytearray(b"GW-HOTFIX-STATUS-1\0" if removed else b"")
for table, record_id, offset, length, status in selected:
identity.extend(struct.pack("<IIB" if removed else "<II", table, record_id, status)
if removed else struct.pack("<II", table, record_id))
if status == 1:
identity.extend(blob[offset:offset + length])
result = int.from_bytes(hashlib.sha256(identity).digest()[:4], "little") & 0x7fffffff
if not result:
raise ValueError("Zero content identity")
return result
def inspect_header(raw):
marker = b"inline constexpr uint8_t PayloadBlob[]=\n"
payload_at = raw.index(marker) + len(marker)
payload_end = raw.index(b";\nstruct Record", payload_at)
literal_lines = raw[payload_at:payload_end].splitlines()
blob = bytearray()
for line in literal_lines:
if len(line) not in (2 + 4 * OCTAL_LINE_BYTES,):
# Only the final literal may contain fewer than 64 bytes.
if line != literal_lines[-1] or len(line) < 2 or (len(line) - 2) % 4:
raise ValueError("Compact payload literal shape changed")
if not line.startswith(b'"') or not line.endswith(b'"'):
raise ValueError("Compact payload literal shape changed")
body = line[1:-1]
if any(body[i:i + 1] != b"\\" for i in range(0, len(body), 4)):
raise ValueError("Expected fixed-width octal literals")
blob.extend(int(body[i + 1:i + 4], 8) for i in range(0, len(body), 4))
record_at = raw.index(b"inline constexpr Record Records[]={", payload_end)
record_end = raw.index(b";\n", record_at)
record_text = raw[record_at:record_end]
records = []
for match in RECORD.finditer(record_text):
table = int(match[1], 16)
record_id = int(match[2])
status = 1 if match[3] else 2
offset = int(match[3] or 0)
length = int(match[4] or 0)
if offset + length > len(blob):
raise ValueError("Record exceeds compact payload")
records.append((table, record_id, offset, length, status))
if len(records) < PAGE_FIRST + PAGE_COUNT:
raise ValueError("Incomplete hotfix registry")
push_match = re.search(rb"inline constexpr int32_t PushID=(\d+);", raw[:payload_at])
if not push_match:
raise ValueError("Root push identity absent")
page_at = raw.index(b"inline constexpr Push Pushes[]={", record_end)
page_end = raw.index(b";\n", page_at)
pages = [(int(m[1]), int(m[2]), int(m[3])) for m in PUSH.finditer(raw[page_at:page_end])]
page = next((p for p in pages if p[1:] == (PAGE_FIRST, PAGE_COUNT)), None)
if page is None:
raise ValueError("ChrRaces page ownership changed")
root_id = int(push_match[1])
if root_id != digest_identity(records, blob):
raise ValueError("Existing root identity disagrees with all record bytes")
if page[0] != digest_identity(records, blob, PAGE_FIRST, PAGE_FIRST + PAGE_COUNT):
raise ValueError("Existing ChrRaces page identity disagrees with its records")
for race, (offset, length, _before, _after) in ROWS.items():
hits = [row for row in records if row[0] == TABLE and row[1] == race]
if hits != [(TABLE, race, offset, length, 1)]:
raise ValueError(f"ChrRaces row {race} identity or location changed")
return payload_at, blob, records, root_id, page[0]
def correct_header(raw):
payload_at, blob, records, old_root, old_page = inspect_header(raw)
fixed = bytearray(raw)
changed = []
for race, (offset, length, before, after) in ROWS.items():
field_offset = offset + length - BASE_LANGUAGE_TRAILING_FIELDS
if blob[field_offset] == after:
continue
if blob[field_offset] != before:
raise ValueError(f"ChrRaces {race} BaseLanguage has an unknown value")
literal_at = payload_at + (field_offset // OCTAL_LINE_BYTES) * LITERAL_LINE_BYTES
literal_at += 1 + (field_offset % OCTAL_LINE_BYTES) * 4
before_octal = f"\\{before:03o}".encode()
after_octal = f"\\{after:03o}".encode()
if fixed[literal_at:literal_at + 4] != before_octal:
raise ValueError("Compact literal offset does not match row byte")
fixed[literal_at:literal_at + 4] = after_octal
blob[field_offset] = after
changed.append((race, field_offset, before, after))
if not changed:
return raw, {"changed": [], "root_push_id": old_root, "page_push_id": old_page}
if [r[0] for r in changed] != [9, 10]:
raise ValueError("Partial ChrRaces correction")
new_root = digest_identity(records, blob)
new_page = digest_identity(records, blob, PAGE_FIRST, PAGE_FIRST + PAGE_COUNT)
new = bytes(fixed)
replacements = (
(f"inline constexpr int32_t PushID={old_root};".encode(),
f"inline constexpr int32_t PushID={new_root};".encode()),
(f"{{{old_page},{PAGE_FIRST},{PAGE_COUNT}}}".encode(),
f"{{{new_page},{PAGE_FIRST},{PAGE_COUNT}}}".encode()),
)
for old, replacement in replacements:
if new.count(old) != 1:
raise ValueError("Push identity replacement not unique")
new = new.replace(old, replacement, 1)
# Parse the entire result so the two rows and both derived identities agree.
inspect_header(new)
return new, {"changed": changed, "old_root_push_id": old_root,
"root_push_id": new_root, "old_page_push_id": old_page,
"page_push_id": new_page}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--header", type=Path, default=DEFAULT_HEADER)
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
before = args.header.read_bytes()
after, result = correct_header(before)
result.update(header=str(args.header), before_sha256=hashlib.sha256(before).hexdigest(),
after_sha256=hashlib.sha256(after).hexdigest(), applied=False)
if args.apply and after != before:
temporary = args.header.with_name(args.header.name + ".chrraces-tmp")
if temporary.exists():
raise FileExistsError(temporary)
temporary.write_bytes(after)
temporary.replace(args.header)
result["applied"] = True
print(json.dumps(result, separators=(",", ":")))
if __name__ == "__main__":
main()