#!/usr/bin/env python3
"""Check a dump's uds UCP files and write a stub for any that are missing or invalid.
usage: make_ucp_stub.py DUMP [--config-id N] [--dry-run]
DUMP is the app folder containing sce_sys. Each NPWR id in sce_sys/uds/npbind.dat
(falling back to sce_sys/trophy2/npbind.dat) maps to sce_sys/uds/uds<NN>.ucp by
its index. A UCP passes if the container, digest, member set and every
npCommunicationId are good; otherwise it is replaced by a stub, and an invalid
existing file is kept as uds<NN>.ucp.bak.
Container: 0x60-byte header, 0x40-byte entry per member, member data 16-byte
aligned.
"""
import argparse
import hashlib
import json
import shutil
import struct
import sys
from pathlib import Path
MAGIC = 0xB228C60A
NPBIND_MAGIC = 0xD294A018
HEADER, ENTRY, ALIGN = 0x60, 0x40, 0x10
# Always write all four members. You've been warned.
ORDER = ["enum_definition.json", "events_definition.json",
"stats_definition.json", "stats_extraction.json"]
HAS_ID = ("enum_definition.json", "stats_definition.json", "stats_extraction.json")
def member_docs(npwr, config_id):
base = {"schemaVersion": "1.1", "npCommunicationId": npwr}
return {
"enum_definition.json": {**base, "enumDefinitionRevision": 1, "enumArray": []},
"events_definition.json": {"configurationId": config_id, "events": [],
"nextOffset": 0, "previousOffset": 0, "totalItemCount": 0},
"stats_definition.json": {**base, "statsDefinitionRevision": 1, "statDefinitionArray": []},
"stats_extraction.json": {**base, "statsExtractionRevision": 1, "statsExtractionRuleArray": []},
}
def pad(n):
# real files add a full 16 bytes after members that are already aligned
return ALIGN - n % ALIGN
def digest(data):
zeroed = bytearray(data)
zeroed[0x1C:0x30] = bytes(20)
return hashlib.sha1(zeroed).digest()
def pack(members):
"""members: [(name, bytes)] -> UCP bytes with a valid header digest."""
table_end = HEADER + ENTRY * len(members)
offsets, at = [], table_end
for _, body in members:
offsets.append(at)
at += len(body) + pad(len(body))
out = bytearray(at)
struct.pack_into(">IIQIII", out, 0, MAGIC, 1, at, len(members), ENTRY, 0)
for i, ((name, body), off) in enumerate(zip(members, offsets)):
entry = HEADER + i * ENTRY
out[entry:entry + len(name)] = name.encode()
struct.pack_into(">QQ", out, entry + 0x20, off, len(body))
out[off:off + len(body)] = body
out[0x1C:0x30] = hashlib.sha1(out).digest()
return bytes(out)
def unpack(data):
"""Parse the container, raising ValueError on structural problems."""
if len(data) < HEADER:
raise ValueError(f"{len(data)} bytes, shorter than the {HEADER:#x}-byte header")
magic, version, size = struct.unpack_from(">IIQ", data, 0)
count, entry_size = struct.unpack_from(">II", data, 0x10)
if magic != MAGIC:
raise ValueError(f"bad magic {magic:#010x}")
if version == 0:
raise ValueError("version is 0")
if size != len(data):
raise ValueError(f"size field {size} != file size {len(data)}")
if entry_size != ENTRY:
raise ValueError(f"entry size {entry_size:#x}, expected {ENTRY:#x}")
if HEADER + count * ENTRY > len(data):
raise ValueError(f"{count} entries do not fit in the file")
members = []
for i in range(count):
entry = HEADER + i * ENTRY
name = data[entry:entry + 0x20].split(b"\0")[0].decode("latin1")
off, length = struct.unpack_from(">QQ", data, entry + 0x20)
if off > len(data) or off + length > len(data):
raise ValueError(f"member {name!r} runs past the end of the file")
members.append((name, data[off:off + length]))
return members
def validate(data, npwr):
"""Return a list of problems; empty means the UCP is acceptable."""
try:
members = unpack(data)
except ValueError as err:
return [str(err)]
problems = []
if digest(data) != data[0x1C:0x30]:
problems.append(f"digest is {data[0x1C:0x30].hex()}, should be {digest(data).hex()}")
names = [n for n, _ in members]
missing = [n for n in ORDER if n not in names]
if missing:
problems.append("missing members: " + ", ".join(missing))
for name, body in members:
if name not in HAS_ID:
continue
try:
found = json.loads(body).get("npCommunicationId")
except (ValueError, AttributeError) as err:
problems.append(f"{name} is not valid JSON ({err})")
continue
if found != npwr:
problems.append(f"{name} npCommunicationId is {found!r}, npbind says {npwr!r}")
return problems
def npbind_ids(path):
"""NPWR ids in npbind.dat, in index order."""
data = path.read_bytes()
if len(data) < 0x80 or struct.unpack_from(">I", data, 0)[0] != NPBIND_MAGIC:
raise ValueError(f"{path}: not an npbind.dat")
entry_size, = struct.unpack_from(">I", data, 0x14)
count, = struct.unpack_from(">I", data, 0x1C)
if entry_size == 0 or 0x80 + count * entry_size > len(data):
raise ValueError(f"{path}: {count} entries of {entry_size:#x} bytes do not fit")
ids = []
for i in range(count):
base = 0x80 + i * entry_size
at, end = base, base + entry_size
while at + 4 <= end:
tag, length = struct.unpack_from(">HH", data, at)
if tag == 0:
break
if tag == 0x10:
ids.append(data[at + 4:at + 4 + length].split(b"\0")[0].decode("ascii"))
break
at += 4 + length
else:
raise ValueError(f"{path}: entry {i} has no NPWR id")
return ids
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("dump", type=Path)
ap.add_argument("--config-id", type=int, default=54474)
ap.add_argument("--dry-run", action="store_true", help="report only, write nothing")
args = ap.parse_args()
sce_sys = args.dump / "sce_sys"
npbind = next((p for p in (sce_sys / "uds" / "npbind.dat", sce_sys / "trophy2" / "npbind.dat")
if p.is_file()), None)
if npbind is None:
sys.exit(f"{sce_sys}: no uds/npbind.dat or trophy2/npbind.dat")
try:
ids = npbind_ids(npbind)
except ValueError as err:
sys.exit(str(err))
if not ids:
sys.exit(f"{npbind}: lists no NPWR ids")
status = 0
for index, npwr in enumerate(ids):
ucp = sce_sys / "uds" / f"uds{index:02d}.ucp"
if ucp.is_file():
problems = validate(ucp.read_bytes(), npwr)
if not problems:
print(f"{ucp}: valid for {npwr}, nothing to do")
continue
reason = "invalid: " + "; ".join(problems)
else:
reason = "missing"
print(f"{ucp}: {reason}")
if args.dry_run:
print(f" would write a stub for {npwr}")
status = 1
continue
docs = member_docs(npwr, args.config_id)
stub = pack([(n, json.dumps(docs[n], separators=(", ", ": ")).encode()) for n in ORDER])
ucp.parent.mkdir(parents=True, exist_ok=True)
if ucp.is_file():
backup = ucp.with_suffix(".ucp.bak")
if not backup.exists():
shutil.copy2(ucp, backup)
ucp.write_bytes(stub)
print(f" wrote stub for {npwr} ({len(stub)} bytes)")
sys.exit(status)
if __name__ == "__main__":
main()